Skip to content

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

โœจ feat(goal): plan the exploration structure before executing (#18942)

Arvin Xud8722c7a8452
diff --git a/apps/cli/src/commands/goal.ts b/apps/cli/src/commands/goal.ts
index 8689e0b63a9..4f1ccb5b61b 100644
--- a/apps/cli/src/commands/goal.ts
+++ b/apps/cli/src/commands/goal.ts
@@ -82,7 +82,11 @@ export function registerGoalCommand(program: Command) {
.command('create <title>')
.description('Create a standalone goal and seed its graph')
.option('-r, --requirement <text>', 'Acceptance requirement')
- .option('-w, --work <title...>', 'Initial work node titles')
+ .option(
+ '-i, --instruction <text>',
+ "The ask in the user's own words, shown on the problem node",
+ )
+ .option('-w, --work <title...>', 'Initial work node titles (omit to let the planner decompose)')
.option('--agent <id>', 'Responsible agent ID')
.option('--project <id>', 'Project ID')
.option('--max-rounds <n>', 'Maximum goal rounds')
@@ -117,6 +121,7 @@ export function registerGoalCommand(program: Command) {
: undefined,
maxRounds: options.maxRounds ? Number.parseInt(options.maxRounds, 10) : undefined,
maxTotalCost: options.maxCost ? Number.parseFloat(options.maxCost) : undefined,
+ problemDescription: options.instruction,
projectId: options.project,
requirement: options.requirement,
title,
diff --git a/apps/server/src/routers/lambda/goal.ts b/apps/server/src/routers/lambda/goal.ts
index 627ce5b769a..50105ff1af0 100644
--- a/apps/server/src/routers/lambda/goal.ts
+++ b/apps/server/src/routers/lambda/goal.ts
@@ -114,6 +114,7 @@ export const goalRouter = router({
.optional(),
maxRounds: z.number().int().positive().optional(),
maxTotalCost: z.number().positive().optional(),
+ problemDescription: z.string().optional(),
projectId: z.string().optional(),
requirement: z.string().optional(),
title: z.string().min(1),
diff --git a/apps/server/src/services/goal/criteriaGenerator.ts b/apps/server/src/services/goal/criteriaGenerator.ts
index 0081f59e130..b0e5b24205b 100644
--- a/apps/server/src/services/goal/criteriaGenerator.ts
+++ b/apps/server/src/services/goal/criteriaGenerator.ts
@@ -3,8 +3,11 @@ import { isProgrammaticTestCheck } from '@lobechat/const/verify';
import type { TracingOptions } from '@lobechat/llm-generation-tracing';
import {
chainGoalCriteriaDraft,
+ chainGoalDecompose,
GOAL_CRITERIA_DRAFT_JSON_SCHEMA,
GOAL_CRITERIA_DRAFT_PROMPT_VERSION,
+ GOAL_DECOMPOSE_JSON_SCHEMA,
+ GOAL_DECOMPOSE_PROMPT_VERSION,
VERIFY_EVIDENCE_MODALITIES,
VERIFY_EVIDENCE_SCOPES,
VERIFY_EVIDENCE_TYPES,
@@ -64,6 +67,16 @@ export interface GoalPlanDraft {
title: string;
}
+const decompositionSchema = z.object({
+ problemStatement: z.string().min(1),
+ works: z
+ .array(z.object({ instruction: z.string().min(1), title: z.string().min(1).max(80) }))
+ .min(1)
+ .max(5),
+});
+
+export type GoalDecompositionDraft = z.infer<typeof decompositionSchema>;
+
export class GoalCriteriaGeneratorService {
constructor(
private readonly db: LobeChatDatabase,
@@ -118,4 +131,38 @@ export class GoalCriteriaGeneratorService {
return { ...parsed.data, criteria };
}
+
+ /**
+ * Plan the opening exploration structure for a goal that has no work yet:
+ * the core question plus 1โ€“5 independent directions. Returns undefined on
+ * any model/schema failure so the coordinator can fall back to a single
+ * work seeded from the raw requirement instead of stalling the goal.
+ */
+ async decompose(params: { 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(
+ {
+ ...chainGoalDecompose(params),
+ ...modelConfig,
+ schema: GOAL_DECOMPOSE_JSON_SCHEMA,
+ thinking: { type: 'disabled' },
+ },
+ {
+ metadata: { trigger: 'goal_decompose' },
+ tracing: {
+ promptVersion: GOAL_DECOMPOSE_PROMPT_VERSION,
+ scenario: TRACING_SCENARIOS.GoalDecompose,
+ schemaName: GOAL_DECOMPOSE_JSON_SCHEMA.name,
+ } satisfies TracingOptions,
+ },
+ );
+
+ const parsed = decompositionSchema.safeParse(raw);
+ if (!parsed.success) {
+ log('goal decomposition did not match schema: %O', parsed.error.flatten());
+ return undefined;
+ }
+ return parsed.data;
+ }
}
diff --git a/apps/server/src/services/goal/decideNextMove.test.ts b/apps/server/src/services/goal/decideNextMove.test.ts
index 000023262e0..4b2cd7848e0 100644
--- a/apps/server/src/services/goal/decideNextMove.test.ts
+++ b/apps/server/src/services/goal/decideNextMove.test.ts
@@ -202,8 +202,13 @@ describe('decideNextMove', () => {
});
describe('with no ready work', () => {
- it('reports an empty graph and a fully blocked one differently', () => {
- expect(decide(graph()).message).toContain('add a work node');
+ it('plans the decomposition for an empty graph, parks a fully blocked one', () => {
+ // A goal with no work has not been planned yet โ€” that is the planner's
+ // cue, not a dead end.
+ expect(decide(graph())).toMatchObject({
+ branch: 'plan_decomposition',
+ outcome: 'advanced',
+ });
const blocked = graph({
edges: [
diff --git a/apps/server/src/services/goal/decideNextMove.ts b/apps/server/src/services/goal/decideNextMove.ts
index f67025f0e67..afa90c69a94 100644
--- a/apps/server/src/services/goal/decideNextMove.ts
+++ b/apps/server/src/services/goal/decideNextMove.ts
@@ -180,19 +180,27 @@ const decideWithoutFrontier = (
): GoalMove => {
const base = { candidates };
const taskNodes = graph.nodes.filter((node) => node.kind === 'task');
- const allWorkTerminal =
- taskNodes.length > 0 && taskNodes.every((node) => TERMINAL_NODE_STATUSES.has(node.status));
+
+ // A goal with no work at all has not been planned yet โ€” decompose it into
+ // explorable directions before anything runs, instead of parking it.
+ if (taskNodes.length === 0) {
+ return {
+ ...base,
+ branch: 'plan_decomposition',
+ message: 'Goal has no work yet; plan its exploration structure first',
+ outcome: 'advanced',
+ };
+ }
+
+ const allWorkTerminal = taskNodes.every((node) => TERMINAL_NODE_STATUSES.has(node.status));
if (!allWorkTerminal) {
- // Nothing here moves without a person: either there is no Work at all, or
- // every remaining Work is blocked and nothing is running to unblock it.
+ // Nothing here moves without a person: every remaining Work is blocked and
+ // nothing is running to unblock it.
return {
...base,
branch: 'no_frontier',
- message:
- taskNodes.length === 0
- ? 'No work frontier exists; add a work node'
- : 'No work node is ready; resolve its dependencies first',
+ message: 'No work node is ready; resolve its dependencies first',
outcome: 'no_progress',
};
}
diff --git a/apps/server/src/services/goal/index.test.ts b/apps/server/src/services/goal/index.test.ts
index 60a4b92e1ae..209d672385f 100644
--- a/apps/server/src/services/goal/index.test.ts
+++ b/apps/server/src/services/goal/index.test.ts
@@ -7,6 +7,7 @@ import { getTestDB } from '@/database/core/getTestDB';
import { AcceptanceModel } from '@/database/models/acceptance';
import { AgentOperationModel } from '@/database/models/agentOperation';
import { GoalModel } from '@/database/models/goal';
+import { GoalGraphModel } from '@/database/models/goalGraph';
import { TaskModel } from '@/database/models/task';
import { TaskTopicModel } from '@/database/models/taskTopic';
import {
@@ -28,6 +29,7 @@ import { AgentRuntimeCoordinator } from '@/server/modules/AgentRuntime/AgentRunt
import { TaskService } from '../task';
import { TaskRunnerService } from '../taskRunner';
+import { GoalCriteriaGeneratorService } from './criteriaGenerator';
import { GoalService } from './index';
import type { GoalTickObservation } from './traceObservation';
@@ -214,12 +216,61 @@ describe('GoalService', () => {
expect(await service.graph(graph.goal.id)).toBeDefined();
});
+ it('plans the decomposition when a goal has no work yet', async () => {
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
+ problemStatement: 'ๆ ธๅฟƒ้—ฎ้ข˜็š„ไธ€ๅฅ่ฏ้™ˆ่ฟฐ',
+ works: [
+ { instruction: 'ๆ”ถ้›†ๅŽŸๅง‹ๆๆ–™', title: 'ๆ–นๅ‘A:ๆ”ถ้›†' },
+ { instruction: 'ๅˆ†ๆžๅนถ็ปผๅˆ็ป“่ฎบ', title: 'ๆ–นๅ‘B:ๅˆ†ๆž' },
+ ],
+ });
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({
+ problemDescription: '็”จๆˆท็š„ๅŽŸ่ฏ',
+ requirement: 'ๅฎŒๆ•ด้œ€ๆฑ‚ไธŽ้ชŒๆ”ถๆ ‡ๅ‡†ๅ…จๆ–‡',
+ title: 'Complex ask',
+ });
+ // The seeded graph carries the user's own words, not the contract blob.
+ expect(graph.nodes.find((n) => n.kind === 'problem')?.description).toBe('็”จๆˆท็š„ๅŽŸ่ฏ');
+ expect(graph.nodes.filter((n) => n.kind === 'task')).toHaveLength(0);
+
+ const result = await service.tick(graph.goal.id);
+
+ expect(result.outcome).toBe('advanced');
+ const after = await service.graph(graph.goal.id);
+ expect(after.nodes.filter((n) => n.kind === 'task').map((n) => n.title)).toEqual([
+ 'ๆ–นๅ‘A:ๆ”ถ้›†',
+ 'ๆ–นๅ‘B:ๅˆ†ๆž',
+ ]);
+ expect(after.nodes.find((n) => n.kind === 'problem')?.description).toBe('ๆ ธๅฟƒ้—ฎ้ข˜็š„ไธ€ๅฅ่ฏ้™ˆ่ฟฐ');
+ expect(after.edges.filter((e) => e.kind === 'decomposes')).toHaveLength(2);
+ });
+
+ it('falls back to a single work when the planner fails, instead of stalling', async () => {
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockRejectedValue(
+ new Error('model unavailable'),
+ );
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({ problemDescription: 'ๅŽŸ่ฏ', title: 'Nothing to do' });
+
+ const result = await service.tick(graph.goal.id);
+
+ expect(result.outcome).toBe('advanced');
+ const tasks = (await service.graph(graph.goal.id)).nodes.filter((n) => n.kind === 'task');
+ expect(tasks).toHaveLength(1);
+ expect(tasks[0].description).toBe('ๅŽŸ่ฏ');
+ });
+
it('parks a goal nothing can move so the sweep stops re-picking it', async () => {
- // A goal with no Work can only report `no_progress`. Left `running` it is
- // selected by every newest-first scan forever, and enough of them starve
- // every other stalled goal out of the sweep's window.
+ // Every remaining Work is blocked and nothing runs to unblock it. Left
+ // `running` it is selected by every newest-first scan forever, and enough
+ // of them starve every other stalled goal out of the sweep's window.
const service = new GoalService(serverDB, userId);
- const graph = await service.create({ title: 'Nothing to do' });
+ const graph = await service.create({ title: 'Deadlocked', work: ['A', 'B'] });
+ const [a, b] = graph.nodes.filter((n) => n.kind === 'task');
+ const graphModel = new GoalGraphModel(serverDB, userId);
+ await graphModel.createEdge(graph.goal.id, a.id, b.id, 'depends_on');
+ await graphModel.createEdge(graph.goal.id, b.id, a.id, 'depends_on');
const result = await service.tick(graph.goal.id);
diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.ts
index 852c727c675..f9a782b0bad 100644
--- a/apps/server/src/services/goal/index.ts
+++ b/apps/server/src/services/goal/index.ts
@@ -29,6 +29,7 @@ import { AgentRuntimeCoordinator } from '@/server/modules/AgentRuntime/AgentRunt
import { TaskService } from '../task';
import { TaskRunnerService } from '../taskRunner';
import { AcceptanceService } from '../verify/acceptanceService';
+import { GoalCriteriaGeneratorService } from './criteriaGenerator';
import {
decideNextMove,
GOAL_ACCEPTANCE_TASK_TITLE,
@@ -64,10 +65,19 @@ export interface CreateGoalGraphInput {
createdByAgentId?: string;
maxRounds?: number;
maxTotalCost?: number;
+ /**
+ * The user's ask in their own words, shown on the seeded problem node. The
+ * full `requirement` (with its acceptance boilerplate) stays on the goal row
+ * โ€” copying it onto the node made every drill-down read like a contract.
+ */
+ problemDescription?: string;
projectId?: string;
requirement?: string;
title: string;
- /** Seed Work nodes, in dependency-free order. A plain string is title-only. */
+ /**
+ * Seed Work nodes, in dependency-free order. A plain string is title-only.
+ * When omitted, the coordinator plans the decomposition on first advance.
+ */
work?: Array<CreateGoalWorkInput | string>;
}
@@ -160,7 +170,7 @@ export class GoalService {
try {
const problem = await authorGraph.createNode(goal.id, {
createdByAgentId: input.createdByAgentId,
- description: input.requirement,
+ description: input.problemDescription ?? input.requirement,
kind: 'problem',
status: 'active',
title: input.title,
@@ -413,6 +423,10 @@ export class GoalService {
return observe(await this.settleTerminalAcceptance(graph, move, effects));
}
+ case 'plan_decomposition': {
+ return observe(await this.planDecomposition(graph, effects));
+ }
+
case 'no_frontier': {
// Say so on the row instead of leaving a goal that reads as `running`
// while it cannot run โ€” and, just as importantly, take it out of the
@@ -930,6 +944,51 @@ export class GoalService {
.filter(Boolean)
.join('\n\n');
+ /**
+ * Turn a goal with no work into an explorable structure: the LLM plans the
+ * core question plus 1โ€“5 independent directions, each carrying only its own
+ * deliverable requirements. A planning failure degrades to one work seeded
+ * from the raw requirement โ€” the goal must never stall on its planner.
+ */
+ private planDecomposition = async (graph: GoalGraphSnapshot, effects: GoalAdvanceEffect[]) => {
+ const goalId = graph.goal.id;
+ const problem = graph.nodes.find((node) => node.kind === 'problem');
+ const requirement = graph.goal.requirement ?? problem?.description ?? graph.goal.title;
+
+ const generator = new GoalCriteriaGeneratorService(this.db, this.userId, this.workspaceId);
+ const plan = await generator.decompose({ requirement }).catch(() => undefined);
+
+ const works = plan?.works ?? [
+ { instruction: problem?.description ?? requirement, title: graph.goal.title },
+ ];
+
+ if (plan && problem) {
+ // The node's description becomes the planner's own words for the core
+ // question โ€” not the acceptance boilerplate the goal row keeps.
+ await this.coordinatorGraph.updateNodeDescription(goalId, problem.id, plan.problemStatement);
+ }
+
+ for (const work of works) {
+ const node = await this.coordinatorGraph.createNode(goalId, {
+ description: work.instruction,
+ kind: 'task',
+ title: work.title,
+ });
+ if (!node) continue;
+ if (problem)
+ await this.coordinatorGraph.createEdge(goalId, problem.id, node.id, 'decomposes');
+ effects.push({ nodeId: node.id, type: 'created_node', detail: work.title });
+ }
+
+ return {
+ goalId,
+ message: plan
+ ? `Planned ${works.length} exploration direction${works.length > 1 ? 's' : ''}`
+ : 'Planner unavailable; seeded a single work from the requirement',
+ outcome: 'advanced' as const,
+ };
+ };
+
private buildTaskAcceptanceRequirement = (
graph: GoalGraphSnapshot,
title: string,
@@ -947,12 +1006,14 @@ export class GoalService {
.join('\n\n');
}
+ // The full goal requirement (with its numbered acceptance list) is NOT
+ // injected here: it belongs to the terminal acceptance task above, and
+ // pasting it into every Work made each task's acceptance read as the whole
+ // contract. A Work is judged on its own outcome only.
return [
`Verify only this Work: ${title}.`,
description ? `Required Work outcome: ${description}` : undefined,
- graph.goal.requirement
- ? `Use this overall Goal requirement only to interpret requirements relevant to the current Work: ${graph.goal.requirement}`
- : undefined,
+ `This Work is one direction of the Goal "${graph.goal.title}"; the full Goal contract is verified separately at the end.`,
'Pass only when the current Work deliverable is complete and supported by concrete evidence. Ignore sibling and downstream Work deliverables; they are verified by their own Tasks.',
]
.filter(Boolean)
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/goal.ts b/apps/server/src/services/toolExecution/serverRuntimes/goal.ts
index 0ab45014639..ddf19041d39 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/goal.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/goal.ts
@@ -51,9 +51,12 @@ export const goalRuntime: ServerRuntimeRegistration = {
// passed as `maxRounds`, which counts runs across every Work in the
// graph and would strand later tasks that have not run at all.
maxTotalCost: args.maxTotalCost ?? undefined,
+ // No seed work: the coordinator plans the decomposition on first
+ // advance, so a complex ask becomes several explorable directions
+ // instead of one task that mirrors the whole request.
+ problemDescription: args.instruction,
requirement: buildGoalRequirement(args.name, drafts, args.instruction),
title: args.name,
- work: [{ description: args.instruction, title: args.name }],
});
// The TRPC `goal.create` route queues this; calling the service
// directly does not. Without it the "the server will pick it up"
diff --git a/package.json b/package.json
index 0256c0d32c6..4bcc1b28ba7 100644
--- a/package.json
+++ b/package.json
@@ -174,7 +174,6 @@
]
},
"overrides": {
- "@ant-design/icons": "6.3.2",
"@types/react": "19.2.13",
"antd": "6.3.5",
"baseline-browser-mapping": "2.10.31",
@@ -187,7 +186,7 @@
},
"dependencies": {
"@aiden0z/pptx-renderer": "^1.2.4",
- "@ant-design/icons": "6.3.2",
+ "@ant-design/icons": "^6.3.4",
"@anthropic-ai/sdk": "^0.73.0",
"@atlaskit/pragmatic-drag-and-drop": "^1.8.1",
"@atlaskit/pragmatic-drag-and-drop-hitbox": "^1.2.0",
@@ -592,7 +591,6 @@
"workerd"
],
"overrides": {
- "@ant-design/icons": "6.3.2",
"@react-pdf/image": "3.0.4",
"@types/react": "19.2.13",
"@vitest/coverage-v8": "3.2.6",
diff --git a/packages/agent-tracing/src/goal/types.ts b/packages/agent-tracing/src/goal/types.ts
index 8b4f903f133..185ec5a1cdd 100644
--- a/packages/agent-tracing/src/goal/types.ts
+++ b/packages/agent-tracing/src/goal/types.ts
@@ -27,6 +27,8 @@ export type GoalTickBranch =
| 'pending_decision'
/** No work node is eligible: none exists, or all remaining ones are blocked. */
| 'no_frontier'
+ /** The graph has no work yet โ€” decompose the goal into explorable directions first. */
+ | 'plan_decomposition'
/** Every work node finished; the goal-level acceptance contract is next. */
| 'terminal_acceptance'
/** The chosen work has no responsible task yet. */
diff --git a/packages/builtin-tool-goal/src/client/executor/index.ts b/packages/builtin-tool-goal/src/client/executor/index.ts
index b55d33d03fb..69abcd1c7ed 100644
--- a/packages/builtin-tool-goal/src/client/executor/index.ts
+++ b/packages/builtin-tool-goal/src/client/executor/index.ts
@@ -61,9 +61,11 @@ class GoalExecutor extends BaseExecutor<typeof GoalApiName> {
// passed as `maxRounds`, which counts runs across every Work in the
// graph and would strand later tasks that have not run at all.
maxTotalCost: params.maxTotalCost ?? undefined,
+ // No seed work: the coordinator plans the decomposition on first
+ // advance, turning a complex ask into several explorable directions.
+ problemDescription: params.instruction,
requirement: buildGoalRequirement(params.name, criteria, params.instruction),
title: params.name,
- work: [{ description: params.instruction, title: params.name }],
});
return await this.reportCreatedGoal(graph, criteria.length, params.name);
diff --git a/packages/const/src/llmGenerationTracing.ts b/packages/const/src/llmGenerationTracing.ts
index 295e1b4ea04..3921fa26c10 100644
--- a/packages/const/src/llmGenerationTracing.ts
+++ b/packages/const/src/llmGenerationTracing.ts
@@ -15,6 +15,7 @@ export const TRACING_SCENARIOS = {
ExpertiseTopicIngestion: 'expertise_topic_ingestion',
FollowUp: 'follow_up',
GoalCriteriaGen: 'goal_criteria_gen',
+ GoalDecompose: 'goal_decompose',
HomeBrief: 'home_brief',
InputCompletion: 'input_completion',
MemoryExtract: 'memory_extract',
diff --git a/packages/database/src/models/goalGraph.ts b/packages/database/src/models/goalGraph.ts
index 9a32f26bd5b..98b4e38a388 100644
--- a/packages/database/src/models/goalGraph.ts
+++ b/packages/database/src/models/goalGraph.ts
@@ -320,6 +320,26 @@ export class GoalGraphModel {
return node;
});
+ /** 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) =>
+ this.db.transaction(async (tx) => {
+ if (!(await this.ownedGoal(goalId, tx))) return undefined;
+ const [node] = await tx
+ .update(goalNodes)
+ .set({ description, updatedAt: new Date() })
+ .where(and(eq(goalNodes.goalId, goalId), eq(goalNodes.id, nodeId)))
+ .returning();
+ if (!node) return undefined;
+ await this.appendEvent(tx, goalId, {
+ entityId: node.id,
+ entityType: 'node',
+ eventType: 'updated',
+ reason: 'Planner refined the description',
+ taskId: node.taskId ?? undefined,
+ });
+ return node;
+ });
+
updateNodeStatus = async (
goalId: string,
nodeId: string,
diff --git a/packages/prompts/src/chains/goal.ts b/packages/prompts/src/chains/goal.ts
index 7ab51a262e8..300dc2cafab 100644
--- a/packages/prompts/src/chains/goal.ts
+++ b/packages/prompts/src/chains/goal.ts
@@ -64,6 +64,69 @@ export const GOAL_CRITERIA_DRAFT_JSON_SCHEMA = {
strict: true,
};
+/** Bump when the goal decomposition planning prompt meaningfully changes. */
+export const GOAL_DECOMPOSE_PROMPT_VERSION = 'v1';
+
+export const GOAL_DECOMPOSE_JSON_SCHEMA = {
+ name: 'goal_decomposition',
+ schema: {
+ additionalProperties: false,
+ properties: {
+ problemStatement: { maxLength: 280, minLength: 1, type: 'string' },
+ works: {
+ items: {
+ additionalProperties: false,
+ properties: {
+ instruction: { minLength: 1, type: 'string' },
+ title: { maxLength: 80, minLength: 1, type: 'string' },
+ },
+ required: ['title', 'instruction'],
+ type: 'object',
+ },
+ maxItems: 5,
+ minItems: 1,
+ type: 'array',
+ },
+ },
+ required: ['problemStatement', 'works'],
+ type: 'object' as const,
+ },
+ strict: true,
+};
+
+interface GoalDecomposeInput {
+ requirement: string;
+}
+
+/**
+ * Plan the opening exploration structure of a goal graph: the core question it
+ * answers plus the independent work directions to pursue, before anything runs.
+ */
+export const chainGoalDecompose = ({
+ requirement,
+}: GoalDecomposeInput): {
+ messages: OpenAIChatMessage[];
+} => ({
+ messages: [
+ {
+ content: [
+ 'You plan the opening exploration structure for a persistent autonomous goal.',
+ 'Decompose the goal into the core question it must answer and the independent work directions that together answer it.',
+ 'Guidelines:',
+ '- problemStatement is 1โ€“2 sentences naming the core question or outcome of the goal, in your own words. Never copy the acceptance-criteria list into it.',
+ '- Return 1โ€“5 works. A complex goal (analysis, research, multi-stage delivery) must be split into several directions that can be explored independently or in sequence โ€” e.g. gather the raw material, analyze it from distinct angles, then synthesize. A genuinely small single-step goal may stay as one work.',
+ '- Each work.title names its direction concisely; titles must be distinct from each other and from the goal name.',
+ '- Each work.instruction is a complete, self-contained brief for an autonomous agent working on that direction only: what to do, the concrete deliverable, and how that deliverable will be judged. Include only the requirements relevant to this direction โ€” never paste the full goal acceptance list into every work.',
+ '- Preserve every concrete URL, scope, constraint, and numeric threshold from the goal in whichever work it belongs to.',
+ '- Order works so that earlier ones produce what later ones consume.',
+ '- Write all fields in the language used by the goal.',
+ ].join('\n'),
+ role: 'system',
+ },
+ { content: `## Goal\n${requirement}`, role: 'user' },
+ ],
+});
+
interface GoalCriteriaDraftInput {
context?: string;
goal: string;
diff --git a/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsx b/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsx
index 53ad8ecffa0..4125293b30a 100644
--- a/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsx
+++ b/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsx
@@ -442,10 +442,12 @@ const CreateGoalContent = memo<CreateGoalContentProps>((props) => {
// graph-wide round cap, which counts runs across every Work and would
// strand the fourth task of a goal whose limit is three attempts.
maxTotalCost: budget.maxTotalCost ?? undefined,
+ // No seed work: the coordinator plans the decomposition on first
+ // advance, turning a complex ask into several explorable directions.
+ problemDescription: instruction,
projectId,
requirement: buildGoalRequirement(title, reviewedCriteria, budget.requirement),
title,
- work: [{ description: instruction, title }],
});
// `goal.create` already queued an advance; this runs the same driver so
// the goal is visibly moving by the time the modal closes even where the
diff --git a/src/features/AgentGoals/ProcessControl/Graph/GraphNode.tsx b/src/features/AgentGoals/ProcessControl/Graph/GraphNode.tsx
index 8f8c5ba3d13..4d88f29bf79 100644
--- a/src/features/AgentGoals/ProcessControl/Graph/GraphNode.tsx
+++ b/src/features/AgentGoals/ProcessControl/Graph/GraphNode.tsx
@@ -1,14 +1,14 @@
'use client';
import { Flexbox, Icon, Tooltip } from '@lobehub/ui';
-import { Text } from '@lobehub/ui/base-ui';
import { Handle, type NodeProps, Position } from '@xyflow/react';
import { createStaticStyles, cssVar, cx } from 'antd-style';
-import { FileBox, Repeat2, ShieldCheck } from 'lucide-react';
+import { FileBox, type LucideIcon, Repeat2, ShieldCheck } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { TASK_STATUS_VISUALS } from '@/components/ExecutionStatus';
+import RunningGlyph from '@/features/Home/components/RunningGlyph';
import type { GoalNodeView } from '../goalGraphViewModel';
import { KIND_COLOR, KIND_ICON } from '../shared';
@@ -44,12 +44,6 @@ const styles = createStaticStyles(({ css }) => ({
opacity 0.2s,
border-color 0.15s;
`,
- chipDot: css`
- flex: none;
- width: 5px;
- height: 5px;
- border-radius: 50%;
- `,
chipText: css`
font-size: 11px;
line-height: 16px;
@@ -58,6 +52,22 @@ const styles = createStaticStyles(({ css }) => ({
dim: css`
opacity: 0.45;
`,
+ statusRow: css`
+ display: flex;
+ gap: 10px;
+ align-items: center;
+
+ padding-block: 10px 0;
+ padding-inline: 12px;
+
+ font-family: ${cssVar.fontFamilyCode};
+ font-variant-numeric: tabular-nums;
+
+ /* The row owns the card's top padding; keep the head snug beneath it. */
+ & + div {
+ padding-block-start: 6px;
+ }
+ `,
gate: css`
border-color: ${cssVar.colorWarningBorder};
background: ${cssVar.colorWarningBg};
@@ -145,32 +155,71 @@ const styles = createStaticStyles(({ css }) => ({
`,
}));
-const useStateChip = (data: GraphNodeData): { color: string; text: string } | null => {
+interface StateChip {
+ color: string;
+ /** The task family's status glyph; running renders the animated ring instead. */
+ icon?: LucideIcon;
+ text: string;
+}
+
+const useStateChip = (data: GraphNodeData): StateChip | null => {
const { t } = useTranslation('chat');
const { isGate, running, stale, view } = data;
const { node } = view;
- if (isGate) return { color: cssVar.colorWarning, text: t('goalProcess.tag.needsDecision') };
- if (stale) return { color: cssVar.colorError, text: t('goalProcess.tag.lost') };
- if (running) return { color: cssVar.colorInfo, text: t('goalProcess.node.running') };
+ if (isGate)
+ return {
+ color: TASK_STATUS_VISUALS.paused.color,
+ icon: TASK_STATUS_VISUALS.paused.icon,
+ text: t('goalProcess.tag.needsDecision'),
+ };
+ if (stale)
+ return {
+ color: TASK_STATUS_VISUALS.failed.color,
+ icon: TASK_STATUS_VISUALS.failed.icon,
+ text: t('goalProcess.tag.lost'),
+ };
+ // Running renders the same animated ring the frontier and home surfaces use.
+ if (running)
+ return { color: TASK_STATUS_VISUALS.running.color, text: t('goalProcess.node.running') };
if (node.kind === 'task' && node.status === 'resolved')
- return { color: cssVar.colorSuccess, text: t('goalProcess.node.done') };
+ return {
+ color: TASK_STATUS_VISUALS.completed.color,
+ icon: TASK_STATUS_VISUALS.completed.icon,
+ text: t('goalProcess.node.done'),
+ };
if (node.kind === 'task' && (node.status === 'retired' || node.status === 'rejected'))
- return { color: cssVar.colorTextTertiary, text: t('goalProcess.tag.retired') };
+ return {
+ color: TASK_STATUS_VISUALS.canceled.color,
+ icon: TASK_STATUS_VISUALS.canceled.icon,
+ text: t('goalProcess.tag.retired'),
+ };
if (node.kind === 'decision' && node.status === 'resolved')
return {
color: cssVar.colorTextTertiary,
+ icon: TASK_STATUS_VISUALS.completed.icon,
text: view.humanTouches.length
? t('goalProcess.node.decidedByYou')
: t('goalProcess.node.decidedByAgent'),
};
+ // Every task reads its state in the same top row โ€” a queued one included,
+ // so "not dispatched" no longer hides in the metric strip.
+ if (node.kind === 'task')
+ return {
+ color: TASK_STATUS_VISUALS.backlog.color,
+ icon: TASK_STATUS_VISUALS.backlog.icon,
+ text: node.taskId
+ ? t(`goalProcess.nodeStatus.${node.status}` as const)
+ : t('goalProcess.node.unassigned'),
+ };
return null;
};
const RunningClock = memo<{ startedAt?: Date }>(({ startedAt }) => {
const elapsed = useElapsed(startedAt);
if (!elapsed) return null;
- return <span style={{ marginInlineStart: 'auto' }}>{elapsed}</span>;
+ // Sits right behind the state chip in the status row โ€” no auto margin.
+ return <span style={{ fontSize: 11 }}>{elapsed}</span>;
});
RunningClock.displayName = 'GoalGraphRunningClock';
@@ -202,6 +251,30 @@ const GraphNodeView = memo<NodeProps>(({ data }) => {
selected && styles.selected,
)}
>
+ {/* Status reads first: its own top row, left-aligned, with the running
+ clock riding right behind it (review: bottom placements read poorly). */}
+ {(chip || view.humanTouches.length > 0) && (
+ <div className={styles.statusRow}>
+ {chip && (
+ <Flexbox horizontal align={'center'} gap={5}>
+ {chip.icon ? (
+ <Icon color={chip.color} icon={chip.icon} size={13} />
+ ) : (
+ <RunningGlyph size={13} />
+ )}
+ <span className={styles.chipText} style={{ color: chip.color }}>
+ {chip.text}
+ </span>
+ </Flexbox>
+ )}
+ {running && <RunningClock startedAt={view.startedAt} />}
+ {view.humanTouches.length > 0 && (
+ <Tooltip title={t('goalProcess.node.humanTouched')}>
+ <span className={styles.human}>@</span>
+ </Tooltip>
+ )}
+ </div>
+ )}
<div className={styles.head}>
<div className={styles.glyph} style={{ background: palette.soft, color: palette.line }}>
<Icon icon={KIND_ICON[node.kind]} size={16} />
@@ -210,45 +283,18 @@ const GraphNodeView = memo<NodeProps>(({ data }) => {
<span className={styles.title}>{node.title}</span>
{subtitle && <span className={styles.subtitle}>{subtitle}</span>}
</Flexbox>
- {/* State and human participation sit inside the card, on the header's
- trailing edge. Floating them on the card's outline collided with
- the edges and arrowheads routed around it. */}
- <Flexbox horizontal align={'center'} gap={6} style={{ flex: 'none' }}>
- {view.humanTouches.length > 0 && (
- <Tooltip title={t('goalProcess.node.humanTouched')}>
- <span className={styles.human}>@</span>
- </Tooltip>
- )}
- {chip && (
- <Flexbox horizontal align={'center'} gap={4}>
- <span className={styles.chipDot} style={{ background: chip.color }} />
- <span className={styles.chipText} style={{ color: chip.color }}>
- {chip.text}
- </span>
- </Flexbox>
- )}
- </Flexbox>
</div>
{isTask && (
<div className={styles.metrics}>
- {node.taskId ? (
+ {/* "Not dispatched" moved to the status row with every other
+ state; an unassigned task simply has no verifier metric yet. */}
+ {node.taskId && (
<Tooltip title={t('goalProcess.node.verifierTooltip')}>
<span className={styles.metric}>
<Icon icon={ShieldCheck} size={13} />
{t('goalProcess.node.verifier')}
</span>
</Tooltip>
- ) : (
- <span className={styles.metric}>
- <Icon
- color={TASK_STATUS_VISUALS.backlog.color}
- icon={TASK_STATUS_VISUALS.backlog.icon}
- size={13}
- />
- <Text fontSize={11} type={'secondary'}>
- {t('goalProcess.node.unassigned')}
- </Text>
- </span>
)}
<Tooltip title={t('goalProcess.node.attemptsTooltip', { count: attempts })}>
<span className={styles.metric}>
@@ -266,7 +312,6 @@ const GraphNodeView = memo<NodeProps>(({ data }) => {
</span>
</Tooltip>
)}
- {running && <RunningClock startedAt={view.startedAt} />}
</div>
)}
</div>
diff --git a/src/features/AgentGoals/ProcessControl/Graph/index.tsx b/src/features/AgentGoals/ProcessControl/Graph/index.tsx
index ec2725d84fc..dc9e885a009 100644
--- a/src/features/AgentGoals/ProcessControl/Graph/index.tsx
+++ b/src/features/AgentGoals/ProcessControl/Graph/index.tsx
@@ -205,6 +205,18 @@ const Canvas = memo<GraphProps & { className: string; interactive: boolean; view
return layoutGraph(nodes, edges);
}, [graph, visibleIds]);
+ // Inline, the canvas hugs its content: a two-node graph in a fixed 560px
+ // frame is mostly empty margin, and `fitView` then shrinks the nodes to
+ // fill it. Sizing the frame from the layout keeps small graphs at natural
+ // node scale; 560px stays the ceiling so large graphs still zoom out.
+ const inlineHeight = useMemo(() => {
+ const boxes = Object.values(positions);
+ if (boxes.length === 0) return 216;
+ const top = Math.min(...boxes.map((box) => box.y));
+ const bottom = Math.max(...boxes.map((box) => box.y + box.height));
+ return Math.min(560, Math.max(216, bottom - top + 72));
+ }, [positions]);
+
const flowNodes: FlowNode[] = useMemo(
() =>
graph.nodes
@@ -269,7 +281,7 @@ const Canvas = memo<GraphProps & { className: string; interactive: boolean; view
}, [view, flowNodes.length, fitView]);
return (
- <div className={className}>
+ <div className={className} style={interactive ? undefined : { height: inlineHeight }}>
{/* Inline, the map is a picture: it settles on `fitView` and stays
there. Panning or zooming it inside a scrolling page moves the graph
under the cursor while the page moves too, and leaves no way back to
diff --git a/src/services/goal.ts b/src/services/goal.ts
index 3dbd2b21e5c..14ae26a6a36 100644
--- a/src/services/goal.ts
+++ b/src/services/goal.ts
@@ -27,6 +27,8 @@ class GoalService {
createdByAgentId?: string;
maxRounds?: number;
maxTotalCost?: number;
+ /** The user's ask in their own words โ€” shown on the seeded problem node. */
+ problemDescription?: string;
projectId?: string;
requirement?: string;
title: string;