🤯 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): clarify ambiguous goals before work starts (#20143)
Arvin Xu07e591368b78
diff --git a/apps/server/src/routers/lambda/goal.ts b/apps/server/src/routers/lambda/goal.tsindex 0bc5c45f82e..d1cd34b39c8 100644--- a/apps/server/src/routers/lambda/goal.ts+++ b/apps/server/src/routers/lambda/goal.ts@@ -371,6 +371,39 @@ export const goalRouter = router({},),+ /**+ * Answer a goal's clarification round at once. One advance follows all the+ * answers, so the re-plan never starts with half of them.+ */+ answerClarifications: goalWriteProcedure+ .input(+ idInput.extend({+ answers: z+ .array(+ z.object({+ decisionId: z.string().uuid(),+ optionId: z.string(),+ resolution: z.string().optional(),+ }),+ )+ .min(1),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ try {+ await ctx.goalService.answerClarifications(input.id, input.answers);+ await scheduleGoalAdvance({+ goalId: input.id,+ trigger: 'decide',+ userId: ctx.userId,+ workspaceId: ctx.workspaceId ?? undefined,+ });+ return { message: 'Clarifications answered', success: true };+ } catch (error) {+ mapGoalError(error, 'answer clarifications for');+ }+ }),+decide: goalWriteProcedure.input(idInput.extend({@@ -521,6 +554,15 @@ export const goalRouter = router({}}),+ /** Clarifications still waiting on the user, grouped by goal. */+ pendingClarifications: goalProcedure.query(async ({ ctx }) => {+ try {+ return { data: await ctx.goalService.pendingClarifications(), success: true };+ } catch (error) {+ mapGoalError(error, 'list clarifications for');+ }+ }),+graph: goalProcedure.input(idInput).query(async ({ ctx, input }) => {try {return { data: await ctx.goalService.graph(input.id), success: true };diff --git a/apps/server/src/services/goal/criteriaGenerator.test.ts b/apps/server/src/services/goal/criteriaGenerator.test.tsindex 424d446a5e4..007efd0e613 100644--- a/apps/server/src/services/goal/criteriaGenerator.test.ts+++ b/apps/server/src/services/goal/criteriaGenerator.test.ts@@ -58,14 +58,17 @@ describe('GoalCriteriaGeneratorService', () => {],};generateObject.mockResolvedValueOnce(draft);- await expect(service.decompose({ requirement: 'Upgrade office editing' })).resolves.toEqual(- draft,- );+ // An answer without the understanding fields still plans, as a clear goal.+ await expect(service.decompose({ requirement: 'Upgrade office editing' })).resolves.toEqual({+ ...draft,+ assumptions: [],+ questions: [],+ });expect(generateObject).toHaveBeenLastCalledWith(expect.objectContaining({ schema: expect.objectContaining({ name: 'goal_decomposition' }) }),expect.objectContaining({tracing: {- promptVersion: 'v5',+ promptVersion: 'v6',scenario: 'goal_decompose',schemaName: 'goal_decomposition',},diff --git a/apps/server/src/services/goal/criteriaGenerator.ts b/apps/server/src/services/goal/criteriaGenerator.tsindex 36743a1a344..8981d4c2722 100644--- a/apps/server/src/services/goal/criteriaGenerator.ts+++ b/apps/server/src/services/goal/criteriaGenerator.ts@@ -1,6 +1,7 @@import { TRACING_SCENARIOS } from '@lobechat/const';import { isProgrammaticTestCheck } from '@lobechat/const/verify';import type { TracingOptions } from '@lobechat/llm-generation-tracing';+import type { GoalClarificationAnswer } from '@lobechat/prompts';import {chainGoalCriteriaDraft,chainGoalDecompose,@@ -69,7 +70,24 @@ export interface GoalPlanDraft {}const decompositionSchema = z.object({+ /** Readings the plan relies on that the goal did not state. */+ assumptions: z.array(z.string()).default([]),problemStatement: z.string().min(1),+ /**+ * What the planner could not determine and would change the deliverable.+ * Defaulted so an older answer without the field still plans.+ */+ questions: z+ .array(+ z.object({+ assumption: z.string(),+ blocking: z.boolean(),+ impact: z.string().optional(),+ options: z.array(z.string()).default([]),+ question: z.string(),+ }),+ )+ .default([]),tasks: z.array(z.object({@@ -89,7 +107,7 @@ const decompositionSchema = z.object({.max(5),});-export type GoalDecompositionDraft = z.infer<typeof decompositionSchema>;+export type GoalDecompositionDraft = z.input<typeof decompositionSchema>;export class GoalCriteriaGeneratorService {constructor(@@ -152,7 +170,10 @@ export class GoalCriteriaGeneratorService {* any model/schema failure so the coordinator can fall back to a single* task seeded from the raw requirement instead of stalling the goal.*/- async decompose(params: { requirement: string }): Promise<GoalDecompositionDraft | undefined> {+ async decompose(params: {+ clarifications?: GoalClarificationAnswer[];+ requirement: string;+ }): Promise<GoalDecompositionDraft | undefined> {const modelConfig = await resolveGoalModelConfig(this.db, this.userId);const ai = new AiGenerationService(this.db, this.userId, this.workspaceId);const raw = await ai.generateObject(diff --git a/apps/server/src/services/goal/index.test.ts b/apps/server/src/services/goal/index.test.tsindex f5a906f2bf9..a31d0081cf8 100644--- a/apps/server/src/services/goal/index.test.ts+++ b/apps/server/src/services/goal/index.test.ts@@ -1279,6 +1279,253 @@ describe('GoalService', () => {expect(after.edges.filter((e) => e.kind === 'depends_on')).toHaveLength(1);});+ it('asks a blocking question before planning, then plans once with the answer', async () => {+ const planner = vi+ .spyOn(GoalCriteriaGeneratorService.prototype, 'decompose')+ .mockResolvedValue({+ assumptions: ['报告用中文'],+ problemStatement: '为新功能写一份发布说明',+ questions: [+ {+ assumption: '面向终端用户',+ blocking: true,+ impact: '决定写产品说明还是 API 变更',+ options: ['终端用户', '开发者'],+ question: '这份说明给谁看?',+ },+ ],+ tasks: [{ dependsOn: [], hypothesis: null, instruction: '写说明', title: '撰写' }],+ });+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ title: 'Release notes' });++ // The first plan asks instead of creating Tasks on a guess.+ expect((await service.tick(graph.goal.id)).outcome).toBe('advanced');+ let after = await service.graph(graph.goal.id);+ expect(after.nodes.filter((n) => n.kind === 'task')).toHaveLength(0);+ const problem = after.nodes.find((n) => n.kind === 'problem')!;+ expect(Number(problem.confidence)).toBe(0.3);+ expect(after.goal.config?.understanding).toMatchObject({+ assumptions: ['报告用中文'],+ level: 'low',+ });+ const [decision] = after.decisions;+ expect(decision).toMatchObject({ question: '这份说明给谁看?', status: 'pending' });+ expect(decision.options?.map((option) => option.id)).toEqual([+ 'option-1',+ 'option-2',+ 'assume',+ 'answer',+ ]);+ expect(after.edges).toContainEqual(+ expect.objectContaining({+ kind: 'leads_to',+ sourceNodeId: problem.id,+ targetNodeId: decision.nodeId,+ }),+ );++ // The open question parks the goal on the ordinary decision gate.+ expect((await service.tick(graph.goal.id)).outcome).toBe('waiting_human');+ expect((await service.graph(graph.goal.id)).goal.status).toBe('review');++ // An empty free-text answer is refused rather than re-planning on nothing.+ await expect(service.decide(graph.goal.id, decision.id, 'answer', ' ')).rejects.toThrow(+ 'This answer needs a note',+ );+ await service.decide(graph.goal.id, decision.id, 'option-2', '只关心 SDK');++ // The re-plan receives the answer and, even though the planner still+ // reports a blocking question, proceeds on assumptions: one round only.+ expect((await service.tick(graph.goal.id)).outcome).toBe('advanced');+ expect(planner).toHaveBeenLastCalledWith({+ clarifications: [{ answer: '开发者 (只关心 SDK)', question: '这份说明给谁看?' }],+ requirement: expect.any(String),+ });+ after = await service.graph(graph.goal.id);+ expect(after.nodes.filter((n) => n.kind === 'task').map((n) => n.title)).toEqual(['撰写']);+ expect(after.decisions.filter((d) => d.status === 'pending')).toHaveLength(0);+ expect(Number(after.nodes.find((n) => n.kind === 'problem')!.confidence)).toBe(0.6);+ // The re-asked question was answered, so its fallback never becomes an+ // assumption that contradicts the answer.+ expect(after.goal.config?.understanding).toMatchObject({+ assumptions: ['报告用中文'],+ level: 'medium',+ });+ });++ it('lists a clarification round for other surfaces and answers it in one go', async () => {+ const planner = vi+ .spyOn(GoalCriteriaGeneratorService.prototype, 'decompose')+ .mockResolvedValue({+ assumptions: [],+ problemStatement: '写发布说明',+ questions: [+ {+ assumption: '终端用户',+ blocking: true,+ impact: '决定语气',+ options: ['终端用户', '开发者'],+ question: '给谁看?',+ },+ { assumption: '更新日志', blocking: true, options: [], question: '发在哪里?' },+ ],+ tasks: [{ dependsOn: [], hypothesis: null, instruction: '写', title: '撰写' }],+ });+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ requirement: '为新功能写一份发布说明',+ title: 'Release notes',+ });+ await service.tick(graph.goal.id);++ const pending = await service.pendingClarifications();+ expect(pending).toEqual([+ expect.objectContaining({+ goalId: graph.goal.id,+ questions: expect.arrayContaining([+ expect.objectContaining({ description: '决定语气', question: '给谁看?' }),+ expect.objectContaining({ description: null, question: '发在哪里?' }),+ ]),+ // The requirement says which goal this is away from its own page.+ requirement: '为新功能写一份发布说明',+ title: 'Release notes',+ }),+ ]);++ // A paused goal keeps its questions but stops asking them elsewhere.+ await service.pause(graph.goal.id);+ expect(await service.pendingClarifications()).toEqual([]);+ await service.resume(graph.goal.id);+ expect(await service.pendingClarifications()).toHaveLength(1);++ const audience = pending[0].questions.find((q) => q.question === '给谁看?')!;+ const place = pending[0].questions.find((q) => q.question === '发在哪里?')!;+ await service.answerClarifications(graph.goal.id, [+ { decisionId: audience.decisionId, optionId: 'option-2', resolution: '只关心 SDK' },+ { decisionId: place.decisionId, optionId: 'answer', resolution: 'GitHub Release' },+ ]);++ expect(await service.pendingClarifications()).toEqual([]);+ expect((await service.graph(graph.goal.id)).goal.status).toBe('running');+ // One re-plan, carrying both answers.+ await service.tick(graph.goal.id);+ const [lastCall] = planner.mock.calls.at(-1)!;+ expect(lastCall.clarifications).toHaveLength(2);+ expect(lastCall.clarifications).toEqual(+ expect.arrayContaining([+ { answer: '开发者 (只关心 SDK)', question: '给谁看?' },+ { answer: 'GitHub Release', question: '发在哪里?' },+ ]),+ );+ });++ it('writes none of a clarification round when one answer is invalid, and retries cleanly', async () => {+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({+ assumptions: [],+ problemStatement: '写发布说明',+ questions: [+ {+ assumption: '终端用户',+ blocking: true,+ options: ['终端用户', '开发者'],+ question: '给谁看?',+ },+ { assumption: '更新日志', blocking: true, options: [], question: '发在哪里?' },+ ],+ tasks: [{ dependsOn: [], hypothesis: null, instruction: '写', title: '撰写' }],+ });+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ title: 'Release notes' });+ await service.tick(graph.goal.id);+ const [{ questions }] = await service.pendingClarifications();+ const audience = questions.find((q) => q.question === '给谁看?')!;+ const place = questions.find((q) => q.question === '发在哪里?')!;++ // The second answer is invalid, so the first must not be written either.+ await expect(+ service.answerClarifications(graph.goal.id, [+ { decisionId: audience.decisionId, optionId: 'option-2' },+ { decisionId: place.decisionId, optionId: 'no-such-option' },+ ]),+ ).rejects.toThrow('Unknown decision option');+ expect((await service.pendingClarifications())[0].questions).toHaveLength(2);++ // A retry after a partial write succeeds: the recorded answer is skipped.+ await service.decide(graph.goal.id, audience.decisionId, 'option-2');+ await service.answerClarifications(graph.goal.id, [+ { decisionId: audience.decisionId, optionId: 'option-2' },+ { decisionId: place.decisionId, optionId: 'assume' },+ ]);+ expect(await service.pendingClarifications()).toEqual([]);+ });++ it('keeps the answers in the fallback task when the re-plan fails', async () => {+ const planner = vi+ .spyOn(GoalCriteriaGeneratorService.prototype, 'decompose')+ .mockResolvedValue({+ assumptions: [],+ problemStatement: '写发布说明',+ questions: [+ {+ assumption: '终端用户',+ blocking: true,+ options: ['终端用户', '开发者'],+ question: '给谁看?',+ },+ ],+ tasks: [{ dependsOn: [], hypothesis: null, instruction: '写', title: '撰写' }],+ });+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ problemDescription: '写一份发布说明,必须附上迁移指南',+ requirement: '写一份发布说明,必须附上迁移指南',+ title: 'Release notes',+ });+ await service.tick(graph.goal.id);+ // Asking commits no tasks, so the user's own words stay on the problem.+ expect(+ (await service.graph(graph.goal.id)).nodes.find((n) => n.kind === 'problem')!.description,+ ).toBe('写一份发布说明,必须附上迁移指南');+ const [{ questions }] = await service.pendingClarifications();+ await service.answerClarifications(graph.goal.id, [+ { decisionId: questions[0].decisionId, optionId: 'option-2', resolution: '只关心 SDK' },+ ]);++ planner.mockRejectedValueOnce(new Error('planner down'));+ await service.tick(graph.goal.id);++ const task = (await service.graph(graph.goal.id)).nodes.find((n) => n.kind === 'task');+ // The original request's constraint survives, not the planner's summary.+ expect(task!.description).toContain('必须附上迁移指南');+ expect(task!.description).toContain('Q: 给谁看?');+ expect(task!.description).toContain('A: 开发者 (只关心 SDK)');+ });++ it('keeps the coordinator understanding when the user edits the goal policy', async () => {+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({+ assumptions: ['只修 P0'],+ problemStatement: '修 bug',+ questions: [],+ tasks: [{ dependsOn: [], hypothesis: null, instruction: '修', title: '修复' }],+ });+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ title: 'Fix' });+ await service.tick(graph.goal.id);++ // A policy editor sends its whole (stale) config snapshot back.+ await new GoalModel(serverDB, userId).update(graph.goal.id, {+ config: { maxConcurrentTasks: 2 },+ });++ const after = await service.graph(graph.goal.id);+ expect(after.goal.config?.maxConcurrentTasks).toBe(2);+ expect(after.goal.config?.understanding).toMatchObject({+ assumptions: ['只修 P0'],+ level: 'medium',+ });+ });+it('plans the decomposition once when two advances race through the planner', async () => {// The queued kickoff and the client's fire-and-forget fallback can both// reach plan_decomposition together; the atomic planning claim must stopdiff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.tsindex 1186cf99ed2..9bcb6229e27 100644--- a/apps/server/src/services/goal/index.ts+++ b/apps/server/src/services/goal/index.ts@@ -1,9 +1,14 @@import type { GoalAdvanceEffect, GoalMetricCriteriaState } from '@lobechat/agent-tracing';import { buildGoalRequirement } from '@lobechat/builtin-tool-goal';-import { GOAL_COORDINATOR_ACTOR_ID } from '@lobechat/const/goal';+import {+ GOAL_CLARIFICATION_OPTION,+ GOAL_CLARIFICATION_TITLE,+ GOAL_COORDINATOR_ACTOR_ID,+} from '@lobechat/const/goal';import type {GoalConfig,GoalCreateConfig,+ GoalDecisionOption,GoalEdgeKind,GoalGraphNode,GoalGraphSnapshot,@@ -78,6 +83,13 @@ import {toFrontierTaskState,toTraceGraphState,} from './traceObservation';+import {+ clarificationOptions,+ collectClarificationAnswers,+ hasAskedClarification,+ normalizeUnderstanding,+ UNDERSTANDING_CONFIDENCE,+} from './understanding';const TASK_NODE_CLAIM_TTL_MS = 5 * 60 * 1000;const TASK_DESCRIPTION_MAX_LENGTH = 255;@@ -1398,6 +1410,11 @@ export class GoalService {if (decision.options?.length && !decision.options.some((option) => option.id === optionId)) {throw new TRPCError({ code: 'BAD_REQUEST', message: 'Unknown decision option' });}+ // The note *is* the answer for this option; an empty one would re-plan the+ // goal on nothing and the question could never be asked again.+ if (optionId === GOAL_CLARIFICATION_OPTION.answer && !resolution?.trim()) {+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'This answer needs a note' });+ }const resolved = await this.graphModel.resolveDecision(goalId,decisionId,@@ -1439,6 +1456,83 @@ export class GoalService {return resolved;};+ /**+ * Answer a goal's clarification round in one go. Each answer resolves like a+ * single `decide`; the caller schedules one advance afterwards, so the+ * re-plan sees every answer instead of running after the first.+ */+ answerClarifications = async (+ goalId: string,+ answers: Array<{ decisionId: string; optionId: string; resolution?: string }>,+ ) => {+ const graph = await this.requireGraph(goalId);+ const decisions = new Map(graph.decisions.map((decision) => [decision.id, decision]));++ // Check the whole round before writing any of it: one bad answer used to+ // leave the ones before it resolved, and the client's retry then failed on+ // those. An answer already recorded as given is a retry, not a conflict.+ const toResolve = answers.filter((answer) => {+ const decision = decisions.get(answer.decisionId);+ if (!decision) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Pending decision not found' });+ }+ if (decision.status === 'resolved' && decision.resolvedOptionId === answer.optionId) {+ return false;+ }+ if (decision.status !== 'pending') {+ throw new TRPCError({ code: 'CONFLICT', message: 'Decision was already resolved' });+ }+ if (decision.options?.length && !decision.options.some((o) => o.id === answer.optionId)) {+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Unknown decision option' });+ }+ if (answer.optionId === GOAL_CLARIFICATION_OPTION.answer && !answer.resolution?.trim()) {+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'This answer needs a note' });+ }+ return true;+ });++ for (const answer of toResolve) {+ await this.decide(goalId, answer.decisionId, answer.optionId, answer.resolution);+ }+ };++ /** Pending clarifications grouped by goal, for surfaces outside the goal page. */+ pendingClarifications = async () => {+ const rows = await this.goalModel.listPendingClarifications();+ const byGoal = new Map<+ string,+ {+ agentId: string | null;+ goalId: string;+ questions: Array<{+ decisionId: string;+ description: string | null;+ options: GoalDecisionOption[];+ question: string;+ }>;+ requirement: string | null;+ title: string;+ }+ >();+ for (const row of rows) {+ const group = byGoal.get(row.goalId) ?? {+ agentId: row.agentId,+ goalId: row.goalId,+ questions: [],+ requirement: row.requirement,+ title: row.goalTitle,+ };+ group.questions.push({+ decisionId: row.decisionId,+ description: row.description,+ options: row.options ?? [],+ question: row.question,+ });+ byGoal.set(row.goalId, group);+ }+ return [...byGoal.values()];+ };+/*** Advance the goal by one coordinator step.*@@ -2423,10 +2517,38 @@ export class GoalService {}const generator = new GoalCriteriaGeneratorService(this.db, this.userId, this.workspaceId);- const plan = await generator.decompose({ requirement }).catch(() => undefined);+ const clarifications = collectClarificationAnswers(graph);+ const plan = await generator+ .decompose({ clarifications, requirement })+ .catch(() => undefined);+ // A graph without a problem node has nowhere to hang a question, so its+ // questions are planned around as assumptions like a re-plan's would be.+ const understanding = plan+ ? normalizeUnderstanding(+ plan,+ hasAskedClarification(graph) || !problem,+ clarifications.map((item) => item.question),+ )+ : undefined;const draftTasks: GoalDecompositionDraft['tasks'] = plan?.tasks ?? [- { instruction: problem?.description ?? requirement, title: graph.goal.title },+ {+ // The user's answers are authoritative; a planner failure after the+ // clarification round must not start the work without them.+ instruction: [+ // After a clarification round, scope the work by the original request+ // plus the answers — never by a summary a planner wrote earlier.+ clarifications.length > 0 ? requirement : (problem?.description ?? requirement),+ clarifications.length > 0+ ? `Answered clarifications (authoritative):\n${clarifications+ .map((item) => `- Q: ${item.question}\n A: ${item.answer}`)+ .join('\n')}`+ : undefined,+ ]+ .filter(Boolean)+ .join('\n\n'),+ title: graph.goal.title,+ },];// Only the current lease owner may commit. The model call above does not@@ -2457,10 +2579,55 @@ export class GoalService {return undefined;const committedEffects: GoalAdvanceEffect[] = [];+ const asking = Boolean(understanding?.ask.length && currentProblem);if (plan && currentProblem) {// The node's description becomes the planner's own words for the core- // question — not the acceptance boilerplate the goal row keeps.- await writer.updateNodeDescription(goalId, currentProblem.id, plan.problemStatement);+ // question — not the acceptance boilerplate the goal row keeps. A plan+ // that stops to ask commits no tasks, so it keeps the user's own words:+ // the re-plan, or its fallback, must still read the original request.+ await writer.updateNodeDescription(+ goalId,+ currentProblem.id,+ asking ? (currentProblem.description ?? plan.problemStatement) : plan.problemStatement,+ understanding && UNDERSTANDING_CONFIDENCE[understanding.level],+ );+ }+ if (understanding) {+ await goalModel.updateUnderstanding(goalId, {+ assumptions: understanding.assumptions,+ level: understanding.level,+ updatedAt: new Date().toISOString(),+ });+ }++ // A question only the user can answer is asked before anything runs:+ // Tasks planned on a wrong reading of the goal are the most expensive+ // way to find out. No Task is created, so the next plan — made with the+ // answers — starts from the same empty graph.+ if (asking && understanding && currentProblem) {+ for (const question of understanding.ask) {+ const node = await writer.createNode(goalId, {+ description: question.impact,+ kind: 'decision',+ status: 'waiting',+ title: GOAL_CLARIFICATION_TITLE,+ });+ if (!node) throw new Error('Failed to open a clarification decision');+ await writer.createEdge(goalId, currentProblem.id, node.id, 'leads_to');+ await writer.createDecision(goalId, node.id, {+ authority: 'user',+ options: clarificationOptions(question),+ question: question.question,+ requestedUserId: this.userId,+ });+ committedEffects.push({+ detail: question.question,+ nodeId: currentProblem.id,+ targetId: node.id,+ type: 'opened_decision',+ });+ }+ return committedEffects;}const createdIds: string[] = [];@@ -2519,6 +2686,15 @@ export class GoalService {}effects.push(...committed);+ const asked = committed.filter((effect) => effect.type === 'opened_decision').length;+ if (asked > 0) {+ return {+ goalId,+ message: `Asked ${asked} clarification question${asked > 1 ? 's' : ''} before planning`,+ outcome: 'advanced' as const,+ };+ }+return {goalId,message: plandiff --git a/apps/server/src/services/goal/understanding.test.ts b/apps/server/src/services/goal/understanding.test.tsnew file mode 100644index 00000000000..2a75dcb6377--- /dev/null+++ b/apps/server/src/services/goal/understanding.test.ts@@ -0,0 +1,192 @@+import { GOAL_CLARIFICATION_TITLE } from '@lobechat/const/goal';+import type { GoalGraphDecision, GoalGraphNode, GoalGraphSnapshot } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import {+ clarificationOptions,+ collectClarificationAnswers,+ hasAskedClarification,+ normalizeUnderstanding,+} from './understanding';++const question = (overrides: Partial<Record<string, unknown>> = {}) => ({+ assumption: 'Target the web app',+ blocking: true,+ impact: 'Decides which client gets built',+ options: ['Web', 'Desktop'],+ question: 'Which client should this ship on?',+ ...overrides,+});++describe('normalizeUnderstanding', () => {+ it('asks the blocking questions and rates the understanding low', () => {+ const result = normalizeUnderstanding(+ {+ assumptions: [],+ questions: [+ question(),+ question({ assumption: 'CSV', blocking: false, question: 'Which export format?' }),+ ],+ },+ false,+ );++ expect(result.level).toBe('low');+ expect(result.ask).toEqual([+ {+ assumption: 'Target the web app',+ impact: 'Decides which client gets built',+ options: ['Web', 'Desktop'],+ question: 'Which client should this ship on?',+ },+ ]);+ // The question that is not asked still shapes the plan as a visible assumption.+ expect(result.assumptions).toEqual(['CSV']);+ });++ it('never asks twice: a re-plan turns its questions into assumptions', () => {+ const result = normalizeUnderstanding(+ { assumptions: ['Use English'], questions: [question()] },+ true,+ );++ expect(result.ask).toEqual([]);+ expect(result.level).toBe('medium');+ expect(result.assumptions).toEqual(['Use English', 'Target the web app']);+ });++ it('drops a re-asked question the user already answered instead of assuming against it', () => {+ const result = normalizeUnderstanding(+ {+ assumptions: ['Use English'],+ questions: [question(), question({ assumption: 'CSV', question: 'Which format?' })],+ },+ true,+ [' which client should this ship on? '],+ );++ expect(result.assumptions).toEqual(['Use English', 'CSV']);+ });++ it('rates a goal with nothing unknown high', () => {+ expect(normalizeUnderstanding({ assumptions: [], questions: [] }, false)).toEqual({+ ask: [],+ assumptions: [],+ level: 'high',+ });+ // An answer from before the fields existed plans as a clear goal.+ expect(normalizeUnderstanding({}, false).level).toBe('high');+ });++ it('asks a repeated question once', () => {+ const result = normalizeUnderstanding(+ { questions: [question(), question({ question: 'which client should this ship on' })] },+ false,+ );++ expect(result.ask).toHaveLength(1);+ });++ it('caps the questions and drops blank ones', () => {+ const result = normalizeUnderstanding(+ {+ questions: [+ question({ question: ' ' }),+ question({ question: 'Q1' }),+ question({ question: 'Q2' }),+ question({ question: 'Q3' }),+ question({ question: 'Q4' }),+ ],+ },+ false,+ );++ expect(result.ask.map((item) => item.question)).toEqual(['Q1', 'Q2', 'Q3']);+ });+});++const node = (overrides: Partial<GoalGraphNode>): GoalGraphNode =>+ ({+ confidence: null,+ createdAt: new Date(0),+ description: null,+ goalId: 'goal',+ id: 'node',+ kind: 'decision',+ priority: 0,+ resolvedAt: null,+ status: 'resolved',+ taskId: null,+ title: GOAL_CLARIFICATION_TITLE,+ updatedAt: new Date(0),+ ...overrides,+ }) as GoalGraphNode;++const decision = (overrides: Partial<GoalGraphDecision>): GoalGraphDecision =>+ ({+ authority: 'user',+ canceledAt: null,+ createdAt: new Date(0),+ id: 'decision',+ nodeId: 'node',+ options: clarificationOptions({+ assumption: 'Target the web app',+ options: ['Web', 'Desktop'],+ question: 'Which client?',+ }),+ question: 'Which client?',+ recommendedOptionId: null,+ requestedProjectRole: null,+ requestedUserId: null,+ resolution: null,+ resolvedAt: new Date(0),+ resolvedByAgentId: null,+ resolvedByUserId: 'user',+ resolvedOptionId: 'option-2',+ status: 'resolved',+ updatedAt: new Date(0),+ ...overrides,+ }) as GoalGraphDecision;++const graphOf = (nodes: GoalGraphNode[], decisions: GoalGraphDecision[]) =>+ ({ decisions, nodes }) as unknown as GoalGraphSnapshot;++describe('collectClarificationAnswers', () => {+ it('reads each kind of answer back as the planner should see it', () => {+ const graph = graphOf(+ [node({ id: 'n1' }), node({ id: 'n2' }), node({ id: 'n3' }), node({ id: 'n4' })],+ [+ decision({ id: 'd1', nodeId: 'n1', resolvedOptionId: 'option-2' }),+ decision({+ id: 'd2',+ nodeId: 'n2',+ resolution: 'Only macOS',+ resolvedOptionId: 'option-2',+ }),+ decision({ id: 'd3', nodeId: 'n3', resolvedOptionId: 'assume' }),+ decision({ id: 'd4', nodeId: 'n4', resolution: 'Ship both', resolvedOptionId: 'answer' }),+ ],+ );++ expect(collectClarificationAnswers(graph).map((item) => item.answer)).toEqual([+ 'Desktop',+ 'Desktop (Only macOS)',+ 'No preference — proceed with: Target the web app',+ 'Ship both',+ ]);+ });++ it('ignores pending and non-clarification decisions', () => {+ const graph = graphOf(+ [node({ id: 'n1' }), node({ id: 'n2', title: 'Choose how to recover failed task' })],+ [+ decision({ nodeId: 'n1', resolvedOptionId: null, status: 'pending' }),+ decision({ nodeId: 'n2', resolvedOptionId: 'retry' }),+ ],+ );++ expect(collectClarificationAnswers(graph)).toEqual([]);+ expect(hasAskedClarification(graph)).toBe(true);+ expect(hasAskedClarification(graphOf([node({ title: 'Other' })], []))).toBe(false);+ });+});diff --git a/apps/server/src/services/goal/understanding.ts b/apps/server/src/services/goal/understanding.tsnew file mode 100644index 00000000000..559316df0cc--- /dev/null+++ b/apps/server/src/services/goal/understanding.ts@@ -0,0 +1,147 @@+import { GOAL_CLARIFICATION_OPTION, GOAL_CLARIFICATION_TITLE } from '@lobechat/const/goal';+import type { GoalClarificationAnswer } from '@lobechat/prompts';+import type {+ GoalDecisionOption,+ GoalGraphSnapshot,+ GoalUnderstandingLevel,+} from '@lobechat/types';++import type { GoalDecompositionDraft } from './criteriaGenerator';++const MAX_QUESTIONS = 3;++/**+ * Stored on the problem node's `confidence` column. The level is what+ * decisions read; the number only exists because the column is numeric.+ */+export const UNDERSTANDING_CONFIDENCE: Record<GoalUnderstandingLevel, number> = {+ high: 0.9,+ low: 0.3,+ medium: 0.6,+};++export interface ClarificationQuestion {+ assumption: string;+ impact?: string;+ options: string[];+ question: string;+}++export interface GoalUnderstandingPlan {+ /** Questions to put to the user before any Task is created; empty means proceed. */+ ask: ClarificationQuestion[];+ assumptions: string[];+ level: GoalUnderstandingLevel;+}++/** Whether the coordinator already put its clarification round to the user. */+export const hasAskedClarification = (graph: GoalGraphSnapshot): boolean =>+ graph.nodes.some((node) => node.kind === 'decision' && node.title === GOAL_CLARIFICATION_TITLE);++/**+ * Turn what the planner reported into what the coordinator does.+ *+ * The level is derived, never self-rated: a planner that lists a blocking+ * question has by its own account found something it cannot decide, so the+ * user is asked — once. The second plan proceeds on its assumptions whatever+ * it reports, so a goal can never loop on its own questions.+ */+/** Compare questions the way a user would: case, spacing and closing punctuation don't count. */+const questionKey = (question: string) =>+ question+ .trim()+ .toLowerCase()+ .replace(/[\s??.。!!]+$/u, '');++export const normalizeUnderstanding = (+ plan: Pick<GoalDecompositionDraft, 'assumptions' | 'questions'>,+ alreadyAsked: boolean,+ answeredQuestions: string[] = [],+): GoalUnderstandingPlan => {+ // A re-plan that repeats an answered question would otherwise record its+ // fallback as an assumption — one that contradicts what the user just said.+ const answered = new Set(answeredQuestions.map(questionKey));+ const questions = (plan.questions ?? [])+ .map((item) => ({+ assumption: item.assumption.trim(),+ blocking: item.blocking,+ impact: item.impact?.trim() || undefined,+ options: (item.options ?? []).map((option) => option.trim()).filter(Boolean),+ question: item.question.trim(),+ }))+ .filter((item) => item.question && !answered.has(questionKey(item.question)))+ // The same question twice would be asked as two decisions sharing one answer.+ .filter(+ (item, index, all) =>+ all.findIndex((other) => questionKey(other.question) === questionKey(item.question)) ===+ index,+ )+ .slice(0, MAX_QUESTIONS);++ const ask = alreadyAsked ? [] : questions.filter((item) => item.blocking);+ const asked = new Set(ask);+ // A question that is not put to the user still shapes the plan: its fallback+ // becomes an assumption the user can see and correct.+ const assumptions = [+ ...(plan.assumptions ?? []).map((item) => item.trim()),+ ...questions.filter((item) => !asked.has(item)).map((item) => item.assumption),+ ].filter(Boolean);++ return {+ ask: ask.map(({ blocking: _, ...item }) => item),+ assumptions: [...new Set(assumptions)],+ level: ask.length > 0 ? 'low' : assumptions.length > 0 ? 'medium' : 'high',+ };+};++/** The planner's choices plus the two answers every clarification accepts. */+export const clarificationOptions = (question: ClarificationQuestion): GoalDecisionOption[] => [+ ...question.options.map((label, index) => ({ id: `option-${index + 1}`, label })),+ {+ description: question.assumption,+ id: GOAL_CLARIFICATION_OPTION.assume,+ label: 'Go with the assumption',+ },+ { id: GOAL_CLARIFICATION_OPTION.answer, label: 'Answer with my note' },+];++/**+ * Read the user's answers back off the graph for the re-plan.+ *+ * Built from the resolved decisions rather than stored separately, so the+ * answer the planner sees is always the one the audit trail recorded.+ */+export const collectClarificationAnswers = (+ graph: GoalGraphSnapshot,+): GoalClarificationAnswer[] => {+ const clarificationNodeIds = new Set(+ graph.nodes+ .filter((node) => node.kind === 'decision' && node.title === GOAL_CLARIFICATION_TITLE)+ .map((node) => node.id),+ );++ return graph.decisions+ .filter(+ (decision) =>+ decision.status === 'resolved' &&+ clarificationNodeIds.has(decision.nodeId) &&+ decision.resolvedOptionId,+ )+ .map((decision) => {+ const option = decision.options?.find((item) => item.id === decision.resolvedOptionId);+ const note = decision.resolution?.trim();+ let answer: string;+ if (decision.resolvedOptionId === GOAL_CLARIFICATION_OPTION.assume) {+ answer = `No preference — proceed with: ${option?.description ?? 'your stated assumption'}`;+ } else if (decision.resolvedOptionId === GOAL_CLARIFICATION_OPTION.answer) {+ answer = note ?? '';+ } else {+ answer = option?.label ?? decision.resolvedOptionId!;+ }+ // A note on a chosen option is extra guidance, not a replacement for it.+ if (note && decision.resolvedOptionId !== GOAL_CLARIFICATION_OPTION.answer)+ answer = `${answer} (${note})`;+ return { answer, question: decision.question };+ })+ .filter((item) => item.answer);+};diff --git a/locales/ar/chat.json b/locales/ar/chat.jsonindex da162a0d6c9..0b8ca0dbddf 100644--- a/locales/ar/chat.json+++ b/locales/ar/chat.json@@ -1837,7 +1837,6 @@"taskDetail.untitled": "بدون عنوان","taskDetail.updateFailed": "فشل تحديث المهمة","taskIntent.analyzing": "جارٍ القراءة…",- "taskIntent.answerPlaceholder": "الإجابة، أو اتركها فارغة للتخطي","taskIntent.answersHeading": "التوضيحات","taskIntent.back": "تعديل المسودة","taskIntent.create": "إنشاء",@@ -1847,7 +1846,6 @@"taskIntent.goalCallout.desc": "الهدف يعمل على تحقيق معيار قبول ثابت عبر جولات متعددة.","taskIntent.goalCallout.title": "يبدو أن هذا هدف مستمر","taskIntent.moreCreateOptions": "خيارات إنشاء إضافية",- "taskIntent.next": "التالي","taskIntent.openCreated": "فتح","taskIntent.reviewStep": "تأكيد ما فهمته","taskList.activeTasks": "المهام النشطة",diff --git a/locales/bg-BG/chat.json b/locales/bg-BG/chat.jsonindex eba89a545de..bc056467fb8 100644--- a/locales/bg-BG/chat.json+++ b/locales/bg-BG/chat.json@@ -1837,7 +1837,6 @@"taskDetail.untitled": "Без заглавие","taskDetail.updateFailed": "Неуспешно обновяване на задачата","taskIntent.analyzing": "Четене…",- "taskIntent.answerPlaceholder": "Отговор, или оставете празно, за да пропуснете","taskIntent.answersHeading": "Уточнения","taskIntent.back": "Редактиране на черновата","taskIntent.create": "Създай",@@ -1847,7 +1846,6 @@"taskIntent.goalCallout.desc": "Целта продължава да работи срещу установен стандарт за приемане през множество кръгове.","taskIntent.goalCallout.title": "Това изглежда като продължаваща цел","taskIntent.moreCreateOptions": "Още опции за създаване",- "taskIntent.next": "Напред","taskIntent.openCreated": "Отвори","taskIntent.reviewStep": "Потвърди какво разбрах","taskList.activeTasks": "Активни задачи",diff --git a/locales/de-DE/chat.json b/locales/de-DE/chat.jsonindex 7ce7034f7fd..edc8907df81 100644--- a/locales/de-DE/chat.json+++ b/locales/de-DE/chat.json@@ -1837,7 +1837,6 @@"taskDetail.untitled": "Unbenannt","taskDetail.updateFailed": "Aktualisierung der Aufgabe fehlgeschlagen","taskIntent.analyzing": "Lesen…",- "taskIntent.answerPlaceholder": "Antworten oder leer lassen, um zu überspringen","taskIntent.answersHeading": "Klarstellungen","taskIntent.back": "Entwurf bearbeiten","taskIntent.create": "Erstellen",@@ -1847,7 +1846,6 @@"taskIntent.goalCallout.desc": "Ein Ziel arbeitet kontinuierlich gegen eine festgelegte Akzeptanzgrenze über mehrere Runden hinweg.","taskIntent.goalCallout.title": "Das klingt wie ein fortlaufendes Ziel","taskIntent.moreCreateOptions": "Weitere Erstellungsoptionen",- "taskIntent.next": "Weiter","taskIntent.openCreated": "Öffnen","taskIntent.reviewStep": "Bestätigen, was ich verstanden habe","taskList.activeTasks": "Aktive Aufgaben",diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 21cced2cb40..2f2ba5fee77 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -599,6 +599,12 @@"goalProcess.attempts.retired": "Retired","goalProcess.attempts.running": "Running","goalProcess.attempts.title": "Previous attempts",+ "goalProcess.clarify.description": "Answer these once and the agent plans with them. Skip to let it proceed on its own assumptions.",+ "goalProcess.clarify.islandSubtitle": "needs your answers before it starts",+ "goalProcess.clarify.openGoal": "Open goal",+ "goalProcess.clarify.skip": "Use the agent’s assumptions",+ "goalProcess.clarify.submit": "Start with these answers",+ "goalProcess.clarify.title": "Clarify the goal before work starts","goalProcess.deliverables.empty": "Nothing delivered yet. Documents, generated files and linked resources a task persists show up here — anything left only on a local path does not.","goalProcess.deliverables.from": "From “{{title}}”","goalProcess.deliverables.title": "Deliverables",@@ -626,6 +632,7 @@"goalProcess.gate.decisionPointLabel": "What needs your decision","goalProcess.gate.noteLabel": "Extra guidance","goalProcess.gate.notePlaceholder": "Optional — goes into the next attempt instructions",+ "goalProcess.gate.option.assume": "Go with the assumption","goalProcess.gate.option.fail": "Fail goal","goalProcess.gate.option.retire": "Retire work","goalProcess.gate.option.retry": "Retry work",@@ -636,6 +643,7 @@"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",@@ -1895,7 +1903,6 @@"taskDetail.untitled": "Untitled","taskDetail.updateFailed": "Failed to update task","taskIntent.analyzing": "Reading…",- "taskIntent.answerPlaceholder": "Answer, or leave blank to skip","taskIntent.answersHeading": "Clarifications","taskIntent.back": "Edit draft","taskIntent.create": "Create",@@ -1905,9 +1912,9 @@"taskIntent.goalCallout.desc": "A goal keeps working against a standing acceptance bar across multiple rounds.","taskIntent.goalCallout.title": "This reads like an ongoing goal","taskIntent.moreCreateOptions": "More create options",- "taskIntent.next": "Next","taskIntent.openCreated": "Open","taskIntent.reviewStep": "Confirm what I understood",+ "taskIntent.skipQuestions": "Skip and create","taskList.activeTasks": "Active Tasks","taskList.all": "All tasks","taskList.assignTo": "Assign to",diff --git a/locales/es-ES/chat.json b/locales/es-ES/chat.jsonindex bb8161bfd62..06d5f5c3485 100644--- a/locales/es-ES/chat.json+++ b/locales/es-ES/chat.json@@ -1837,7 +1837,6 @@"taskDetail.untitled": "Sin título","taskDetail.updateFailed": "Error al actualizar la tarea","taskIntent.analyzing": "Leyendo…",- "taskIntent.answerPlaceholder": "Respuesta, o deja en blanco para omitir","taskIntent.answersHeading": "Aclaraciones","taskIntent.back": "Editar borrador","taskIntent.create": "Crear",@@ -1847,7 +1846,6 @@"taskIntent.goalCallout.desc": "Un objetivo sigue trabajando contra un estándar de aceptación constante a lo largo de múltiples rondas.","taskIntent.goalCallout.title": "Esto parece un objetivo continuo","taskIntent.moreCreateOptions": "Más opciones de creación",- "taskIntent.next": "Siguiente","taskIntent.openCreated": "Abrir","taskIntent.reviewStep": "Confirma lo que entendí","taskList.activeTasks": "Tareas Activas",diff --git a/locales/fa-IR/chat.json b/locales/fa-IR/chat.jsonindex 00069418064..dc16716a860 100644--- a/locales/fa-IR/chat.json+++ b/locales/fa-IR/chat.json@@ -1837,7 +1837,6 @@"taskDetail.untitled": "بیعنوان","taskDetail.updateFailed": "بهروزرسانی وظیفه ناموفق بود","taskIntent.analyzing": "در حال خواندن…",- "taskIntent.answerPlaceholder": "پاسخ دهید، یا برای رد کردن خالی بگذارید","taskIntent.answersHeading": "توضیحات","taskIntent.back": "ویرایش پیشنویس","taskIntent.create": "ایجاد",@@ -1847,7 +1846,6 @@"taskIntent.goalCallout.desc": "یک هدف به طور مداوم در برابر یک معیار پذیرش ثابت در چندین مرحله کار میکند.","taskIntent.goalCallout.title": "این شبیه یک هدف مداوم است","taskIntent.moreCreateOptions": "گزینههای بیشتر برای ایجاد",- "taskIntent.next": "بعدی","taskIntent.openCreated": "باز کردن","taskIntent.reviewStep": "تأیید آنچه که فهمیدم","taskList.activeTasks": "وظایف فعال",diff --git a/locales/fr-FR/chat.json b/locales/fr-FR/chat.jsonindex b879ac2f94a..9986a28657f 100644--- a/locales/fr-FR/chat.json+++ b/locales/fr-FR/chat.json@@ -1837,7 +1837,6 @@"taskDetail.untitled": "Sans titre","taskDetail.updateFailed": "Échec de la mise à jour de la tâche","taskIntent.analyzing": "Lecture…",- "taskIntent.answerPlaceholder": "Réponse, ou laissez vide pour passer","taskIntent.answersHeading": "Clarifications","taskIntent.back": "Modifier le brouillon","taskIntent.create": "Créer",@@ -1847,7 +1846,6 @@"taskIntent.goalCallout.desc": "Un objectif continue de fonctionner contre une barre d'acceptation fixe à travers plusieurs étapes.","taskIntent.goalCallout.title": "Cela ressemble à un objectif continu","taskIntent.moreCreateOptions": "Plus d'options de création",- "taskIntent.next": "Suivant","taskIntent.openCreated": "Ouvrir","taskIntent.reviewStep": "Confirmer ce que j'ai compris","taskList.activeTasks": "Tâches Actives",diff --git a/locales/it-IT/chat.json b/locales/it-IT/chat.jsonindex bc46860f1b6..924482a9863 100644--- a/locales/it-IT/chat.json+++ b/locales/it-IT/chat.json@@ -1837,7 +1837,6 @@"taskDetail.untitled": "Senza titolo","taskDetail.updateFailed": "Impossibile aggiornare l’attività","taskIntent.analyzing": "Lettura in corso…",- "taskIntent.answerPlaceholder": "Rispondi, o lascia vuoto per saltare","taskIntent.answersHeading": "Chiarimenti","taskIntent.back": "Modifica bozza","taskIntent.create": "Crea",@@ -1847,7 +1846,6 @@"taskIntent.goalCallout.desc": "Un obiettivo continua a lavorare contro una soglia di accettazione costante attraverso più fasi.","taskIntent.goalCallout.title": "Questo sembra un obiettivo continuo","taskIntent.moreCreateOptions": "Altre opzioni di creazione",- "taskIntent.next": "Avanti","taskIntent.openCreated": "Apri","taskIntent.reviewStep": "Conferma ciò che ho capito","taskList.activeTasks": "Attività Attive",diff --git a/locales/ja-JP/chat.json b/locales/ja-JP/chat.jsonindex 635ea7dfd76..2ef7e3eea1f 100644--- a/locales/ja-JP/chat.json+++ b/locales/ja-JP/chat.json@@ -1837,7 +1837,6 @@"taskDetail.untitled": "無題","taskDetail.updateFailed": "タスクの更新に失敗しました","taskIntent.analyzing": "読み込み中…",- "taskIntent.answerPlaceholder": "回答、またはスキップする場合は空白のままにしてください","taskIntent.answersHeading": "確認事項","taskIntent.back": "下書きを編集","taskIntent.create": "作成",@@ -1847,7 +1846,6 @@"taskIntent.goalCallout.desc": "目標は、複数のラウンドにわたって一定の受け入れ基準に基づいて進行します。","taskIntent.goalCallout.title": "これは継続的な目標のようです","taskIntent.moreCreateOptions": "その他の作成オプション",- "taskIntent.next": "次へ","taskIntent.openCreated": "開く","taskIntent.reviewStep": "理解した内容を確認","taskList.activeTasks": "アクティブなタスク",diff --git a/locales/ko-KR/chat.json b/locales/ko-KR/chat.jsonindex f476b7a670b..e3635833a16 100644--- a/locales/ko-KR/chat.json+++ b/locales/ko-KR/chat.json@@ -1837,7 +1837,6 @@"taskDetail.untitled": "제목 없음","taskDetail.updateFailed": "작업 업데이트 실패","taskIntent.analyzing": "읽는 중…",- "taskIntent.answerPlaceholder": "답변을 입력하거나, 건너뛰려면 비워두세요","taskIntent.answersHeading": "명확성","taskIntent.back": "초안 수정","taskIntent.create": "생성",@@ -1847,7 +1846,6 @@"taskIntent.goalCallout.desc": "목표는 여러 라운드에 걸쳐 지속적인 수락 기준에 따라 작동합니다.","taskIntent.goalCallout.title": "이것은 지속적인 목표처럼 보입니다","taskIntent.moreCreateOptions": "더 많은 생성 옵션",- "taskIntent.next": "다음","taskIntent.openCreated": "열기","taskIntent.reviewStep": "내가 이해한 내용을 확인","taskList.activeTasks": "활성 작업",diff --git a/locales/nl-NL/chat.json b/locales/nl-NL/chat.jsonindex 1734c72bff7..8c58caf761f 100644--- a/locales/nl-NL/chat.json+++ b/locales/nl-NL/chat.json@@ -1837,7 +1837,6 @@"taskDetail.untitled": "Zonder titel","taskDetail.updateFailed": "Bijwerken van taak mislukt","taskIntent.analyzing": "Lezen…",- "taskIntent.answerPlaceholder": "Antwoord, of laat leeg om over te slaan","taskIntent.answersHeading": "Verduidelijkingen","taskIntent.back": "Concept bewerken","taskIntent.create": "Aanmaken",@@ -1847,7 +1846,6 @@"taskIntent.goalCallout.desc": "Een doel blijft werken tegen een vaste acceptatienorm over meerdere rondes.","taskIntent.goalCallout.title": "Dit leest als een doorlopend doel","taskIntent.moreCreateOptions": "Meer aanmaakopties",- "taskIntent.next": "Volgende","taskIntent.openCreated": "Openen","taskIntent.reviewStep": "Bevestig wat ik begreep","taskList.activeTasks": "Actieve Taken",diff --git a/locales/pl-PL/chat.json b/locales/pl-PL/chat.jsonindex cc529be9d88..a82f34dacf0 100644--- a/locales/pl-PL/chat.json+++ b/locales/pl-PL/chat.json@@ -1837,7 +1837,6 @@"taskDetail.untitled": "Bez tytułu","taskDetail.updateFailed": "Nie udało się zaktualizować zadania","taskIntent.analyzing": "Czytanie…",- "taskIntent.answerPlaceholder": "Odpowiedz lub pozostaw puste, aby pominąć","taskIntent.answersHeading": "Wyjaśnienia","taskIntent.back": "Edytuj szkic","taskIntent.create": "Utwórz",@@ -1847,7 +1846,6 @@"taskIntent.goalCallout.desc": "Cel działa w oparciu o ustalony próg akceptacji przez wiele rund.","taskIntent.goalCallout.title": "To brzmi jak trwający cel","taskIntent.moreCreateOptions": "Więcej opcji tworzenia",- "taskIntent.next": "Dalej","taskIntent.openCreated": "Otwórz","taskIntent.reviewStep": "Potwierdź, co zrozumiałem","taskList.activeTasks": "Aktywne zadania",diff --git a/locales/pt-BR/chat.json b/locales/pt-BR/chat.jsonindex d496a314939..01639165670 100644--- a/locales/pt-BR/chat.json+++ b/locales/pt-BR/chat.json@@ -1837,7 +1837,6 @@"taskDetail.untitled": "Sem título","taskDetail.updateFailed": "Falha ao atualizar a tarefa","taskIntent.analyzing": "Lendo…",- "taskIntent.answerPlaceholder": "Resposta, ou deixe em branco para pular","taskIntent.answersHeading": "Esclarecimentos","taskIntent.back": "Editar rascunho","taskIntent.create": "Criar",@@ -1847,7 +1846,6 @@"taskIntent.goalCallout.desc": "Um objetivo continua funcionando contra um padrão de aceitação fixo ao longo de várias rodadas.","taskIntent.goalCallout.title": "Isso parece um objetivo contínuo","taskIntent.moreCreateOptions": "Mais opções de criação",- "taskIntent.next": "Próximo","taskIntent.openCreated": "Abrir","taskIntent.reviewStep": "Confirmar o que eu entendi","taskList.activeTasks": "Tarefas Ativas",diff --git a/locales/ru-RU/chat.json b/locales/ru-RU/chat.jsonindex a38f4afeedf..da5686e53a5 100644--- a/locales/ru-RU/chat.json+++ b/locales/ru-RU/chat.json@@ -1837,7 +1837,6 @@"taskDetail.untitled": "Без названия","taskDetail.updateFailed": "Не удалось обновить задачу","taskIntent.analyzing": "Чтение…",- "taskIntent.answerPlaceholder": "Ответьте или оставьте пустым, чтобы пропустить","taskIntent.answersHeading": "Уточнения","taskIntent.back": "Редактировать черновик","taskIntent.create": "Создать",@@ -1847,7 +1846,6 @@"taskIntent.goalCallout.desc": "Цель продолжает работать с установленной планкой принятия на протяжении нескольких этапов.","taskIntent.goalCallout.title": "Это похоже на текущую цель","taskIntent.moreCreateOptions": "Больше вариантов создания",- "taskIntent.next": "Далее","taskIntent.openCreated": "Открыть","taskIntent.reviewStep": "Подтвердите, что я понял","taskList.activeTasks": "Активные задачи",diff --git a/locales/tr-TR/chat.json b/locales/tr-TR/chat.jsonindex 73abf015614..fde36bf36a4 100644--- a/locales/tr-TR/chat.json+++ b/locales/tr-TR/chat.json@@ -1837,7 +1837,6 @@"taskDetail.untitled": "Başlıksız","taskDetail.updateFailed": "Görev güncellenemedi","taskIntent.analyzing": "Okunuyor…",- "taskIntent.answerPlaceholder": "Cevap verin veya atlamak için boş bırakın","taskIntent.answersHeading": "Açıklamalar","taskIntent.back": "Taslağı düzenle","taskIntent.create": "Oluştur",@@ -1847,7 +1846,6 @@"taskIntent.goalCallout.desc": "Bir hedef, birden fazla tur boyunca sürekli bir kabul barına karşı çalışır.","taskIntent.goalCallout.title": "Bu, devam eden bir hedef gibi görünüyor","taskIntent.moreCreateOptions": "Daha fazla oluşturma seçeneği",- "taskIntent.next": "Sonraki","taskIntent.openCreated": "Aç","taskIntent.reviewStep": "Anladığımı onayla","taskList.activeTasks": "Aktif Görevler",diff --git a/locales/vi-VN/chat.json b/locales/vi-VN/chat.jsonindex 1d78938ec52..3258c43073d 100644--- a/locales/vi-VN/chat.json+++ b/locales/vi-VN/chat.json@@ -1837,7 +1837,6 @@"taskDetail.untitled": "Không tiêu đề","taskDetail.updateFailed": "Cập nhật nhiệm vụ thất bại","taskIntent.analyzing": "Đang đọc…",- "taskIntent.answerPlaceholder": "Trả lời, hoặc để trống để bỏ qua","taskIntent.answersHeading": "Làm rõ","taskIntent.back": "Chỉnh sửa bản nháp","taskIntent.create": "Tạo",@@ -1847,7 +1846,6 @@"taskIntent.goalCallout.desc": "Một mục tiêu sẽ tiếp tục hoạt động dựa trên mức chấp nhận cố định qua nhiều vòng.","taskIntent.goalCallout.title": "Điều này giống như một mục tiêu đang diễn ra","taskIntent.moreCreateOptions": "Thêm tùy chọn tạo",- "taskIntent.next": "Tiếp theo","taskIntent.openCreated": "Mở","taskIntent.reviewStep": "Xác nhận những gì tôi đã hiểu","taskList.activeTasks": "Công Việc Đang Hoạt Động",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 399bee0529e..f3eeb0e0127 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -599,6 +599,12 @@"goalProcess.attempts.retired": "已放弃","goalProcess.attempts.running": "进行中","goalProcess.attempts.title": "之前的尝试",+ "goalProcess.clarify.description": "回答一次,Agent 就会按你的回答规划;跳过则按 Agent 自己的假设开工。",+ "goalProcess.clarify.islandSubtitle": "开工前需要你确认",+ "goalProcess.clarify.openGoal": "打开目标",+ "goalProcess.clarify.skip": "都按 Agent 的假设来",+ "goalProcess.clarify.submit": "按这些回答开工",+ "goalProcess.clarify.title": "开工前先确认目标","goalProcess.deliverables.empty": "还没有交付物。任务写入产品的文档、生成的文件和关联资源会出现在这里——只留在本地路径上的产物不会。","goalProcess.deliverables.from": "来自「{{title}}」","goalProcess.deliverables.title": "交付物",@@ -626,6 +632,7 @@"goalProcess.gate.decisionPointLabel": "需要你决定什么","goalProcess.gate.noteLabel": "补充说明","goalProcess.gate.notePlaceholder": "可选,会写进下一次尝试的指令",+ "goalProcess.gate.option.assume": "按 Agent 的假设来","goalProcess.gate.option.fail": "判定目标失败","goalProcess.gate.option.retire": "放弃这项任务","goalProcess.gate.option.retry": "重试这项任务",@@ -636,6 +643,7 @@"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": "去验收",@@ -1895,7 +1903,6 @@"taskDetail.untitled": "无标题","taskDetail.updateFailed": "任务更新失败","taskIntent.analyzing": "正在理解…",- "taskIntent.answerPlaceholder": "回答,或留空跳过","taskIntent.answersHeading": "补充说明","taskIntent.back": "返回修改","taskIntent.create": "创建",@@ -1905,9 +1912,9 @@"taskIntent.goalCallout.desc": "目标会按既定的验收标准持续推进多轮。","taskIntent.goalCallout.title": "这更像一个持续的目标","taskIntent.moreCreateOptions": "更多创建方式",- "taskIntent.next": "下一步","taskIntent.openCreated": "打开","taskIntent.reviewStep": "先确认一下我的理解",+ "taskIntent.skipQuestions": "跳过,直接创建","taskList.activeTasks": "进行中的任务","taskList.all": "全部任务","taskList.assignTo": "指派给",diff --git a/locales/zh-TW/chat.json b/locales/zh-TW/chat.jsonindex 739728e5f5d..dad5e83017d 100644--- a/locales/zh-TW/chat.json+++ b/locales/zh-TW/chat.json@@ -1837,7 +1837,6 @@"taskDetail.untitled": "未命名","taskDetail.updateFailed": "更新任務失敗","taskIntent.analyzing": "正在閱讀…",- "taskIntent.answerPlaceholder": "回答,或留空以跳過","taskIntent.answersHeading": "澄清","taskIntent.back": "編輯草稿","taskIntent.create": "建立",@@ -1847,7 +1846,6 @@"taskIntent.goalCallout.desc": "目標會在多輪過程中持續運作,並符合既定的接受標準。","taskIntent.goalCallout.title": "這看起來像是一個持續的目標","taskIntent.moreCreateOptions": "更多建立選項",- "taskIntent.next": "下一步","taskIntent.openCreated": "開啟","taskIntent.reviewStep": "確認我所理解的內容","taskList.activeTasks": "進行中的任務",diff --git a/packages/const/src/goal.ts b/packages/const/src/goal.tsindex 82271d77e04..169fae96ccd 100644--- a/packages/const/src/goal.ts+++ b/packages/const/src/goal.ts@@ -50,6 +50,21 @@ export const GOAL_COORDINATOR_ACTOR_ID = 'goal-coordinator';*/export const GOAL_ACCEPTANCE_TASK_TITLE = 'Complete full Goal acceptance';+/**+ * Fixed title of the decision node the coordinator opens when decomposition+ * finds a question only the user can answer. Stored in English as data and+ * matched by clients for localized copy, the same way as the acceptance title.+ */+export const GOAL_CLARIFICATION_TITLE = 'Clarify the goal';++/** Option ids every clarification decision carries besides the planner's own choices. */+export const GOAL_CLARIFICATION_OPTION = {+ /** Answer in the free-text note; the note is the answer. */+ answer: 'answer',+ /** Proceed on the assumption the planner stated for this question. */+ assume: 'assume',+} as const;+/*** Task error strings the Goal coordinator matches on to route a paused Task.*diff --git a/packages/database/src/models/goal.ts b/packages/database/src/models/goal.tsindex fe2a27f9608..d68a010ea18 100644--- a/packages/database/src/models/goal.ts+++ b/packages/database/src/models/goal.ts@@ -1,8 +1,13 @@import { randomUUID } from 'node:crypto';-import type { GoalStatus } from '@lobechat/const/goal';-import type { GoalNodeStatus, GoalSupervisionState } from '@lobechat/types';-import { and, desc, eq, inArray, sql } from 'drizzle-orm';+import { GOAL_CLARIFICATION_TITLE, type GoalStatus } from '@lobechat/const/goal';+import type {+ GoalDecisionOption,+ GoalNodeStatus,+ GoalSupervisionState,+ GoalUnderstanding,+} from '@lobechat/types';+import { and, desc, eq, inArray, notInArray, sql } from 'drizzle-orm';import type { GoalItem, NewGoal } from '../schemas/goal';import { goals } from '../schemas/goal';@@ -137,6 +142,21 @@ export class GoalModel {return row as GoalItem | undefined;};+ /**+ * Patch only `config.understanding`, for the same reason as+ * `updatePauseReason`: decomposition writes it while the user may be editing+ * budget or acceptance on the same column.+ */+ updateUnderstanding = async (id: string, understanding: GoalUnderstanding): Promise<void> => {+ await this.db+ .update(goals)+ .set({+ config: sql`jsonb_set(COALESCE(${goals.config}, '{}'::jsonb), '{understanding}', ${JSON.stringify(understanding)}::jsonb)`,+ updatedAt: new Date(),+ })+ .where(and(eq(goals.id, id), this.ownership()));+ };+/** Compare-and-swap only the supervisor namespace; concurrent budget edits survive. */updateSupervisorState = async (id: string,@@ -171,12 +191,13 @@ export class GoalModel {// policy edits cannot replace the concurrently written incident ledger....(value.config !== undefined? {- config: sql`(COALESCE(${JSON.stringify(value.config ?? {})}::jsonb, '{}'::jsonb) - 'planningCheckpoint' - 'planningProtocol' - 'supervisorState' - 'managerState')+ config: sql`(COALESCE(${JSON.stringify(value.config ?? {})}::jsonb, '{}'::jsonb) - 'planningCheckpoint' - 'planningProtocol' - 'supervisorState' - 'managerState' - 'understanding')|| jsonb_strip_nulls(jsonb_build_object('planningCheckpoint', ${goals.config}->'planningCheckpoint','planningProtocol', ${goals.config}->'planningProtocol','supervisorState', ${goals.config}->'supervisorState',- 'managerState', ${goals.config}->'managerState'+ 'managerState', ${goals.config}->'managerState',+ 'understanding', ${goals.config}->'understanding'))`,}: {}),@@ -273,6 +294,40 @@ export class GoalModel {});};+ /**+ * Every clarification the coordinator is still waiting on, across the+ * caller's goals — what a surface outside the goal page needs to ask them.+ * Oldest first, so the question that has waited longest is asked first.+ */+ listPendingClarifications = async (): Promise<PendingGoalClarificationRow[]> =>+ this.db+ .select({+ agentId: goals.agentId,+ decisionId: goalNodeDecisions.id,+ description: goalNodes.description,+ goalId: goals.id,+ goalTitle: goals.title,+ options: goalNodeDecisions.options,+ requirement: goals.requirement,+ question: goalNodeDecisions.question,+ })+ .from(goalNodeDecisions)+ .innerJoin(goalNodes, eq(goalNodeDecisions.nodeId, goalNodes.id))+ .innerJoin(goals, eq(goalNodes.goalId, goals.id))+ .where(+ and(+ this.ownership(),+ // Only a goal parked on its questions asks them; one the user paused+ // or ended keeps its open questions without nagging about them.+ notInArray(goals.status, ['paused', 'achieved', 'failed', 'canceled']),+ eq(goalNodeDecisions.status, 'pending'),+ eq(goalNodes.title, GOAL_CLARIFICATION_TITLE),+ ),+ )+ // A round's questions share one transaction timestamp; the id keeps+ // their order stable across reads so "question 1" stays question 1.+ .orderBy(goalNodeDecisions.createdAt, goalNodeDecisions.id);+delete = async (id: string) => {return this.db.delete(goals).where(and(eq(goals.id, id), this.ownership()));};@@ -492,3 +547,16 @@ export interface GoalListItem {totalRunCost: number;totalRunDuration: number;}++export interface PendingGoalClarificationRow {+ agentId: string | null;+ decisionId: string;+ /** What changes with the answer (the decision node's description). */+ description: string | null;+ goalId: string;+ goalTitle: string;+ options: GoalDecisionOption[] | null;+ question: string;+ /** What the goal asks for, so a surface away from its page can say which goal this is. */+ requirement: string | null;+}diff --git a/packages/database/src/models/goalGraph.ts b/packages/database/src/models/goalGraph.tsindex 8db39dfe7dd..bed1f249335 100644--- a/packages/database/src/models/goalGraph.ts+++ b/packages/database/src/models/goalGraph.ts@@ -534,12 +534,22 @@ export class GoalGraphModel {});/** Rewrite a node's description — e.g. the planner replacing the seeded requirement blob with its own problem statement. */- updateNodeDescription = async (goalId: string, nodeId: string, description: string) =>+ /** `confidence` travels with the description when the planner re-reads the problem. */+ updateNodeDescription = async (+ goalId: string,+ nodeId: string,+ description: string,+ confidence?: number,+ ) =>this.db.transaction(async (tx) => {if (!(await this.ownedGoal(goalId, tx))) return undefined;const [node] = await tx.update(goalNodes)- .set({ description, updatedAt: new Date() })+ .set({+ description,+ ...(confidence === undefined ? {} : { confidence: confidence.toString() }),+ updatedAt: new Date(),+ }).where(and(eq(goalNodes.goalId, goalId), eq(goalNodes.id, nodeId))).returning();if (!node) return undefined;diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex dd7a3745c55..2d79f68efca 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -1888,15 +1888,14 @@ export default {'createTask.visibility.private': 'Private','createTask.visibility.workspace': 'Workspace','taskIntent.analyzing': 'Reading…',- 'taskIntent.answerPlaceholder': 'Answer, or leave blank to skip','taskIntent.answersHeading': 'Clarifications','taskIntent.back': 'Edit draft','taskIntent.created': 'Task created','taskIntent.openCreated': 'Open',- 'taskIntent.next': 'Next','taskIntent.createDirectly': 'Create without reading the draft','taskIntent.moreCreateOptions': 'More create options','taskIntent.create': 'Create',+ 'taskIntent.skipQuestions': 'Skip and create','taskIntent.goalCallout.action': 'Create a goal','taskIntent.goalCallout.desc':'A goal keeps working against a standing acceptance bar across multiple rounds.',@@ -2094,6 +2093,14 @@ export default {'goalProcess.gate.decisionPointLabel': 'What needs your decision','goalProcess.gate.title.recoverTask': 'Decide what happens to the failed task','goalProcess.gate.title.goalAcceptance': 'Decide the goal acceptance outcome',+ 'goalProcess.clarify.title': 'Clarify the goal before work starts',+ 'goalProcess.clarify.description':+ 'Answer these once and the agent plans with them. Skip to let it proceed on its own assumptions.',+ 'goalProcess.clarify.submit': 'Start with these answers',+ 'goalProcess.clarify.skip': 'Use the agent’s assumptions',+ 'goalProcess.clarify.islandSubtitle': 'needs your answers before it starts',+ 'goalProcess.clarify.openGoal': 'Open goal',+ 'goalProcess.gate.title.clarifyGoal': 'Clarify the goal before work starts','goalProcess.gate.reason.verifyInternalError':'Verification could not run (internal error); this delivery was not evaluated','goalProcess.gate.reason.verifyFailed': 'Task {{id}} did not pass verification',@@ -2107,6 +2114,7 @@ export default {'goalProcess.gate.option.retry': 'Retry work','goalProcess.gate.option.retire': 'Retire work','goalProcess.gate.option.fail': 'Fail goal',+ 'goalProcess.gate.option.assume': 'Go with the assumption','goalProcess.attempts.title': 'Previous attempts','goalProcess.attempts.nth': 'Attempt {{index}}','goalProcess.attempts.passed': 'Passed',diff --git a/packages/prompts/src/chains/goal.test.ts b/packages/prompts/src/chains/goal.test.tsindex 4dce173f754..c3a37f3e3c5 100644--- a/packages/prompts/src/chains/goal.test.ts+++ b/packages/prompts/src/chains/goal.test.ts@@ -43,7 +43,7 @@ describe('chainGoalDecompose', () => {const { messages } = chainGoalDecompose({ requirement });const prompt = messages[0].content;- expect(GOAL_DECOMPOSE_PROMPT_VERSION).toBe('v5');+ expect(GOAL_DECOMPOSE_PROMPT_VERSION).toBe('v6');expect(messages[1].content).toContain(requirement);expect(prompt).toContain('a request to build, fix, or upgrade requires implementation');expect(prompt).toContain('It may pass when it proves a capability is missing');@@ -54,4 +54,19 @@ describe('chainGoalDecompose', () => {expect(prompt).toContain('discovering a read-only viewer triggers implementation');expect(prompt).toContain('an investigation-only goal must not become an implementation task');});++ it('reports what it cannot determine and plans on answered clarifications', () => {+ const plain = chainGoalDecompose({ requirement: '写一份发布说明' });+ expect(plain.messages[0].content).toContain(+ 'every blocking question goes into that single round',+ );+ expect(plain.messages[1].content).not.toContain('Answered clarifications');++ const { messages } = chainGoalDecompose({+ clarifications: [{ answer: '开发者', question: '给谁看?' }],+ requirement: '写一份发布说明',+ });+ expect(messages[1].content).toContain('## Answered clarifications');+ expect(messages[1].content).toContain('- Q: 给谁看?\n A: 开发者');+ });});diff --git a/packages/prompts/src/chains/goal.ts b/packages/prompts/src/chains/goal.tsindex f88a65c503e..56fd4922ff8 100644--- a/packages/prompts/src/chains/goal.ts+++ b/packages/prompts/src/chains/goal.ts@@ -65,14 +65,31 @@ export const GOAL_CRITERIA_DRAFT_JSON_SCHEMA = {};/** Bump when the goal decomposition planning prompt meaningfully changes. */-export const GOAL_DECOMPOSE_PROMPT_VERSION = 'v5';+export const GOAL_DECOMPOSE_PROMPT_VERSION = 'v6';export const GOAL_DECOMPOSE_JSON_SCHEMA = {name: 'goal_decomposition',schema: {additionalProperties: false,properties: {+ assumptions: { items: { maxLength: 280, type: 'string' }, maxItems: 5, type: 'array' },problemStatement: { maxLength: 280, minLength: 1, type: 'string' },+ questions: {+ items: {+ additionalProperties: false,+ properties: {+ assumption: { maxLength: 280, minLength: 1, type: 'string' },+ blocking: { type: 'boolean' },+ impact: { maxLength: 280, type: 'string' },+ options: { items: { maxLength: 80, type: 'string' }, maxItems: 4, type: 'array' },+ question: { maxLength: 280, minLength: 1, type: 'string' },+ },+ required: ['question', 'impact', 'options', 'assumption', 'blocking'],+ type: 'object',+ },+ maxItems: 3,+ type: 'array',+ },tasks: {items: {additionalProperties: false,@@ -90,13 +107,20 @@ export const GOAL_DECOMPOSE_JSON_SCHEMA = {type: 'array',},},- required: ['problemStatement', 'tasks'],+ required: ['problemStatement', 'questions', 'assumptions', 'tasks'],type: 'object' as const,},strict: true,};+export interface GoalClarificationAnswer {+ answer: string;+ question: string;+}+interface GoalDecomposeInput {+ /** Questions the user already answered for this goal; present on the re-plan after a clarification. */+ clarifications?: GoalClarificationAnswer[];requirement: string;}@@ -105,6 +129,7 @@ interface GoalDecomposeInput {* answers plus the independent task directions to pursue, before anything runs.*/export const chainGoalDecompose = ({+ clarifications,requirement,}: GoalDecomposeInput): {messages: OpenAIChatMessage[];@@ -129,11 +154,27 @@ export const chainGoalDecompose = ({'- Order tasks so that earlier ones produce what later ones consume.','- For each task, set dependsOn to the 0-based indices of the earlier tasks whose outputs it consumes; use [] for a task that can start immediately. A pipeline-shaped goal (gather → analyze → synthesize) must express those edges — do not mark every task independent — but never invent a dependency the task does not actually need.','- hypothesis marks a task as a candidate answer under test: one sentence stating what the direction bets on, which its result may confirm or refute, and from which later branches may be derived. Set it only for genuinely uncertain approaches that compete with or may replace an alternative. Certain delivery steps — gathering material, implementing a requested change, verifying a deliverable, writing a report — take null. Most goals have no hypothesis at all; never invent one to decorate an ordinary step.',+ '- questions lists what you cannot determine from the goal yet whose answer would change the deliverable itself — its scope, audience, format, target, or a choice between incompatible directions. Never ask about anything the goal (or an answered clarification) already states, about details you can discover by working, or about preferences with a sensible default. Each carries impact (what changes with the answer), up to 4 short options when the answer is a choice, and assumption: what you will do if nobody answers.',+ '- Set blocking when the goal leaves open something that defines the deliverable itself and no default is safe: who it is for, what exactly is to be analyzed or changed, what outcome a change must achieve, or which of incompatible directions to take. A guess there produces a different deliverable, not merely a weaker one. Formats, details, and preferences with a sensible default are never blocking.',+ '- The user is asked once, before any work starts, and every blocking question goes into that single round — there is no later chance to ask, so list them all now rather than holding one back. Keep to what truly decides the deliverable. A goal that already states these things returns no blocking question.',+ '- assumptions lists the non-obvious readings the plan relies on that the user may want to correct; skip the obvious. Write every assumption and every answered clarification into the instructions of the tasks it affects.','- Write all fields in the language used by the goal.',].join('\n'),role: 'system',},- { content: `## Goal\n${requirement}`, role: 'user' },+ {+ content: [+ `## Goal\n${requirement}`,+ clarifications?.length+ ? `## Answered clarifications (authoritative; do not ask again)\n${clarifications+ .map((item) => `- Q: ${item.question}\n A: ${item.answer}`)+ .join('\n')}`+ : undefined,+ ]+ .filter(Boolean)+ .join('\n\n'),+ role: 'user',+ },],});diff --git a/packages/shared-tool-ui/src/AskUserQuestion/QuestionPanel.tsx b/packages/shared-tool-ui/src/AskUserQuestion/QuestionPanel.tsxindex 8a221fa3922..13dd599cf13 100644--- a/packages/shared-tool-ui/src/AskUserQuestion/QuestionPanel.tsx+++ b/packages/shared-tool-ui/src/AskUserQuestion/QuestionPanel.tsx@@ -105,7 +105,14 @@ export const QuestionPanel = memo<QuestionPanelProps>(</Text>)}</Flexbox>- <Text strong>{question.question}</Text>+ <Flexbox gap={2}>+ <Text strong>{question.question}</Text>+ {question.description && (+ <Text fontSize={12} type="secondary">+ {question.description}+ </Text>+ )}+ </Flexbox><Flexbox gap={4} role="listbox">{question.options.map((opt, optIdx) => {diff --git a/packages/shared-tool-ui/src/AskUserQuestion/normalize.test.ts b/packages/shared-tool-ui/src/AskUserQuestion/normalize.test.tsindex 167246955a4..7b06e31ed2a 100644--- a/packages/shared-tool-ui/src/AskUserQuestion/normalize.test.ts+++ b/packages/shared-tool-ui/src/AskUserQuestion/normalize.test.ts@@ -146,4 +146,14 @@ describe('normalizeAskUserQuestions', () => {},]);});++ it('keeps a question description a host supplies', () => {+ expect(+ normalizeAskUserQuestions({+ questions: [+ { description: 'Decides the tone', header: 'Q1', options: [], question: 'Who?' },+ ],+ }),+ ).toEqual([{ description: 'Decides the tone', header: 'Q1', options: [], question: 'Who?' }]);+ });});diff --git a/packages/shared-tool-ui/src/AskUserQuestion/normalize.ts b/packages/shared-tool-ui/src/AskUserQuestion/normalize.tsindex 6f149a3c3b8..564aba360ae 100644--- a/packages/shared-tool-ui/src/AskUserQuestion/normalize.ts+++ b/packages/shared-tool-ui/src/AskUserQuestion/normalize.ts@@ -65,9 +65,11 @@ const normalizeQuestion = (value: unknown): AskUserQuestionItem | undefined => {? rawOptions.map(normalizeOption).filter(isQuestionOption): [];const header = pickString(item?.header) ?? '';+ const description = pickString(item?.description);const multiSelect = typeof item?.multiSelect === 'boolean' ? item.multiSelect : undefined;return {+ ...(description ? { description } : {}),header,...(multiSelect === undefined ? {} : { multiSelect }),options,diff --git a/packages/shared-tool-ui/src/AskUserQuestion/types.ts b/packages/shared-tool-ui/src/AskUserQuestion/types.tsindex 7db29646d7c..ede672f9286 100644--- a/packages/shared-tool-ui/src/AskUserQuestion/types.ts+++ b/packages/shared-tool-ui/src/AskUserQuestion/types.ts@@ -24,6 +24,11 @@ export interface AskUserQuestionOption {* is 2-4 entries, `multiSelect` is opt-in.*/export interface AskUserQuestionItem {+ /**+ * Why the question matters — shown under it. Tool calls do not send one;+ * hosts that ask their own questions (goal / task clarification) do.+ */+ description?: string;header: string;multiSelect?: boolean;options: AskUserQuestionOption[];diff --git a/packages/shared-tool-ui/src/AskUserQuestion/useAskUserForm.test.ts b/packages/shared-tool-ui/src/AskUserQuestion/useAskUserForm.test.tsindex 53e6f58c3a3..ab6081dcc0a 100644--- a/packages/shared-tool-ui/src/AskUserQuestion/useAskUserForm.test.ts+++ b/packages/shared-tool-ui/src/AskUserQuestion/useAskUserForm.test.ts@@ -535,3 +535,34 @@ describe('useAskUserForm producer deadline', () => {vi.useRealTimers();});});++describe('useAskUserForm requireAllAnswered', () => {+ it('waits for every question by default', () => {+ const { hook } = setup(twoQuestionArgs);+ act(() => hook.result.current.handleToggle(twoQuestionArgs.questions[0], 'Narrow'));+ expect(hook.result.current.isSubmitDisabled).toBe(true);+ });++ it('submits a partial answer when every question is optional', async () => {+ const onInteractionAction = vi.fn().mockResolvedValue(undefined);+ const hook = renderHook(() =>+ useAskUserForm({+ args: twoQuestionArgs,+ onInteractionAction,+ persistedDraft: undefined,+ requireAllAnswered: false,+ writeDraft: vi.fn(),+ }),+ );+ expect(hook.result.current.isSubmitDisabled).toBe(true);++ act(() => hook.result.current.handleToggle(twoQuestionArgs.questions[0], 'Narrow'));+ expect(hook.result.current.isSubmitDisabled).toBe(false);++ await act(async () => hook.result.current.handleSubmit());+ expect(onInteractionAction).toHaveBeenCalledWith({+ payload: { 'How broad?': 'Narrow' },+ type: 'submit',+ });+ });+});diff --git a/packages/shared-tool-ui/src/AskUserQuestion/useAskUserForm.ts b/packages/shared-tool-ui/src/AskUserQuestion/useAskUserForm.tsindex 71774b87483..c158cabc439 100644--- a/packages/shared-tool-ui/src/AskUserQuestion/useAskUserForm.ts+++ b/packages/shared-tool-ui/src/AskUserQuestion/useAskUserForm.ts@@ -36,6 +36,12 @@ export interface UseAskUserFormParams {onInteractionAction?: BuiltinInterventionProps<AskUserQuestionArgs>['onInteractionAction'];/** Raw persisted draft blob read from the host's store (coerced internally). */persistedDraft: unknown;+ /**+ * Whether Submit waits for every question. Defaults to `true`; a host whose+ * questions are all optional (task intent) passes `false` so answering one+ * of three is still a submission.+ */+ requireAllAnswered?: boolean;/** Persist the full draft; host wires this to its own store. */writeDraft: (draft: AskUserDraft) => void;}@@ -99,6 +105,7 @@ export const useAskUserForm = ({disabled = false,onInteractionAction,persistedDraft,+ requireAllAnswered = true,writeDraft,}: UseAskUserFormParams): AskUserFormApi => {const questions = useMemo(() => normalizeAskUserQuestions(args), [args]);@@ -425,8 +432,11 @@ export const useAskUserForm = ({}, [awaitProducerAck, disabled, onInteractionAction, submitting]);const allAnswered = useMemo(- () => questions.every((q) => isQuestionAnswered(q, picks, custom)),- [picks, custom, questions],+ () =>+ requireAllAnswered+ ? questions.every((q) => isQuestionAnswered(q, picks, custom))+ : questions.some((q) => isQuestionAnswered(q, picks, custom)),+ [picks, custom, questions, requireAllAnswered],);// Timeout fallback for legacy question forms: shortly BEFORE the deadline,diff --git a/packages/types/src/goal.ts b/packages/types/src/goal.tsindex b99ff878420..57f840241c1 100644--- a/packages/types/src/goal.ts+++ b/packages/types/src/goal.ts@@ -262,6 +262,22 @@ export interface GoalManagerState {turns: number;}+/**+ * How well the coordinator understands what the user wants, as of the last+ * decomposition. Derived from the concrete unknowns the planner reported rather+ * than a self-rated score: `low` means a question was put to the user,+ * `medium` means the plan proceeds on the listed assumptions, `high` means+ * neither.+ */+export type GoalUnderstandingLevel = 'high' | 'medium' | 'low';++export interface GoalUnderstanding {+ /** What the plan takes as given where the goal did not say; shown for the user to correct. */+ assumptions: string[];+ level: GoalUnderstandingLevel;+ updatedAt: string;+}+export interface GoalConfig {acceptance?: GoalAcceptancePolicy;@@ -292,10 +308,15 @@ export interface GoalConfig {* Unset means the goal's agent does its own Tasks.*/taskAgentId?: string;+ /** Coordinator-owned; written by decomposition, never by a policy edit. */+ understanding?: GoalUnderstanding;}/** Creation accepts planning options, never a runtime receipt. */-export type GoalCreateConfig = Omit<GoalConfig, 'managerState' | 'supervisorState'>;+export type GoalCreateConfig = Omit<+ GoalConfig,+ 'managerState' | 'supervisorState' | 'understanding'+>;/*** The goal entity as exposed to clients — a mirror of the `goals` table row.diff --git a/src/features/AgentGoals/GoalClarification/index.tsx b/src/features/AgentGoals/GoalClarification/index.tsxnew file mode 100644index 00000000000..a94ace39d90--- /dev/null+++ b/src/features/AgentGoals/GoalClarification/index.tsx@@ -0,0 +1,71 @@+'use client';++import { memo, useCallback, useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import ClarificationQuestions, {+ type ClarificationAnswer,+} from '@/features/ClarificationQuestions';+import { useGoalStore } from '@/store/goal';++import {+ assumeAll,+ type PendingGoalClarification,+ toClarificationQuestions,+ toDecisionAnswers,+} from './mapping';++export type { PendingGoalClarification } from './mapping';++interface GoalClarificationProps {+ actionsPortalTarget?: HTMLElement | null;+ goalId: string;+ pending: PendingGoalClarification[];+}++/**+ * A goal's clarification round as one form: every question the planner needs+ * answered before work starts, submitted together so the goal re-plans once.+ * Mounted on the goal page and in the global island.+ */+const GoalClarification = memo<GoalClarificationProps>(+ ({ actionsPortalTarget, goalId, pending }) => {+ const { t } = useTranslation('chat');+ const answerGoalClarifications = useGoalStore((s) => s.answerGoalClarifications);++ const questions = useMemo(+ () => toClarificationQuestions(pending, { assume: t('goalProcess.gate.option.assume') }),+ [pending, t],+ );++ const handleSubmit = useCallback(+ (answers: ClarificationAnswer[]) =>+ answerGoalClarifications(goalId, toDecisionAnswers(answers)),+ [answerGoalClarifications, goalId],+ );+ const handleSkip = useCallback(+ () => answerGoalClarifications(goalId, assumeAll(pending)),+ [answerGoalClarifications, goalId, pending],+ );++ // One draft per round: the same goal asking new questions starts blank.+ const draftKey = `goal:${goalId}:${pending.map((item) => item.decisionId).join(',')}`;++ return (+ <ClarificationQuestions+ actionsPortalTarget={actionsPortalTarget}+ draftKey={draftKey}+ key={draftKey}+ questions={questions}+ skipLabel={t('goalProcess.clarify.skip')}+ submitLabel={t('goalProcess.clarify.submit')}+ onSkip={handleSkip}+ onSubmit={handleSubmit}+ />+ );+ },+);++GoalClarification.displayName = 'GoalClarification';++export default GoalClarification;diff --git a/src/features/AgentGoals/GoalClarification/mapping.test.ts b/src/features/AgentGoals/GoalClarification/mapping.test.tsnew file mode 100644index 00000000000..ec379b1f5ec--- /dev/null+++ b/src/features/AgentGoals/GoalClarification/mapping.test.ts@@ -0,0 +1,60 @@+import { describe, expect, it } from 'vitest';++import {+ assumeAll,+ type PendingGoalClarification,+ toClarificationQuestions,+ toDecisionAnswers,+} from './mapping';++const pending: PendingGoalClarification[] = [+ {+ decisionId: 'd1',+ description: 'Decides the tone',+ options: [+ { id: 'option-1', label: '终端用户' },+ { id: 'option-2', label: '开发者' },+ { description: '面向终端用户', id: 'assume', label: 'Go with the assumption' },+ { id: 'answer', label: 'Answer with my note' },+ ],+ question: '给谁看?',+ },+];++describe('toClarificationQuestions', () => {+ it('drops the note option, which the form’s own text row replaces, and localizes the assumption', () => {+ expect(toClarificationQuestions(pending, { assume: '按 Agent 的假设来' })).toEqual([+ {+ description: 'Decides the tone',+ header: '',+ id: 'd1',+ options: [+ { description: undefined, id: 'option-1', label: '终端用户' },+ { description: undefined, id: 'option-2', label: '开发者' },+ { description: '面向终端用户', id: 'assume', label: '按 Agent 的假设来' },+ ],+ question: '给谁看?',+ },+ ]);+ });+});++describe('toDecisionAnswers', () => {+ it('sends a picked option as itself and typed text as the note answer', () => {+ expect(+ toDecisionAnswers([+ { note: '只关心 SDK', optionId: 'option-2', questionId: 'd1', type: 'option' },+ { questionId: 'd2', text: '发在 GitHub Release', type: 'text' },+ ]),+ ).toEqual([+ { decisionId: 'd1', optionId: 'option-2', resolution: '只关心 SDK' },+ { decisionId: 'd2', optionId: 'answer', resolution: '发在 GitHub Release' },+ ]);+ });+});++describe('assumeAll', () => {+ it('lets the agent proceed on its assumption for every question', () => {+ expect(assumeAll(pending)).toEqual([{ decisionId: 'd1', optionId: 'assume' }]);+ });+});diff --git a/src/features/AgentGoals/GoalClarification/mapping.ts b/src/features/AgentGoals/GoalClarification/mapping.tsnew file mode 100644index 00000000000..5723ba43e76--- /dev/null+++ b/src/features/AgentGoals/GoalClarification/mapping.ts@@ -0,0 +1,68 @@+import { GOAL_CLARIFICATION_OPTION } from '@lobechat/const/goal';+import type { GoalDecisionOption } from '@lobechat/types';++import type {+ ClarificationAnswer,+ ClarificationQuestion,+} from '@/features/ClarificationQuestions/answers';++/** One pending clarification, as both the goal graph and the pending list carry it. */+export interface PendingGoalClarification {+ decisionId: string;+ /** What changes with the answer. */+ description?: string | null;+ options: GoalDecisionOption[] | null;+ question: string;+}++export interface GoalDecisionAnswer {+ decisionId: string;+ optionId: string;+ resolution?: string;+}++/**+ * Present a goal's clarification decisions as one AskUserQuestion form.+ *+ * The planner's choices stay as they are; the "go with the assumption" option+ * keeps its id so the server records it as such, and shows the assumption+ * itself as its description. The "answer with my note" option is dropped — the+ * form's own write-your-own row is that answer.+ */+export const toClarificationQuestions = (+ pending: PendingGoalClarification[],+ labels: { assume: string },+): ClarificationQuestion[] =>+ pending.map((item) => ({+ description: item.description ?? undefined,+ // The form already tabs its questions Q1, Q2…; a header here would only+ // repeat that above the question.+ header: '',+ id: item.decisionId,+ options: (item.options ?? [])+ .filter((option) => option.id !== GOAL_CLARIFICATION_OPTION.answer)+ .map((option) =>+ option.id === GOAL_CLARIFICATION_OPTION.assume+ ? { description: option.description, id: option.id, label: labels.assume }+ : { description: option.description, id: option.id, label: option.label },+ ),+ question: item.question,+ }));++export const toDecisionAnswers = (answers: ClarificationAnswer[]): GoalDecisionAnswer[] =>+ answers.map((answer) =>+ answer.type === 'option'+ ? { decisionId: answer.questionId, optionId: answer.optionId, resolution: answer.note }+ : {+ decisionId: answer.questionId,+ optionId: GOAL_CLARIFICATION_OPTION.answer,+ resolution: answer.text,+ },+ );++/** Skipping the round means letting the agent proceed on what it assumed. */+export const assumeAll = (pending: PendingGoalClarification[]): GoalDecisionAnswer[] =>+ pending.map((item) => ({+ decisionId: item.decisionId,+ optionId: GOAL_CLARIFICATION_OPTION.assume,+ }));diff --git a/src/features/AgentGoals/ProcessControl/Frontier.tsx b/src/features/AgentGoals/ProcessControl/Frontier.tsxindex 2cbcae686d8..c369cb4a9f4 100644--- a/src/features/AgentGoals/ProcessControl/Frontier.tsx+++ b/src/features/AgentGoals/ProcessControl/Frontier.tsx@@ -15,6 +15,7 @@ import RunningGlyph from '@/features/Home/components/RunningGlyph';import { useActivityTime } from '@/hooks/useActivityTime';import { useChatStore } from '@/store/chat';+import GoalClarification, { type PendingGoalClarification } from '../GoalClarification';import AssigneeProfileAvatar from './AssigneeProfileAvatar';import {coordinatorGateReason,@@ -434,6 +435,13 @@ const FrontierRow = memo<{{gateReasonText ?? view.decision.question}</Text>)}+ {gateKind === 'clarifyGoal' && node.description && (+ // What changes with the answer — the reason the question is worth+ // stopping for, which the bare question does not say.+ <Text fontSize={13} type={'secondary'}>+ {node.description}+ </Text>+ )}{item.kind === 'stale' && <StaleBody view={view} />}<AttemptLedger view={subject ?? view} />{item.kind === 'gate' && canEdit && (@@ -508,6 +516,20 @@ const Frontier = memo<FrontierProps>(({ actions, canEdit, graph, onSelect, plannconst 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+ ? graph.frontier.filter(+ (item) => item.kind === 'gate' && viewGateKind(item.view) === 'clarifyGoal',+ )+ : [];+ const rows = graph.frontier.filter((item) => !clarifyItems.includes(item));+ const pendingClarifications: PendingGoalClarification[] = clarifyItems.map(({ view }) => ({+ decisionId: view.decision!.id,+ description: view.node.description,+ options: view.decision!.options,+ question: view.decision!.question,+ }));return (<Flexbox gap={8}>@@ -556,9 +578,24 @@ const Frontier = memo<FrontierProps>(({ actions, canEdit, graph, onSelect, plann</Text></Flexbox>))}- {graph.frontier.map((item, index) => (+ {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>+ )}+ {rows.map((item, index) => (<Fragment key={item.key}>- {index > 0 && <Divider dashed style={{ margin: 0 }} />}+ {(index > 0 || pendingClarifications.length > 0) && (+ <Divider dashed style={{ margin: 0 }} />+ )}<FrontierRowactions={actions}canEdit={canEdit}diff --git a/src/features/AgentGoals/ProcessControl/coordinatorCopy.test.ts b/src/features/AgentGoals/ProcessControl/coordinatorCopy.test.tsindex c13936375eb..ba440db7e21 100644--- a/src/features/AgentGoals/ProcessControl/coordinatorCopy.test.ts+++ b/src/features/AgentGoals/ProcessControl/coordinatorCopy.test.ts@@ -9,9 +9,10 @@ import {const decision = (ids: string[]) => ({ options: ids.map((id) => ({ id, label: id })) }) as any;describe('coordinatorGateKind', () => {- it('recognizes the two coordinator gate shapes and nothing else', () => {+ it('recognizes the coordinator gate shapes and nothing else', () => {expect(coordinatorGateKind(decision(['retry', 'retire']))).toBe('recoverTask');expect(coordinatorGateKind(decision(['retry', 'fail']))).toBe('goalAcceptance');+ expect(coordinatorGateKind(decision(['option-1', 'assume', 'answer']))).toBe('clarifyGoal');expect(coordinatorGateKind(decision(['approve', 'reject']))).toBeUndefined();expect(coordinatorGateKind(undefined)).toBeUndefined();});diff --git a/src/features/AgentGoals/ProcessControl/coordinatorCopy.ts b/src/features/AgentGoals/ProcessControl/coordinatorCopy.tsindex a739c4e3a36..5b0413365dd 100644--- a/src/features/AgentGoals/ProcessControl/coordinatorCopy.ts+++ b/src/features/AgentGoals/ProcessControl/coordinatorCopy.ts@@ -1,4 +1,4 @@-import { GOAL_ACCEPTANCE_TASK_TITLE } from '@lobechat/const/goal';+import { GOAL_ACCEPTANCE_TASK_TITLE, GOAL_CLARIFICATION_OPTION } from '@lobechat/const/goal';import type { GoalGraphDecision } from '@lobechat/types';import type { GoalNodeView } from './goalGraphViewModel';@@ -11,7 +11,7 @@ import type { GoalNodeView } from './goalGraphViewModel';* not recognize renders verbatim.*/-export type CoordinatorGateKind = 'goalAcceptance' | 'recoverTask';+export type CoordinatorGateKind = 'clarifyGoal' | 'goalAcceptance' | 'recoverTask';export interface LocalizedCopyRef {key: string;@@ -27,6 +27,8 @@ export const coordinatorGateKind = (const ids = idsOf(decision);if (ids.has('retry') && ids.has('retire')) return 'recoverTask';if (ids.has('retry') && ids.has('fail')) return 'goalAcceptance';+ if (ids.has(GOAL_CLARIFICATION_OPTION.assume) && ids.has(GOAL_CLARIFICATION_OPTION.answer))+ return 'clarifyGoal';return undefined;};diff --git a/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.test.tsx b/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.test.tsxindex 2489ad0341c..0f4b608f1ad 100644--- a/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.test.tsx+++ b/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.test.tsx@@ -585,6 +585,46 @@ describe('CreateTaskInlineEntry', () => {await waitFor(() => expect(createTaskMock).toHaveBeenCalledTimes(1));});+ it('creates with the answer a keyboard pick submits in the same keystroke', async () => {+ analyzeIntentMock.mockResolvedValue({+ ...clearReading,+ clarifications: [{ options: ['lobe-chat'], question: 'Which repo?' }],+ confidence: 'medium',+ });++ render(<CreateTaskInlineEntry variant="hero" />);+ fireEvent.keyDown(screen.getByTestId('task-editor'), { key: 'Enter', metaKey: true });+ await screen.findByText('taskIntent.reviewStep');++ // A digit picks the option and, being the last answer, submits at once.+ fireEvent.keyDown(document.body, { key: '1' });++ await waitFor(() => expect(synthesizeInstructionMock).toHaveBeenCalledTimes(1));+ expect(synthesizeInstructionMock.mock.calls[0][0].answers).toEqual([+ { answer: 'lobe-chat', question: 'Which repo?' },+ ]);+ });++ it('creates the draft as typed when the questions are skipped, even after a pick', async () => {+ analyzeIntentMock.mockResolvedValue({+ ...clearReading,+ clarifications: [{ options: ['lobe-chat'], question: 'Which repo?' }],+ confidence: 'medium',+ });++ render(<CreateTaskInlineEntry variant="hero" />);+ fireEvent.keyDown(screen.getByTestId('task-editor'), { key: 'Enter', metaKey: true });++ await screen.findByText('taskIntent.reviewStep');+ fireEvent.click(screen.getByText('lobe-chat'));+ fireEvent.click(screen.getByText('taskIntent.skipQuestions'));++ await waitFor(() => expect(createTaskMock).toHaveBeenCalledTimes(1));+ // Skipping is declining to narrow the scope: no rewrite, no answers.+ expect(synthesizeInstructionMock).not.toHaveBeenCalled();+ expect(createTaskMock.mock.calls[0][0].instruction).not.toContain('lobe-chat');+ });+it('names the last step "create", answered or not', async () => {analyzeIntentMock.mockResolvedValue({...clearReading,diff --git a/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.tsx b/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.tsxindex e8efc66e73a..5dbdfdec3b7 100644--- a/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.tsx+++ b/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.tsx@@ -517,10 +517,6 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {await submitDraft(draft);}, [canCreateTask, readDraft, submitDraft]);- const handleAnswerChange = useCallback((index: number, value: string) => {- setIntentAnswers((current) => ({ ...current, [index]: value }));- }, []);-/*** The review editor is the source of truth for what gets created, not the* composer draft it was seeded from — the user may have rewritten any of it.@@ -542,51 +538,62 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {* falls back to the draft with the answers appended, which is what the flow* did before this step existed.*/- const handleConfirmIntent = useCallback(async () => {- const draft = readDraft();- if (!analysis || !draft) return;+ const confirmIntentWith = useCallback(+ async (answers: ClarificationAnswers) => {+ const draft = readDraft();+ if (!analysis || !draft) return;- const pairs = answeredClarifications(analysis, intentAnswers);+ const pairs = answeredClarifications(analysis, answers);- if (pairs.length > 0) {- setIsSynthesizing(true);- try {- const written = await taskService.synthesizeInstruction({- answers: pairs,- context: assigneeMeta?.title ? `Assigned agent: ${assigneeMeta.title}` : undefined,- instruction: draft.instruction,- });+ if (pairs.length > 0) {+ setIsSynthesizing(true);+ try {+ const written = await taskService.synthesizeInstruction({+ answers: pairs,+ context: assigneeMeta?.title ? `Assigned agent: ${assigneeMeta.title}` : undefined,+ instruction: draft.instruction,+ });- await submitDraft({- // Freshly written prose has no mirror to inherit. Sending the- // pre-answer draft's document instead would win over this markdown- // when the task renders, showing a brief the agent never received.- editorJson: undefined,- instruction: written.instruction,- name: written.title.trim() || intentTitle.trim() || analysis.title,- });- return;- } catch {- // Fall through to the append path below.- } finally {- setIsSynthesizing(false);+ await submitDraft({+ // Freshly written prose has no mirror to inherit. Sending the+ // pre-answer draft's document instead would win over this markdown+ // when the task renders, showing a brief the agent never received.+ editorJson: undefined,+ instruction: written.instruction,+ name: written.title.trim() || intentTitle.trim() || analysis.title,+ });+ return;+ } catch {+ // Fall through to the append path below.+ } finally {+ setIsSynthesizing(false);+ }}- }- const confirmed = buildConfirmedDraft({- analysis,- answers: intentAnswers,- editorJson: draft.editorJson,- heading: t('taskIntent.answersHeading'),- instruction: draft.instruction,- });+ const confirmed = buildConfirmedDraft({+ analysis,+ answers,+ editorJson: draft.editorJson,+ heading: t('taskIntent.answersHeading'),+ instruction: draft.instruction,+ });- await submitDraft({- editorJson: confirmed.editorData,- instruction: confirmed.instruction,- name: intentTitle.trim() || analysis.title,- });- }, [analysis, assigneeMeta?.title, intentAnswers, intentTitle, readDraft, submitDraft, t]);+ await submitDraft({+ editorJson: confirmed.editorData,+ instruction: confirmed.instruction,+ name: intentTitle.trim() || analysis.title,+ });+ },+ [analysis, assigneeMeta?.title, intentTitle, readDraft, submitDraft, t],+ );++ const handleConfirmIntent = useCallback(+ (answers?: ClarificationAnswers) => confirmIntentWith(answers ?? intentAnswers),+ [confirmIntentWith, intentAnswers],+ );+ // Skipping creates from the draft as typed; the answers state may still hold+ // what was picked before the user chose to skip.+ const handleSkipIntent = useCallback(() => confirmIntentWith({}), [confirmIntentWith]);// Hands the draft (and any answers already given) to the goal modal, then// drops back to composing: the goal flow owns the outcome from here, and the@@ -660,12 +667,12 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {{isReviewing && analysis && (<TaskIntentReviewanalysis={analysis}- answers={intentAnswers}isCreating={isCreating || isSynthesizing}title={intentTitle}- onAnswerChange={handleAnswerChange}+ onAnswersChange={setIntentAnswers}onBack={() => setAnalysis(null)}onConfirm={handleConfirmIntent}+ onSkip={handleSkipIntent}onSwitchToGoal={canCreateGoal ? handleSwitchToGoal : undefined}onTitleChange={setIntentTitle}/>diff --git a/src/features/AgentTasks/AgentTaskList/TaskIntentReview.tsx b/src/features/AgentTasks/AgentTaskList/TaskIntentReview.tsxindex e0a0690ee70..11c4bd7879b 100644--- a/src/features/AgentTasks/AgentTaskList/TaskIntentReview.tsx+++ b/src/features/AgentTasks/AgentTaskList/TaskIntentReview.tsx@@ -1,14 +1,18 @@'use client';-import { OptionCard } from '@lobechat/shared-tool-ui/components';import type { TaskIntentAnalysis } from '@lobechat/types';-import { Flexbox, Icon, TextArea } from '@lobehub/ui';-import { Button, Tabs, Text } from '@lobehub/ui/base-ui';+import { Flexbox, Icon } from '@lobehub/ui';+import { Button, Text } from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar } from 'antd-style';-import { ArrowLeft, Check, Sparkles, Target } from 'lucide-react';-import { memo, useCallback, useEffect, useState } from 'react';+import { ArrowLeft, Sparkles, Target } from 'lucide-react';+import { memo, useCallback, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';+import ClarificationQuestions, {+ type ClarificationAnswer,+ type ClarificationQuestion,+} from '@/features/ClarificationQuestions';+import type { ClarificationAnswers } from './taskIntent';const styles = createStaticStyles(({ css }) => ({@@ -40,25 +44,6 @@ const styles = createStaticStyles(({ css }) => ({padding-block: 12px 0;padding-inline: 16px;`,- // Mirrors OptionCard's own index chip so the free-text row reads as one more- // numbered choice rather than a separate control below the list.- customIndex: css`- flex-shrink: 0;-- box-sizing: border-box;- width: 22px;- height: 22px;- border-radius: 6px;-- font-family: ${cssVar.fontFamilyCode};- font-size: 12px;- font-weight: 600;- line-height: 22px;- color: ${cssVar.colorTextSecondary};- text-align: center;-- background: ${cssVar.colorFillTertiary};- `,// Reuses OptionCard's row rhythm so the recap reads as the same list the// user just answered, not as a different kind of object.answerRow: css`@@ -74,23 +59,12 @@ const styles = createStaticStyles(({ css }) => ({background: ${cssVar.colorFillQuaternary};}`,- customRow: css`- margin-block-start: 2px;-- /* Align the chip under OptionCard's own index chips. */- padding-inline: 12px;- `,instruction: css`overflow-y: auto;max-height: 220px;border: 1px solid ${cssVar.colorBorderSecondary};border-radius: ${cssVar.borderRadiusLG};`,- tabs: css`- [role='tablist'] {- width: 100%;- }- `,title: css`box-sizing: border-box;width: 100%;@@ -110,85 +84,77 @@ const styles = createStaticStyles(({ css }) => ({export interface TaskIntentReviewProps {analysis: TaskIntentAnalysis;- answers: ClarificationAnswers;/** True while the brief is being written and the task created. */isCreating?: boolean;- onAnswerChange: (index: number, value: string) => void;+ /** Mirrors the answers given so far, keyed by clarification index. */+ onAnswersChange: (answers: ClarificationAnswers) => void;onBack: () => void;- onConfirm: () => void;+ /** `answers` is what the form just submitted; without it, the mirrored answers are used. */+ onConfirm: (answers?: ClarificationAnswers) => void;+ /** Create without answering: exactly the task the composer would have created. */+ onSkip: () => void;/** Omitted when goals are unavailable — the exit is then simply not offered. */onSwitchToGoal?: () => void;onTitleChange: (title: string) => void;title: string;}+/** A picked option is its own label; a note from the notes box rides along. */+const toIndexedAnswers = (answers: ClarificationAnswer[]): ClarificationAnswers =>+ Object.fromEntries(+ answers.map((answer) => [+ Number(answer.questionId),+ answer.type === 'text'+ ? answer.text+ : answer.note+ ? `${answer.optionId} (${answer.note})`+ : answer.optionId,+ ]),+ );+/*** The confirmation step between typing a task and creating it.** It only ever renders for a draft the reader could not settle on its own, so* everything here is something the user is the only one able to answer. The- * questions stay optional: skipping them creates exactly the task the composer- * would have created before, which keeps this a checkpoint rather than a form- * to fill in. Answering the last one and pressing generate is the whole flow —- * the brief is written from the answers and the task created in one step.+ * questions are asked with the same form agents and goals use, and stay+ * optional: skipping them creates exactly the task the composer would have+ * created before, which keeps this a checkpoint rather than a form to fill in.*/const TaskIntentReview = memo<TaskIntentReviewProps>((props) => {const {analysis,- answers,isCreating,- onAnswerChange,+ onAnswersChange,onBack,onConfirm,+ onSkip,onSwitchToGoal,onTitleChange,title,} = props;const { t } = useTranslation('chat');+ const [actionsTarget, setActionsTarget] = useState<HTMLDivElement | null>(null);- // One question at a time, exactly like AskUserQuestionView: stacking them all- // in a scroll box hid both that a next question existed and how to reach it.- const [activeIndex, setActiveIndex] = useState(0);const clarifications = analysis.clarifications;- // A new reading is a new set of questions, so the cursor goes back to the top- // rather than pointing past the end of a shorter list.- useEffect(() => setActiveIndex(0), [clarifications]);-- const isAnswered = useCallback((index: number) => Boolean(answers[index]?.trim()), [answers]);-- // One past the last question: the step that says what answering produced.-- const pickOption = useCallback(- (index: number, option: string) => {- // Tapping the option that is already the answer clears it, so a mis-tap- // doesn't force the user to select the text and delete it by hand.- const cleared = answers[index] === option;- onAnswerChange(index, cleared ? '' : option);- if (cleared) return;-- // Sweep to the next still-unanswered question. When there is none left- // the form stays put: the primary button already reads "generate", so- // the step the user is on is also the last thing they have to press.- const next = clarifications.findIndex((_, i) => i !== index && !answers[i]?.trim());- if (next >= 0) setActiveIndex(next);- },- [answers, clarifications, onAnswerChange],+ const questions = useMemo<ClarificationQuestion[]>(+ () =>+ clarifications.map((clarification, index) => ({+ description: clarification.impact,+ header: '',+ id: String(index),+ options: (clarification.options ?? []).map((option) => ({ id: option, label: option })),+ question: clarification.question,+ })),+ [clarifications],+ );+ const handleAnswersChange = useCallback(+ (answers: ClarificationAnswer[]) => onAnswersChange(toIndexedAnswers(answers)),+ [onAnswersChange],);const showGoalExit = analysis.kind === 'goal' && Boolean(onSwitchToGoal);- const active = clarifications[activeIndex];- const onLastQuestion = activeIndex >= clarifications.length - 1;-- // The primary button names the step it is on: advancing through the- // questions, then generating. There is no confirmation page between the last- // answer and the task — pressing generate writes the brief from the answers- // and creates it, and the brief is on the task's own page afterwards.- // One label for the last step, whether or not anything was answered. Naming- // it for the machinery behind it ("generate") described what the product does- // rather than what the user gets: either way the press ends with a task.- const primary = onLastQuestion- ? { action: onConfirm, label: t('taskIntent.create') }- : { action: () => setActiveIndex(activeIndex + 1), label: t('taskIntent.next') };+ const hasQuestions = questions.length > 0;return (<>@@ -229,88 +195,42 @@ const TaskIntentReview = memo<TaskIntentReviewProps>((props) => {</Flexbox>)}- {clarifications.length > 0 && (- <Tabs- activeKey={String(activeIndex)}- className={styles.tabs}- variant={'square'}- items={[- ...clarifications.map((_, index) => ({- key: String(index),- label: (- <Flexbox horizontal align={'center'} gap={6}>- <Text>{`Q${index + 1}`}</Text>- {isAnswered(index) && <Icon icon={Check} size={12} />}- </Flexbox>- ),- })),- ]}- onChange={(key) => setActiveIndex(Number(key))}+ {hasQuestions && (+ <ClarificationQuestions+ actionsPortalTarget={actionsTarget}+ key={analysis.summary}+ questions={questions}+ requireAllAnswered={false}+ skipLabel={t('taskIntent.skipQuestions')}+ submitLabel={t('taskIntent.create')}+ onAnswersChange={handleAnswersChange}+ onSkip={onSkip}+ // Hand over what was submitted: a keyboard pick submits in the same+ // event that mirrors it, before the parent's state has caught up.+ onSubmit={(answers) => onConfirm(toIndexedAnswers(answers))}/>)}-- {active &&- (() => {- const index = activeIndex;- const options = active.options ?? [];- // An answer that isn't one of the offered options is the user's own- // wording, so it belongs in the free-text row rather than leaving- // every card unselected with the text stranded elsewhere.- const picked = options.includes(answers[index] ?? '') ? answers[index] : undefined;- const custom = picked === undefined ? (answers[index] ?? '') : '';-- return (- <Flexbox gap={10} key={active.question}>- <Flexbox gap={2}>- <Text strong>{active.question}</Text>- {active.impact && (- <Text fontSize={12} type={'secondary'}>- {active.impact}- </Text>- )}- </Flexbox>-- <Flexbox gap={4} role={'listbox'}>- {options.map((option, optionIndex) => (- <OptionCard- index={optionIndex + 1}- key={option}- label={option}- selected={picked === option}- onToggle={() => pickOption(index, option)}- />- ))}- <Flexbox horizontal align={'center'} className={styles.customRow} gap={12}>- <span className={styles.customIndex}>{options.length + 1}</span>- <TextArea- autoSize={{ maxRows: 4, minRows: 1 }}- placeholder={t('taskIntent.answerPlaceholder')}- style={{ flex: 1 }}- value={custom}- variant={'filled'}- onChange={(e) => onAnswerChange(index, e.target.value)}- />- </Flexbox>- </Flexbox>- </Flexbox>- );- })()}</Flexbox><Flexbox horizontal align={'center'} className={styles.footer} justify={'space-between'}><Button icon={ArrowLeft} size={'small'} type={'text'} onClick={onBack}>{t('taskIntent.back')}</Button>- <Button- disabled={isCreating}- loading={isCreating}- shape={'round'}- size={'small'}- type={'primary'}- onClick={primary.action}- >- {primary.label}- </Button>+ {hasQuestions ? (+ // The form's own Skip / Create land here, so the step keeps one footer.+ <div ref={setActionsTarget} />+ ) : (+ <Button+ disabled={isCreating}+ loading={isCreating}+ shape={'round'}+ size={'small'}+ type={'primary'}+ onClick={() => onConfirm()}+ >+ {t('taskIntent.create')}+ </Button>+ )}</Flexbox></>);diff --git a/src/features/ClarificationQuestions/answers.test.ts b/src/features/ClarificationQuestions/answers.test.tsnew file mode 100644index 00000000000..6d0d84aae45--- /dev/null+++ b/src/features/ClarificationQuestions/answers.test.ts@@ -0,0 +1,108 @@+import { describe, expect, it } from 'vitest';++import {+ type ClarificationQuestion,+ draftToClarificationAnswers,+ toAskUserArgs,+ toClarificationAnswers,+} from './answers';++const questions: ClarificationQuestion[] = [+ {+ description: 'Decides the tone',+ header: 'Q1',+ id: 'd1',+ options: [+ { id: 'option-1', label: 'End users' },+ { id: 'option-2', label: 'Developers' },+ ],+ question: 'Who reads it?',+ },+ {+ header: 'Q2',+ id: 'd2',+ options: [{ id: 'assume', label: 'Go with the assumption' }],+ question: 'Where is it published?',+ },+];++describe('toAskUserArgs', () => {+ it('keeps option ids and the question description for the form', () => {+ expect(toAskUserArgs(questions).questions[0]).toEqual({+ description: 'Decides the tone',+ header: 'Q1',+ options: questions[0].options,+ question: 'Who reads it?',+ });+ });+});++describe('toClarificationAnswers', () => {+ it('reads a picked option id as an option answer and typed text as a text answer', () => {+ expect(+ toClarificationAnswers(questions, {+ 'Where is it published?': 'The changelog page',+ 'Who reads it?': 'option-2',+ }),+ ).toEqual([+ { note: undefined, optionId: 'option-2', questionId: 'd1', type: 'option' },+ { questionId: 'd2', text: 'The changelog page', type: 'text' },+ ]);+ });++ it('attaches the notes box to option answers and appends it to typed ones', () => {+ expect(+ toClarificationAnswers(questions, {+ '__supplement__': 'SDK only',+ 'Where is it published?': 'Changelog',+ 'Who reads it?': 'option-2',+ }),+ ).toEqual([+ { note: 'SDK only', optionId: 'option-2', questionId: 'd1', type: 'option' },+ { questionId: 'd2', text: 'Changelog\nSDK only', type: 'text' },+ ]);+ });++ it('answers every question with the whole-form text', () => {+ expect(toClarificationAnswers(questions, { __freeform__: ' Developers, on GitHub ' })).toEqual([+ { questionId: 'd1', text: 'Developers, on GitHub', type: 'text' },+ { questionId: 'd2', text: 'Developers, on GitHub', type: 'text' },+ ]);+ });++ it('leaves out questions that were not answered', () => {+ expect(toClarificationAnswers(questions, { 'Who reads it?': 'option-1' })).toHaveLength(1);+ });+});++describe('questions worded the same', () => {+ const twins: ClarificationQuestion[] = [+ { header: '', id: 'a', options: [{ id: 'x', label: 'X' }], question: 'Which one?' },+ { header: '', id: 'b', options: [{ id: 'y', label: 'Y' }], question: 'Which one?' },+ ];++ it('keep separate answers instead of sharing one', () => {+ const texts = toAskUserArgs(twins).questions.map((q) => q.question);+ expect(new Set(texts).size).toBe(2);++ expect(toClarificationAnswers(twins, { [texts[0]]: 'x', [texts[1]]: 'y' })).toEqual([+ { note: undefined, optionId: 'x', questionId: 'a', type: 'option' },+ { note: undefined, optionId: 'y', questionId: 'b', type: 'option' },+ ]);+ });+});++describe('draftToClarificationAnswers', () => {+ it('reports what the draft would submit right now', () => {+ expect(+ draftToClarificationAnswers(questions, {+ custom: {},+ escapeActive: false,+ escapeText: '',+ picks: { 'Who reads it?': 'option-1' },+ supplementActive: false,+ supplementText: '',+ }),+ ).toEqual([{ note: undefined, optionId: 'option-1', questionId: 'd1', type: 'option' }]);+ });+});diff --git a/src/features/ClarificationQuestions/answers.ts b/src/features/ClarificationQuestions/answers.tsnew file mode 100644index 00000000000..5021ff4bf77--- /dev/null+++ b/src/features/ClarificationQuestions/answers.ts@@ -0,0 +1,104 @@+import {+ type AskUserDraft,+ type AskUserQuestionArgs,+ buildSubmitPayload,+ FREEFORM_PAYLOAD_KEY,+ SUPPLEMENT_PAYLOAD_KEY,+} from '@lobechat/shared-tool-ui/ask-user';++/**+ * A question the product asks on its own behalf — not a tool call — rendered+ * with the same AskUserQuestion form the conversation uses.+ */+export interface ClarificationQuestion {+ /** Why the answer matters; shown under the question. */+ description?: string;+ /** Short tab label. */+ header: string;+ /** Host-owned identity, echoed back on the answer. */+ id: string;+ /** Option ids are submitted as-is, so a host never maps labels back. */+ options: { description?: string; id: string; label: string }[];+ question: string;+}++export type ClarificationAnswer =+ | {+ /** The optional notes box, attached to every picked option. */+ note?: string;+ optionId: string;+ questionId: string;+ type: 'option';+ }+ | { questionId: string; text: string; type: 'text' };++/**+ * The text each question is keyed by inside the form. The form keys answers by+ * question text, so two questions worded the same would share one answer; a+ * repeat gets a counter to keep every key — and every answer — its own.+ */+const formQuestionTexts = (questions: ClarificationQuestion[]): string[] => {+ const seen = new Map<string, number>();+ return questions.map(({ question }) => {+ const count = (seen.get(question) ?? 0) + 1;+ seen.set(question, count);+ return count === 1 ? question : `${question} (${count})`;+ });+};++export const toAskUserArgs = (questions: ClarificationQuestion[]): AskUserQuestionArgs => {+ const texts = formQuestionTexts(questions);+ return {+ questions: questions.map(({ description, header, options }, index) => ({+ ...(description ? { description } : {}),+ header,+ options,+ question: texts[index],+ })),+ };+};++/**+ * Read the form's submit payload back as one answer per question.+ *+ * The payload is keyed by question text and holds either a picked option id or+ * the user's own words; the whole-form "type directly" box answers every+ * question with the same text.+ */+export const toClarificationAnswers = (+ questions: ClarificationQuestion[],+ payload: Record<string, unknown>,+): ClarificationAnswer[] => {+ const freeform = payload[FREEFORM_PAYLOAD_KEY];+ if (typeof freeform === 'string' && freeform.trim()) {+ return questions.map((q) => ({ questionId: q.id, text: freeform.trim(), type: 'text' }));+ }++ const note =+ typeof payload[SUPPLEMENT_PAYLOAD_KEY] === 'string'+ ? (payload[SUPPLEMENT_PAYLOAD_KEY] as string).trim() || undefined+ : undefined;++ const texts = formQuestionTexts(questions);+ return questions.flatMap((q, index): ClarificationAnswer[] => {+ const value = payload[texts[index]];+ if (typeof value !== 'string' || !value.trim()) return [];+ if (q.options.some((option) => option.id === value)) {+ return [{ note, optionId: value, questionId: q.id, type: 'option' }];+ }+ return [+ { questionId: q.id, text: note ? `${value.trim()}\n${note}` : value.trim(), type: 'text' },+ ];+ });+};++/** The answers a draft would submit right now — for hosts that mirror progress. */+export const draftToClarificationAnswers = (+ questions: ClarificationQuestion[],+ draft: AskUserDraft,+): ClarificationAnswer[] => {+ const args = toAskUserArgs(questions).questions;+ const payload: Record<string, unknown> = buildSubmitPayload(args, draft.picks, draft.custom);+ if (draft.supplementText.trim()) payload[SUPPLEMENT_PAYLOAD_KEY] = draft.supplementText.trim();+ return toClarificationAnswers(questions, payload);+};diff --git a/src/features/ClarificationQuestions/draftStorage.test.ts b/src/features/ClarificationQuestions/draftStorage.test.tsnew file mode 100644index 00000000000..7d4b6d38cf4--- /dev/null+++ b/src/features/ClarificationQuestions/draftStorage.test.ts@@ -0,0 +1,51 @@+/**+ * @vitest-environment happy-dom+ */+import { beforeEach, describe, expect, it } from 'vitest';++import {+ accountDraftKey,+ clearClarificationDraft,+ readClarificationDraft,+ writeClarificationDraft,+} from './draftStorage';++const draft = {+ custom: {},+ escapeActive: false,+ escapeText: '',+ picks: { 'Who reads it?': 'option-2' },+ supplementActive: false,+ supplementText: '',+};++describe('clarification draft storage', () => {+ beforeEach(() => window.localStorage.clear());++ it('restores unsent answers for the same round only', () => {+ writeClarificationDraft('goal:g1:d1,d2', draft);++ expect(readClarificationDraft('goal:g1:d1,d2')).toEqual(draft);+ expect(readClarificationDraft('goal:g1:d3')).toBeUndefined();+ });++ it('forgets the answers once they are sent', () => {+ writeClarificationDraft('goal:g1:d1', draft);+ clearClarificationDraft('goal:g1:d1');++ expect(readClarificationDraft('goal:g1:d1')).toBeUndefined();+ });++ it("never restores one account's draft for another in the same browser", () => {+ writeClarificationDraft(accountDraftKey('user-a', 'goal:g1:d1')!, draft);++ expect(readClarificationDraft(accountDraftKey('user-b', 'goal:g1:d1')!)).toBeUndefined();+ expect(accountDraftKey(undefined, 'goal:g1:d1')).toBeUndefined();+ });++ it('treats an unreadable entry as no draft', () => {+ window.localStorage.setItem('lobechat:clarification:draft:v1:goal:g1:d1', '{not json');++ expect(readClarificationDraft('goal:g1:d1')).toBeUndefined();+ });+});diff --git a/src/features/ClarificationQuestions/draftStorage.ts b/src/features/ClarificationQuestions/draftStorage.tsnew file mode 100644index 00000000000..9eb20b6dea0--- /dev/null+++ b/src/features/ClarificationQuestions/draftStorage.ts@@ -0,0 +1,45 @@+import type { AskUserDraft } from '@lobechat/shared-tool-ui/ask-user';++const KEY_PREFIX = 'lobechat:clarification:draft:v1:';++/**+ * A draft holds the signed-in user's own words, so its key carries the account:+ * another account in the same browser never gets it back. No user, no draft.+ */+export const accountDraftKey = (+ userId: string | undefined,+ draftKey: string | undefined,+): string | undefined => (userId && draftKey ? `${userId}:${draftKey}` : undefined);++/**+ * Unsent answers outlive the form: collapsing the island, leaving the page or+ * reloading unmounts it, and the user should find what they picked still+ * picked. Local storage, keyed by the round the answers belong to.+ */+export const readClarificationDraft = (key: string): AskUserDraft | undefined => {+ if (typeof window === 'undefined') return undefined;+ try {+ const raw = window.localStorage.getItem(KEY_PREFIX + key);+ return raw ? (JSON.parse(raw) as AskUserDraft) : undefined;+ } catch {+ return undefined;+ }+};++export const writeClarificationDraft = (key: string, draft: AskUserDraft): void => {+ if (typeof window === 'undefined') return;+ try {+ window.localStorage.setItem(KEY_PREFIX + key, JSON.stringify(draft));+ } catch {+ // Storage full or blocked: the draft still lives in the form for now.+ }+};++export const clearClarificationDraft = (key: string): void => {+ if (typeof window === 'undefined') return;+ try {+ window.localStorage.removeItem(KEY_PREFIX + key);+ } catch {+ // Nothing to clean up if storage is unavailable.+ }+};diff --git a/src/features/ClarificationQuestions/index.tsx b/src/features/ClarificationQuestions/index.tsxnew file mode 100644index 00000000000..914f5487872--- /dev/null+++ b/src/features/ClarificationQuestions/index.tsx@@ -0,0 +1,142 @@+'use client';++import {+ type AskUserDraft,+ AskUserQuestionView,+ useAskUserForm,+} from '@lobechat/shared-tool-ui/ask-user';+import type { BuiltinInterventionProps } from '@lobechat/types';+import { Flexbox } from '@lobehub/ui';+import { Alert } from '@lobehub/ui/base-ui';+import { memo, useCallback, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useUserStore } from '@/store/user';+import { userProfileSelectors } from '@/store/user/selectors';++import {+ type ClarificationAnswer,+ type ClarificationQuestion,+ draftToClarificationAnswers,+ toAskUserArgs,+ toClarificationAnswers,+} from './answers';+import {+ accountDraftKey,+ clearClarificationDraft,+ readClarificationDraft,+ writeClarificationDraft,+} from './draftStorage';+import { useAskUserLabels } from './useAskUserLabels';++export type { ClarificationAnswer, ClarificationQuestion } from './answers';++export interface ClarificationQuestionsProps {+ /** Portal the Skip/Submit footer into a host-owned footer. */+ actionsPortalTarget?: HTMLElement | null;+ /**+ * Keeps unsent answers across unmounts (collapsing the island, leaving the+ * page, reloading). Identify the round, so a new round starts blank.+ */+ draftKey?: string;+ /** Mirror the answers the draft would submit, for hosts that own the result. */+ onAnswersChange?: (answers: ClarificationAnswer[]) => void;+ /** What "skip" means is the host's call: proceed on assumptions, or without answers. */+ onSkip: () => Promise<void> | void;+ onSubmit: (answers: ClarificationAnswer[]) => Promise<void> | void;+ questions: ClarificationQuestion[];+ /** Defaults to `true`; pass `false` when every question is optional. */+ requireAllAnswered?: boolean;+ /** Host wording for the two footer buttons, when "Submit" / "Skip" undersell them. */+ skipLabel?: string;+ submitLabel?: string;+}++/**+ * The one way the product asks the user its own questions.+ *+ * Goal clarification and task intent used to draw their own question cards,+ * each a little different from the AskUserQuestion form agents use in the+ * conversation. This host renders that same form for questions that do not+ * come from a tool call: the draft lives here instead of on a tool message,+ * and the answer comes back as `{ questionId, optionId | text }` rather than+ * a payload keyed by question text.+ */+const ClarificationQuestions = memo<ClarificationQuestionsProps>(+ ({+ actionsPortalTarget,+ draftKey,+ onAnswersChange,+ onSkip,+ onSubmit,+ questions,+ requireAllAnswered,+ skipLabel,+ submitLabel,+ }) => {+ const { t } = useTranslation('tool');+ const labels = useAskUserLabels({ skip: skipLabel, submit: submitLabel });+ const userId = useUserStore(userProfileSelectors.userId);+ const storageKey = accountDraftKey(userId, draftKey);+ const [draft, setDraft] = useState<AskUserDraft | undefined>(() =>+ storageKey ? readClarificationDraft(storageKey) : undefined,+ );+ const [failed, setFailed] = useState(false);+ const args = useMemo(() => toAskUserArgs(questions), [questions]);++ const writeDraft = useCallback(+ (next: AskUserDraft) => {+ setDraft(next);+ if (storageKey) writeClarificationDraft(storageKey, next);+ onAnswersChange?.(draftToClarificationAnswers(questions, next));+ },+ [onAnswersChange, questions, storageKey],+ );++ const onInteractionAction = useCallback<+ NonNullable<BuiltinInterventionProps['onInteractionAction']>+ >(+ async (action) => {+ setFailed(false);+ try {+ if (action.type === 'skip') await onSkip();+ else if (action.type === 'submit')+ await onSubmit(toClarificationAnswers(questions, action.payload ?? {}));+ // Sent: nothing left to restore. A failed send keeps the draft.+ if (storageKey) clearClarificationDraft(storageKey);+ } catch (error) {+ setFailed(true);+ // Rethrow so the form leaves its submitting state and can be retried.+ throw error;+ }+ },+ [onSkip, onSubmit, questions, storageKey],+ );++ const form = useAskUserForm({+ args,+ onInteractionAction,+ persistedDraft: draft,+ requireAllAnswered,+ writeDraft,+ });++ if (!labels) return null;++ return (+ <Flexbox gap={8}>+ {failed && <Alert title={t('askUserQuestion.submitFailed')} type="error" />}+ <AskUserQuestionView+ {...form}+ actionsPortalTarget={actionsPortalTarget}+ labels={labels}+ showCountdown={false}+ />+ </Flexbox>+ );+ },+);++ClarificationQuestions.displayName = 'ClarificationQuestions';++export default ClarificationQuestions;diff --git a/src/features/ClarificationQuestions/useAskUserLabels.test.ts b/src/features/ClarificationQuestions/useAskUserLabels.test.tsnew file mode 100644index 00000000000..2e6ade9f1e1--- /dev/null+++ b/src/features/ClarificationQuestions/useAskUserLabels.test.ts@@ -0,0 +1,33 @@+/**+ * @vitest-environment happy-dom+ */+import { renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useAskUserLabels } from './useAskUserLabels';++const i18n = vi.hoisted(() => ({ ready: true as boolean | undefined }));++vi.mock('react-i18next', () => ({+ useTranslation: () => ({ ready: i18n.ready, t: (key: string) => `t:${key}` }),+}));++describe('useAskUserLabels', () => {+ beforeEach(() => {+ i18n.ready = true;+ });++ it('withholds the labels until the namespace has loaded, so no raw key is shown', () => {+ i18n.ready = false;+ expect(renderHook(() => useAskUserLabels({})).result.current).toBeUndefined();+ });++ it('uses the host wording for the two footer buttons', () => {+ const labels = renderHook(() => useAskUserLabels({ skip: 'Skip and create', submit: 'Create' }))+ .result.current!;++ expect(labels.skip).toBe('Skip and create');+ expect(labels.submit).toBe('Create');+ expect(labels.customPlaceholder).toBe('t:askUserQuestion.customOption.placeholder');+ });+});diff --git a/src/features/ClarificationQuestions/useAskUserLabels.ts b/src/features/ClarificationQuestions/useAskUserLabels.tsnew file mode 100644index 00000000000..19fe057c252--- /dev/null+++ b/src/features/ClarificationQuestions/useAskUserLabels.ts@@ -0,0 +1,33 @@+import type { AskUserQuestionLabels } from '@lobechat/shared-tool-ui/ask-user';+import { useTranslation } from 'react-i18next';++/**+ * The AskUserQuestion form's strings, or `undefined` until they can be shown.+ *+ * They live in the `tool` namespace, which the conversation loads early but a+ * task or goal page may be the first to ask for; rendering before it arrives+ * shows raw keys, so the form waits the moment it takes to load.+ */+export const useAskUserLabels = (overrides: {+ skip?: string;+ submit?: string;+}): AskUserQuestionLabels | undefined => {+ const { t, ready } = useTranslation('tool');+ if (ready === false) return undefined;++ return {+ customPlaceholder: t('askUserQuestion.customOption.placeholder'),+ escapeBack: t('askUserQuestion.escape.back'),+ escapeEnter: t('askUserQuestion.escape.enter'),+ escapePlaceholder: t('askUserQuestion.escape.placeholder'),+ multiSelectTag: t('askUserQuestion.multiSelectTag'),+ recommendedTag: t('askUserQuestion.recommendedTag'),+ skip: overrides.skip ?? t('askUserQuestion.skip'),+ submit: overrides.submit ?? t('askUserQuestion.submit'),+ supplementEnter: t('askUserQuestion.supplement.enter'),+ supplementPlaceholder: t('askUserQuestion.supplement.placeholder'),+ timeExpired: '',+ timeExpiredNoAnswer: '',+ timeRemaining: () => '',+ };+};diff --git a/src/features/GlobalApprovalNotification/GoalClarificationCard.tsx b/src/features/GlobalApprovalNotification/GoalClarificationCard.tsxnew file mode 100644index 00000000000..663da40e21d--- /dev/null+++ b/src/features/GlobalApprovalNotification/GoalClarificationCard.tsx@@ -0,0 +1,87 @@+'use client';++import { Icon } from '@lobehub/ui';+import { ActionIcon } from '@lobehub/ui/base-ui';+import { ArrowUpRight, ChevronUp, Target } from 'lucide-react';+import { memo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import GoalClarification from '@/features/AgentGoals/GoalClarification';+import MarkdownMessage from '@/features/Conversation/Markdown';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';++import { styles } from './styles';+import type { GoalClarificationGroup } from './usePendingGoalClarifications';++interface GoalClarificationCardProps {+ group: GoalClarificationGroup;+ onCollapse?: () => void;+}++/**+ * A goal's clarification round in the island: the same form the goal page+ * shows, answerable from wherever the user is.+ */+const GoalClarificationCard = memo<GoalClarificationCardProps>(({ group, onCollapse }) => {+ const { t } = useTranslation('chat');+ const navigate = useWorkspaceAwareNavigate();+ const [actionsPortalTarget, setActionsPortalTarget] = useState<HTMLDivElement | null>(null);++ const openGoal = () =>+ navigate(+ group.agentId ? `/agent/${group.agentId}/goal/${group.goalId}` : `/goal/${group.goalId}`,+ );++ return (+ <div data-pending-hotkey-scope className={styles.card}>+ <div className={styles.header}>+ <Icon icon={Target} size={18} />+ {/* The goal's own title leads, the same way a run approval leads with its+ agent — several goals can be waiting, and this is how to tell them apart. */}+ <div className={styles.headerMeta} title={group.title}>+ <div className={styles.headerSubtitle}>+ <span>{group.title}</span>+ {t('goalProcess.clarify.islandSubtitle')}+ </div>+ </div>+ <ActionIcon+ icon={ArrowUpRight}+ size="small"+ title={t('goalProcess.clarify.openGoal')}+ onClick={openGoal}+ />+ {onCollapse && (+ <ActionIcon+ icon={ChevronUp}+ size="small"+ title={t('globalApproval.collapse')}+ onClick={onCollapse}+ />+ )}+ </div>++ {group.requirement && (+ <div className={styles.requestContext}>+ <div className={styles.userRequestBody}>+ <MarkdownMessage>{group.requirement}</MarkdownMessage>+ </div>+ </div>+ )}++ <div className={styles.content}>+ <GoalClarification+ actionsPortalTarget={actionsPortalTarget}+ goalId={group.goalId}+ key={group.goalId}+ pending={group.questions}+ />+ </div>++ <div className={styles.actions} ref={setActionsPortalTarget} />+ </div>+ );+});++GoalClarificationCard.displayName = 'GoalClarificationCard';++export default GoalClarificationCard;diff --git a/src/features/GlobalApprovalNotification/index.tsx b/src/features/GlobalApprovalNotification/index.tsxindex e8762a13725..1e88bc6a917 100644--- a/src/features/GlobalApprovalNotification/index.tsx+++ b/src/features/GlobalApprovalNotification/index.tsx@@ -9,9 +9,11 @@ import { useTranslation } from 'react-i18next';import { isDesktop } from '@/const/version';import ApprovalCard from './ApprovalCard';+import GoalClarificationCard from './GoalClarificationCard';import { styles } from './styles';import { useApprovalIslandCollapse } from './useApprovalIslandCollapse';import { useGlobalPendingApprovals } from './useGlobalPendingApprovals';+import { usePendingGoalClarifications } from './usePendingGoalClarifications';const SPRING = { damping: 30, stiffness: 320, type: 'spring' } as const;@@ -29,15 +31,20 @@ const TOP_OFFSET = isDesktop ? TITLE_BAR_HEIGHT + 8 : 16;const GlobalApprovalNotification = memo(() => {const { t } = useTranslation('chat');const groups = useGlobalPendingApprovals();- const [collapsed, setCollapsed] = useApprovalIslandCollapse(groups.length);+ // A goal waiting on its clarification round asks through the same island.+ // Run approvals go first: a run is blocked mid-turn, a goal has not started.+ const goalGroups = usePendingGoalClarifications();+ const total = groups.length + goalGroups.length;+ const [collapsed, setCollapsed] = useApprovalIslandCollapse(total);- const hasApprovals = groups.length > 0;+ const hasApprovals = total > 0;// Only ONE card is actionable at a time: the reused `ApprovalActions`// registers window-level Enter/1/2 shortcuts, so mounting a card per group// would let a single Enter submit every pending approval at once. Extra// approvals queue behind a count and surface as each one resolves.const top = groups[0];- const extraCount = groups.length - 1;+ const topGoal = top ? undefined : goalGroups[0];+ const extraCount = total - 1;return (<div className={styles.wrapper} style={{ '--global-approval-top': `${TOP_OFFSET}px` } as any}>@@ -55,7 +62,7 @@ const GlobalApprovalNotification = memo(() => {onClick={() => setCollapsed(false)}><span className={styles.pillDot} />- {t('globalApproval.pendingCount', { count: groups.length })}+ {t('globalApproval.pendingCount', { count: total })}</m.div>) : (<m.div@@ -81,6 +88,19 @@ const GlobalApprovalNotification = memo(() => {<ApprovalCard group={top} onCollapse={() => setCollapsed(true)} /></m.div>)}+ {topGoal && (+ <m.div+ layout+ animate={{ opacity: 1, scale: 1, y: 0 }}+ exit={{ opacity: 0, scale: 0.96, y: -16 }}+ initial={{ opacity: 0, scale: 0.96, y: -16 }}+ key={`goal:${topGoal.goalId}`}+ style={{ pointerEvents: 'auto', width: '100%' }}+ transition={SPRING}+ >+ <GoalClarificationCard group={topGoal} onCollapse={() => setCollapsed(true)} />+ </m.div>+ )}</AnimatePresence>{extraCount > 0 && (<div className={styles.moreHint}>diff --git a/src/features/GlobalApprovalNotification/usePendingGoalClarifications.test.ts b/src/features/GlobalApprovalNotification/usePendingGoalClarifications.test.tsnew file mode 100644index 00000000000..7ec5637016e--- /dev/null+++ b/src/features/GlobalApprovalNotification/usePendingGoalClarifications.test.ts@@ -0,0 +1,63 @@+import { describe, expect, it } from 'vitest';++import {+ type GoalClarificationGroup,+ goalIdFromPath,+ selectIslandGoalClarifications,+} from './usePendingGoalClarifications';++const group = (goalId: string, questions = 1): GoalClarificationGroup => ({+ agentId: 'agt',+ goalId,+ questions: Array.from({ length: questions }, (_, i) => ({+ decisionId: `${goalId}-${i}`,+ options: [],+ question: `q${i}`,+ })),+ title: goalId,+});++describe('goalIdFromPath', () => {+ it('reads the goal on screen from agent, bare and workspace goal routes', () => {+ expect(goalIdFromPath('/agent/agt_1/goal/goal_a')).toBe('goal_a');+ expect(goalIdFromPath('/goal/goal_b')).toBe('goal_b');+ expect(goalIdFromPath('/acme/agent/agt_1/goal/goal_c')).toBe('goal_c');+ expect(goalIdFromPath('/agent/agt_1/goals')).toBeUndefined();+ expect(goalIdFromPath('/agent/agt_1')).toBeUndefined();+ });+});++describe('selectIslandGoalClarifications', () => {+ const groups = [group('goal_a'), group('goal_b'), group('goal_c')];++ it('asks nothing of a member who cannot edit the goals', () => {+ expect(selectIslandGoalClarifications(groups, { canAnswer: false, onGoalPage: false })).toEqual(+ [],+ );+ });++ it('stays out of a goal page entirely, even for other goals', () => {+ expect(selectIslandGoalClarifications(groups, { canAnswer: true, onGoalPage: true })).toEqual(+ [],+ );+ });++ it('skips only the goal open in the portal beside a conversation', () => {+ expect(+ selectIslandGoalClarifications(groups, {+ canAnswer: true,+ onGoalPage: false,+ portalGoalId: 'goal_b',+ }).map((g) => g.goalId),+ ).toEqual(['goal_a', 'goal_c']);+ expect(+ selectIslandGoalClarifications(groups, { canAnswer: true, onGoalPage: false }),+ ).toHaveLength(3);+ });++ it('drops a goal with nothing left to ask', () => {+ expect(+ selectIslandGoalClarifications([group('goal_a', 0)], { canAnswer: true, onGoalPage: false }),+ ).toEqual([]);+ });+});diff --git a/src/features/GlobalApprovalNotification/usePendingGoalClarifications.ts b/src/features/GlobalApprovalNotification/usePendingGoalClarifications.tsnew file mode 100644index 00000000000..9614adfc404--- /dev/null+++ b/src/features/GlobalApprovalNotification/usePendingGoalClarifications.ts@@ -0,0 +1,67 @@+import { useMemo } from 'react';+import { useLocation } from 'react-router';++import type { PendingGoalClarification } from '@/features/AgentGoals/GoalClarification';+import { usePermission } from '@/hooks/usePermission';+import { useChatStore } from '@/store/chat';+import { chatPortalSelectors } from '@/store/chat/selectors';+import { useGoalStore } from '@/store/goal';+import { useUserStore } from '@/store/user';+import { labPreferSelectors } from '@/store/user/selectors';++export interface GoalClarificationGroup {+ agentId: string | null;+ goalId: string;+ questions: PendingGoalClarification[];+ requirement?: string | null;+ title: string;+}++const GOAL_PAGE_PATTERN = /\/goal\/([^/?#]+)/;++/** The goal whose page is on screen, if the route is a goal page. */+export const goalIdFromPath = (pathname: string): string | undefined =>+ GOAL_PAGE_PATTERN.exec(pathname)?.[1];++/**+ * What the island should ask, given where the user is.+ *+ * A goal page is where goal questions already live, so the island stays out+ * of it entirely — even for other goals, which would only pull attention away+ * from the one on screen. Beside a conversation, only the goal open in the+ * portal is skipped: it asks the same questions in place.+ */+export const selectIslandGoalClarifications = (+ groups: GoalClarificationGroup[],+ {+ canAnswer,+ onGoalPage,+ portalGoalId,+ }: { canAnswer: boolean; onGoalPage: boolean; portalGoalId?: string },+): GoalClarificationGroup[] =>+ // A member who cannot edit the goal cannot answer for it either — the+ // island would only offer a form that fails on submit.+ !canAnswer || onGoalPage+ ? []+ : groups.filter((group) => group.questions.length > 0 && group.goalId !== portalGoalId);++/** Goal clarification rounds the island should ask, oldest first. */+export const usePendingGoalClarifications = (): GoalClarificationGroup[] => {+ const enabled = useUserStore(labPreferSelectors.enableTopicAcceptance);+ // The same gate the goal page puts on its answer controls.+ const { allowed: canAnswer } = usePermission('create_content');+ const useFetchPendingClarifications = useGoalStore((s) => s.useFetchPendingClarifications);+ const { data } = useFetchPendingClarifications(enabled && canAnswer);+ const { pathname } = useLocation();+ const portalGoalId = useChatStore(chatPortalSelectors.goalPortalId);++ return useMemo(+ () =>+ selectIslandGoalClarifications(data ?? [], {+ canAnswer,+ onGoalPage: goalIdFromPath(pathname) !== undefined,+ portalGoalId,+ }),+ [canAnswer, data, pathname, portalGoalId],+ );+};diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex d192982a66f..f07deab935d 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -363,6 +363,8 @@ export const isMyTaskListKey = (key: unknown): boolean =>export const goalKeys = {graph: def('goal:graph', (goalId: string) => ['goal:graph', goalId]),metricSeries: def('goal:metricSeries', (goalId: string) => ['goal:metricSeries', goalId]),+ /** Clarifications waiting on the user across every goal they own. */+ pendingClarifications: def('goal:pendingClarifications', () => ['goal:pendingClarifications']),/** Goals whose planning conversation is this topic (`subject_type = 'topic'`). */topicGoals: def('goal:topicGoals', (topicId: string) => ['goal:topicGoals', topicId]),};diff --git a/src/services/goal.ts b/src/services/goal.tsindex b6900b7ff2f..15c31bf435f 100644--- a/src/services/goal.ts+++ b/src/services/goal.ts@@ -93,6 +93,18 @@ class GoalService {resume = async (id: string) => lambdaClient.goal.resume.mutate({ id });+ /** Answer a goal's whole clarification round; the goal re-plans once with every answer. */+ answerClarifications = async (params: {+ answers: Array<{ decisionId: string; optionId: string; resolution?: string }>;+ id: string;+ }) => lambdaClient.goal.answerClarifications.mutate(params);++ /** Clarifications still waiting on the user, grouped by goal. */+ pendingClarifications = async () => {+ const { data } = await lambdaClient.goal.pendingClarifications.query();+ return data ?? [];+ };+/** Resolve a pending decision gate. Does not resume a paused goal by itself. */decide = async (params: {decisionId: string;diff --git a/src/store/goal/action.ts b/src/store/goal/action.tsindex 029c0355c9b..5cfee7d7066 100644--- a/src/store/goal/action.ts+++ b/src/store/goal/action.ts@@ -42,6 +42,7 @@ const SERVER_ADVANCING_STATUSES = new Set<GoalStatus>(['planning', 'running', 'v/** Kept coarse on purpose — this is liveness, not a progress bar. */const GOAL_GRAPH_POLL_INTERVAL = 5000;+const PENDING_CLARIFICATIONS_POLL_INTERVAL = 30_000;/** A conversation rarely plans more than one goal; this only bounds a runaway topic. */const TOPIC_GOAL_FETCH_LIMIT = 20;@@ -110,6 +111,15 @@ export class GoalActionImpl {await this.refreshGoalGraph(goalId);};+ /** Answer a goal's clarification round in one call, then refresh every view of it. */+ answerGoalClarifications = async (+ goalId: string,+ answers: Array<{ decisionId: string; optionId: string; resolution?: string }>,+ ): Promise<void> => {+ await goalService.answerClarifications({ answers, id: goalId });+ await Promise.all([this.refreshGoalGraph(goalId), mutate(goalKeys.pendingClarifications())]);+ };+pauseGoal = async (goalId: string): Promise<void> => {await goalService.pause(goalId);await this.refreshGoalGraph(goalId);@@ -159,6 +169,18 @@ export class GoalActionImpl {return result;};+ /**+ * Clarifications waiting on the user across their goals — what the global+ * island asks when the user is not on that goal's page. A goal parks until+ * answered, so a slow poll plus focus revalidation is enough.+ */+ useFetchPendingClarifications = (enabled: boolean) =>+ useClientDataSWR(+ enabled ? goalKeys.pendingClarifications() : null,+ () => goalService.pendingClarifications(),+ { refreshInterval: PENDING_CLARIFICATIONS_POLL_INTERVAL, revalidateOnFocus: true },+ );+/** The Goal Graph snapshot behind the process-control surface. */useFetchGoalGraph = (goalId?: string | null) =>useClientDataSWR(goalId ? goalKeys.graph(goalId) : null, () => goalService.getGraph(goalId!), {