Skip to content

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

πŸ› fix(goal): make the goal agent the supervisor and fix exploration graph layout (#19578)

Arvin Xu73a2f2ec658e
diff --git a/apps/cli/src/commands/goal.ts b/apps/cli/src/commands/goal.ts
index 18ecfb49f42..d0d71f45fb3 100644
--- a/apps/cli/src/commands/goal.ts
+++ b/apps/cli/src/commands/goal.ts
@@ -216,7 +216,14 @@ export function registerGoalCommand(program: Command) {
"The ask in the user's own words, shown on the problem node",
)
.option('-t, --task <title...>', 'Initial task node titles (omit to let the planner decompose)')
- .option('--agent <id>', 'Responsible agent ID')
+ .option(
+ '--agent <id>',
+ 'Goal agent: supervises and plans the goal (defaults to the current agent)',
+ )
+ .option(
+ '--task-agent <id>',
+ "Dedicated executor for the goal's tasks (defaults to the goal agent)",
+ )
.option('--project <id>', 'Project ID')
.option('--explore <instruction>', 'Explore alternatives using completed experiment results')
.option('--max-experiments <n>', 'Maximum experiment nodes (requires --explore, default 10)')
@@ -255,8 +262,10 @@ export function registerGoalCommand(program: Command) {
options.maxAttemptsPerTask ||
options.maxStepsPerRun ||
options.operationLeaseTimeoutMs ||
- options.maxConcurrentTasks
+ options.maxConcurrentTasks ||
+ options.taskAgent
? {
+ taskAgentId: options.taskAgent,
manager: options.maxManagerTurns
? { maxTurns: Number(options.maxManagerTurns) }
: undefined,
@@ -497,7 +506,9 @@ export function registerGoalCommand(program: Command) {
goal
.command('set-agent <id> <agent>')
- .description('Hand the goal to a different responsible agent (unfinished tasks follow)')
+ .description(
+ 'Hand the goal to a different supervising agent (its unfinished tasks follow unless the goal has a task agent)',
+ )
.option('--goal-only', 'Only change the goal-level agent; leave existing tasks as assigned')
.action(async (id: string, agentId: string, options: { goalOnly?: boolean }) => {
const result = await (
@@ -506,10 +517,30 @@ export function registerGoalCommand(program: Command) {
log.info(result.message);
});
+ goal
+ .command('set-task-agent <id> <agent>')
+ .description(
+ 'Route the goal\'s tasks to a dedicated executor; "none" hands them back to the goal agent',
+ )
+ .option('--goal-only', 'Only change future tasks; leave existing tasks as assigned')
+ .action(async (id: string, agent: string, options: { goalOnly?: boolean }) => {
+ const result = await (
+ await getTrpcClient()
+ ).goal.setTaskAgent.mutate({
+ agentId: agent === 'none' ? null : agent,
+ goalOnly: options.goalOnly,
+ id,
+ });
+ log.info(result.message);
+ });
+
goal
.command('restart <id>')
.description('Start every unfinished task over (cancel stale runs, reset to backlog)')
- .option('--agent <id>', 'Also hand the goal and restarted tasks to this agent')
+ .option(
+ '--agent <id>',
+ "Also hand the restarted tasks (and the goal's executor slot) to this agent",
+ )
.action(async (id: string, options: { agent?: string }) => {
const result = await (
await getTrpcClient()
diff --git a/apps/server/src/routers/lambda/goal.ts b/apps/server/src/routers/lambda/goal.ts
index 4da606a2254..0e71fad5b99 100644
--- a/apps/server/src/routers/lambda/goal.ts
+++ b/apps/server/src/routers/lambda/goal.ts
@@ -218,6 +218,8 @@ export const goalRouter = router({
maxIncidents: z.number().int().min(1).max(100).optional(),
})
.optional(),
+ /** Dedicated executor for the goal's Tasks; the goal agent supervises. */
+ taskAgentId: z.string().min(1).optional(),
recovery: z
.object({
maxAttemptsPerTask: z.number().int().positive().optional(),
@@ -520,7 +522,8 @@ export const goalRouter = router({
}),
/**
- * Hand the goal to a different responsible agent. Unfinished Tasks follow by
+ * Hand the goal to a different agent β€” the one that supervises and plans it.
+ * When that agent also does the goal's Tasks, unfinished ones follow by
* default (`goalOnly` keeps them); Tasks mid-run switch on their next attempt.
*/
setAgent: goalWriteProcedure
@@ -547,6 +550,34 @@ export const goalRouter = router({
}
}),
+ /**
+ * Route the goal's Tasks to a dedicated executor (`null` hands them back to
+ * the goal agent). Unfinished Tasks follow unless `goalOnly` is set.
+ */
+ setTaskAgent: goalWriteProcedure
+ .input(
+ idInput.extend({ agentId: z.string().min(1).nullable(), goalOnly: z.boolean().optional() }),
+ )
+ .mutation(async ({ ctx, input: { id, agentId, goalOnly } }) => {
+ try {
+ const goal = await ctx.goalModel.findById(id);
+ if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });
+ assertWorkspaceRowManageable(ctx, goal.userId, 'goal');
+
+ const data = await ctx.goalService.setTaskAgent(id, agentId, { goalOnly });
+ const reassigned = data.reassignedTaskIds.length;
+ return {
+ data,
+ message: reassigned
+ ? `Task agent updated; ${reassigned} task(s) reassigned`
+ : 'Task agent updated',
+ success: true,
+ };
+ } catch (error) {
+ mapGoalError(error, 'setTaskAgent');
+ }
+ }),
+
setBudget: goalWriteProcedure
.input(
idInput.extend({
diff --git a/apps/server/src/services/goal/index.test.ts b/apps/server/src/services/goal/index.test.ts
index 019cae810e7..b5fa387670d 100644
--- a/apps/server/src/services/goal/index.test.ts
+++ b/apps/server/src/services/goal/index.test.ts
@@ -282,7 +282,7 @@ describe('GoalService', () => {
.set({
config: {
...originalConfig,
- manager: managerEnabled ? { agentId: 'manager' } : undefined,
+ manager: managerEnabled ? {} : undefined,
managerState: {
consumed: true,
readyForAcceptance: true,
@@ -827,6 +827,103 @@ describe('GoalService', () => {
await expect(service.setAgent(graph.goal.id, 'agt_missing')).rejects.toThrow();
});
+ it('falls back to the goal agent when the dedicated executor was deleted', async () => {
+ await serverDB.insert(agents).values([
+ { id: 'agt_lead_fallback', slug: 'agt-lead-fallback', userId },
+ { id: 'agt_gone_executor', slug: 'agt-gone-executor', userId },
+ ]);
+ const service = new GoalService(serverDB, userId);
+ const taskModel = new TaskModel(serverDB, userId);
+ const graph = await service.create({
+ agentId: 'agt_lead_fallback',
+ config: { taskAgentId: 'agt_gone_executor' },
+ tasks: ['Only task'],
+ title: 'Executor deleted',
+ });
+ await serverDB.delete(agents).where(eq(agents.id, 'agt_gone_executor'));
+
+ const created = await service.tick(graph.goal.id);
+
+ expect(created.taskId).toBeTruthy();
+ expect((await taskModel.findById(created.taskId!))?.assigneeAgentId).toBe('agt_lead_fallback');
+ });
+
+ it('writes only the executor slot, so a concurrent policy edit survives', async () => {
+ await serverDB.insert(agents).values([
+ { id: 'agt_policy_lead', slug: 'agt-policy-lead', userId },
+ { id: 'agt_policy_worker', slug: 'agt-policy-worker', userId },
+ ]);
+ const service = new GoalService(serverDB, userId);
+ const model = new GoalModel(serverDB, userId);
+ const graph = await service.create({ agentId: 'agt_policy_lead', title: 'Policy race' });
+ // setTaskAgent reads the row, then a budget edit lands before it writes.
+ const stale = (await model.findById(graph.goal.id))!;
+ await model.update(graph.goal.id, { config: { ...stale.config, maxConcurrentTasks: 5 } });
+ // `findById` is an instance arrow property, so spy on the service's own model.
+ const serviceModel = (service as unknown as { goalModel: GoalModel }).goalModel;
+ vi.spyOn(serviceModel, 'findById').mockResolvedValueOnce(stale);
+
+ const result = await service.setTaskAgent(graph.goal.id, 'agt_policy_worker');
+
+ expect(result.goal.config?.taskAgentId).toBe('agt_policy_worker');
+ expect(result.goal.config?.maxConcurrentTasks).toBe(5);
+ });
+
+ it('moves supervision without moving the tasks a dedicated executor holds', async () => {
+ await serverDB.insert(agents).values([
+ { id: 'agt_supervisor', slug: 'agt-supervisor', userId },
+ { id: 'agt_executor', slug: 'agt-executor', userId },
+ { id: 'agt_next_supervisor', slug: 'agt-next-supervisor', userId },
+ ]);
+ const service = new GoalService(serverDB, userId);
+ const taskModel = new TaskModel(serverDB, userId);
+ const graph = await service.create({
+ agentId: 'agt_supervisor',
+ config: { taskAgentId: 'agt_executor' },
+ tasks: ['Only task'],
+ title: 'Split roles',
+ });
+ expect(graph.goal.agentId).toBe('agt_supervisor');
+ const created = await service.tick(graph.goal.id);
+ expect((await taskModel.findById(created.taskId!))?.assigneeAgentId).toBe('agt_executor');
+
+ const handed = await service.setAgent(graph.goal.id, 'agt_next_supervisor');
+
+ expect(handed.goal.agentId).toBe('agt_next_supervisor');
+ expect(handed.goal.config?.taskAgentId).toBe('agt_executor');
+ expect(handed.reassignedTaskIds).toEqual([]);
+ expect((await taskModel.findById(created.taskId!))?.assigneeAgentId).toBe('agt_executor');
+ });
+
+ it('routes tasks to a dedicated executor and back to the goal agent', async () => {
+ await serverDB.insert(agents).values([
+ { id: 'agt_owner', slug: 'agt-owner', userId },
+ { id: 'agt_worker', slug: 'agt-worker', userId },
+ ]);
+ const service = new GoalService(serverDB, userId);
+ const taskModel = new TaskModel(serverDB, userId);
+ const graph = await service.create({
+ agentId: 'agt_owner',
+ tasks: ['Only task'],
+ title: 'Delegated',
+ });
+ const created = await service.tick(graph.goal.id);
+ expect((await taskModel.findById(created.taskId!))?.assigneeAgentId).toBe('agt_owner');
+
+ const delegated = await service.setTaskAgent(graph.goal.id, 'agt_worker');
+ expect(delegated.goal.agentId).toBe('agt_owner');
+ expect(delegated.goal.config?.taskAgentId).toBe('agt_worker');
+ expect(delegated.reassignedTaskIds).toEqual([created.taskId]);
+ expect((await taskModel.findById(created.taskId!))?.assigneeAgentId).toBe('agt_worker');
+
+ // Naming the goal agent clears the slot rather than duplicating it.
+ const back = await service.setTaskAgent(graph.goal.id, 'agt_owner');
+ expect(back.goal.config?.taskAgentId).toBeUndefined();
+ expect((await taskModel.findById(created.taskId!))?.assigneeAgentId).toBe('agt_owner');
+
+ await expect(service.setTaskAgent(graph.goal.id, 'agt_missing')).rejects.toThrow();
+ });
+
it('restarts unfinished tasks under a new agent and cancels the stale runs they hold', async () => {
const cancelSpy = vi.spyOn(TaskService.prototype, 'cancelTopic').mockResolvedValue();
await serverDB.insert(agents).values({ id: 'agt_restart', slug: 'agt-restart', userId });
@@ -861,6 +958,30 @@ describe('GoalService', () => {
expect(resumed.goal.status).not.toBe('paused');
});
+ it('restarts a split-role goal under a new executor without replacing its supervisor', async () => {
+ vi.spyOn(TaskService.prototype, 'cancelTopic').mockResolvedValue();
+ await serverDB.insert(agents).values([
+ { id: 'agt_lead', slug: 'agt-lead', userId },
+ { id: 'agt_first_worker', slug: 'agt-first-worker', userId },
+ { id: 'agt_second_worker', slug: 'agt-second-worker', userId },
+ ]);
+ const service = new GoalService(serverDB, userId);
+ const taskModel = new TaskModel(serverDB, userId);
+ const graph = await service.create({
+ agentId: 'agt_lead',
+ config: { taskAgentId: 'agt_first_worker' },
+ tasks: ['Stuck task'],
+ title: 'Restart split roles',
+ });
+ const created = await service.tick(graph.goal.id);
+
+ const result = await service.restart(graph.goal.id, { agentId: 'agt_second_worker' });
+
+ expect(result.goal.agentId).toBe('agt_lead');
+ expect(result.goal.config?.taskAgentId).toBe('agt_second_worker');
+ expect((await taskModel.findById(created.taskId!))?.assigneeAgentId).toBe('agt_second_worker');
+ });
+
it('cancels the failure gate a restart supersedes so the goal starts moving again', async () => {
// A restarted task's pending recovery gate is answered by the restart
// itself. Left pending, it keeps winning the coordinator's
diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.ts
index 787bd5da701..78ab89c58a5 100644
--- a/apps/server/src/services/goal/index.ts
+++ b/apps/server/src/services/goal/index.ts
@@ -24,6 +24,7 @@ import { experimentOwner, provenanceParentId } from '@lobechat/utils/goalGraph';
import { TRPCError } from '@trpc/server';
import { sql } from 'drizzle-orm';
+import { AgentModel } from '@/database/models/agent';
import { AgentOperationModel } from '@/database/models/agentOperation';
import { GoalModel } from '@/database/models/goal';
import { GoalGraphModel } from '@/database/models/goalGraph';
@@ -76,18 +77,27 @@ const TASK_DESCRIPTION_MAX_LENGTH = 255;
/** Advisory-lock namespace for goal dispatch. `0x676f_6469` is ASCII `godi`. */
const GOAL_DISPATCH_LOCK_NAMESPACE = 0x67_6f_64_69;
+/** Who does the goal's Tasks: its dedicated executor, else the goal agent itself. */
+export const goalTaskAgentId = (goal: Pick<GoalItem, 'agentId' | 'config'>) =>
+ goal.config?.taskAgentId ?? goal.agentId ?? undefined;
+
export interface CreateGoalTaskInput {
description?: string;
title: string;
}
export interface CreateGoalGraphInput {
+ /**
+ * The goal agent: it supervises the goal, runs its planning turns and does its
+ * Tasks unless `config.taskAgentId` names a dedicated executor. Defaults to
+ * `createdByAgentId`.
+ */
agentId?: string;
config?: GoalCreateConfig;
/**
* The agent that made this call, when a tool did. Distinct from `agentId`,
- * which is the agent the goal is assigned to β€” creating a goal from the modal
- * on an agent's page sets that, but the author is still the person.
+ * which is the agent the goal belongs to β€” creating a goal from the modal on
+ * an agent's page sets that, but the author is still the person.
*/
createdByAgentId?: string;
/**
@@ -137,6 +147,7 @@ const DELIVERABLE_EVENTS_PER_RUN = 200;
export class GoalService {
private readonly acceptanceService: AcceptanceService;
+ private readonly agentModel: AgentModel;
private readonly goalModel: GoalModel;
/**
* Graph writes attributed to the person who asked for them: seeding a goal,
@@ -161,6 +172,7 @@ export class GoalService {
private readonly workspaceId?: string,
) {
this.acceptanceService = new AcceptanceService(db, userId, workspaceId);
+ this.agentModel = new AgentModel(db, userId, workspaceId);
this.goalModel = new GoalModel(db, userId, workspaceId);
this.graphModel = new GoalGraphModel(db, userId, workspaceId);
this.coordinatorGraph = new GoalGraphModel(db, userId, workspaceId, {
@@ -183,8 +195,8 @@ export class GoalService {
: this.graphModel;
create = async (input: CreateGoalGraphInput): Promise<GoalGraphSnapshot> => {
- if (input.agentId) {
- await assertAgentUsableBy(this.db, input.agentId, {
+ if (input.agentId ?? input.createdByAgentId) {
+ await assertAgentUsableBy(this.db, (input.agentId ?? input.createdByAgentId)!, {
userId: this.userId,
workspaceId: this.workspaceId,
});
@@ -200,15 +212,25 @@ export class GoalService {
// Persist the structured acceptance criteria first: their ids ride on the
// goal config so the page can edit them and the terminal acceptance Task
// is gated on exactly these checks (not an AI re-derivation of the prose).
- const creatorAgentId = input.createdByAgentId ?? input.agentId;
- const { manager: managerOptions, ...options } = input.config ?? {};
+ // The goal's agent supervises it: it owns the goal list entry, the page and,
+ // in manager mode, every planning turn. An agent creating a goal for itself
+ // need not repeat its id; executors are routed separately (`taskAgentId`).
+ const goalAgentId = input.agentId ?? input.createdByAgentId;
+ const { manager: managerOptions, taskAgentId, ...options } = input.config ?? {};
const managed = managerOptions !== undefined;
let config: GoalConfig | undefined = input.config ? options : undefined;
+ if (taskAgentId && taskAgentId !== goalAgentId) {
+ await assertAgentUsableBy(this.db, taskAgentId, {
+ userId: this.userId,
+ workspaceId: this.workspaceId,
+ });
+ config = { ...config, taskAgentId };
+ }
if (managed) {
- if (!creatorAgentId) {
+ if (!goalAgentId) {
throw new TRPCError({
code: 'BAD_REQUEST',
- message: 'A main Agent requires the creating or selected Agent',
+ message: 'A main Agent requires the goal agent',
});
}
const turns = managerOptions?.maxTurns ?? 12;
@@ -222,11 +244,12 @@ export class GoalService {
// rivals: the system planner leads, supervision recovers known transport
// failures, and the main Agent is handed whatever neither can route (see
// `gateOrTakeOver`). Ordering resolves what exclusivity used to.
- await assertAgentUsableBy(this.db, creatorAgentId, {
- userId: this.userId,
- workspaceId: this.workspaceId,
- });
- config = { ...options, manager: { ...managerOptions, agentId: creatorAgentId } };
+ // Rebuilt from the known fields: a legacy caller may still send an
+ // `agentId` inside the policy, and the planning identity is the goal's.
+ config = {
+ ...config,
+ manager: { instruction: managerOptions?.instruction, maxTurns: managerOptions?.maxTurns },
+ };
}
// A supplied requirement is the user-reviewed goal document. Criteria live
// separately; only synthesize a document when the caller omitted one.
@@ -277,7 +300,7 @@ export class GoalService {
}
const goal = await this.goalModel.create({
- agentId: input.agentId ?? creatorAgentId,
+ agentId: goalAgentId,
config,
maxRounds: input.maxRounds,
maxTotalCost: input.maxTotalCost,
@@ -956,12 +979,12 @@ export class GoalService {
};
/**
- * Hand the goal to a different responsible agent. Every Task the
- * coordinator creates from here on is assigned to the new agent, and β€”
- * unless the caller opts out β€” the graph's unfinished Tasks move with it.
- * A Task mid-run keeps its current operation; the reassignment takes effect
- * on its next dispatched attempt, because `runTask` reads the assignee at
- * dispatch time.
+ * Hand the goal to a different agent. The goal agent supervises: it owns the
+ * goal page and list entry and runs every planning turn. When it also does
+ * the goal's own Tasks (no separate `taskAgentId`), every Task the
+ * coordinator creates from here on goes to the new agent and β€” unless the
+ * caller opts out β€” the unfinished ones move with it. A goal whose Tasks go
+ * to a dedicated executor keeps them there; see `setTaskAgent`.
*/
setAgent = async (
goalId: string,
@@ -975,30 +998,87 @@ export class GoalService {
const goal = await this.goalModel.update(goalId, { agentId });
if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });
- const reassignedTaskIds: string[] = [];
- if (!options?.goalOnly) {
- // Snapshot the graph AFTER the goal row moved: a task the coordinator
- // binds later inherits the new agent from the goal, and a task bound
- // before is in this snapshot β€” so no concurrently created task can slip
- // through the handoff still pointing at the previous agent.
- const graph = await this.requireGraph(goalId);
- const taskIds = graph.nodes.flatMap((node) => (node.taskId ? [node.taskId] : []));
- for (const task of await this.taskModel.findByIds(taskIds)) {
- if (task.status === 'completed' || task.status === 'canceled') continue;
- if (task.assigneeAgentId === agentId) continue;
- await this.taskModel.update(task.id, { assigneeAgentId: agentId });
- reassignedTaskIds.push(task.id);
- }
+ const reassignedTaskIds =
+ options?.goalOnly || goal.config?.taskAgentId
+ ? []
+ : await this.reassignUnfinishedTasks(goalId, agentId);
+ return { goal, reassignedTaskIds };
+ };
+
+ /**
+ * Route the goal's Tasks to a dedicated executor, or back to the goal agent
+ * with `null`. The goal agent keeps supervising either way. Unfinished Tasks
+ * move with the change unless the caller opts out.
+ */
+ setTaskAgent = async (
+ goalId: string,
+ agentId: string | null,
+ options?: { goalOnly?: boolean },
+ ): Promise<{ goal: GoalItem; reassignedTaskIds: string[] }> => {
+ if (agentId) {
+ await assertAgentUsableBy(this.db, agentId, {
+ userId: this.userId,
+ workspaceId: this.workspaceId,
+ });
}
+ const current = await this.goalModel.findById(goalId);
+ if (!current) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });
+ // Naming the goal agent itself is the same as clearing: one agent, one slot.
+ const goal = await this.goalModel.updateTaskAgentId(
+ goalId,
+ agentId && agentId !== current.agentId ? agentId : null,
+ );
+ if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });
+
+ const assignee = goalTaskAgentId(goal);
+ const reassignedTaskIds =
+ options?.goalOnly || !assignee ? [] : await this.reassignUnfinishedTasks(goalId, assignee);
return { goal, reassignedTaskIds };
};
+ /**
+ * The agent the next coordinator-created Task goes to.
+ *
+ * `taskAgentId` lives in JSON, so deleting the executor does not null it the
+ * way the `agent_id` foreign key is nulled. Handing that stale id to
+ * `createTask` fails with NOT_FOUND on every tick and the goal can never
+ * create work again β€” so a missing executor falls back to the goal agent.
+ */
+ private resolveTaskAssignee = async (goal: GoalItem) => {
+ const taskAgentId = goal.config?.taskAgentId;
+ if (taskAgentId && !(await this.agentModel.existsById(taskAgentId)))
+ return goal.agentId ?? undefined;
+ return goalTaskAgentId(goal);
+ };
+
+ /**
+ * Snapshot the graph AFTER the goal row moved: a task the coordinator binds
+ * later inherits the new assignee from the goal, and a task bound before is in
+ * this snapshot β€” so no concurrently created task can slip through the
+ * handoff still pointing at the previous agent. A Task mid-run keeps its
+ * current operation; `runTask` reads the assignee at its next dispatch.
+ */
+ private reassignUnfinishedTasks = async (goalId: string, agentId: string) => {
+ const graph = await this.requireGraph(goalId);
+ const taskIds = graph.nodes.flatMap((node) => (node.taskId ? [node.taskId] : []));
+ const reassigned: string[] = [];
+ for (const task of await this.taskModel.findByIds(taskIds)) {
+ if (task.status === 'completed' || task.status === 'canceled') continue;
+ if (task.assigneeAgentId === agentId) continue;
+ await this.taskModel.update(task.id, { assigneeAgentId: agentId });
+ reassigned.push(task.id);
+ }
+ return reassigned;
+ };
+
/**
* Start every unfinished Task node over: interrupt the run it may still be
* holding, clear the failure it may be parked on, and return the Task to
* `backlog` so the next coordinator tick dispatches it afresh. Optionally
- * hands the goal (and the restarted Tasks) to a different agent in the same
- * gesture. Resolved nodes and their completed Tasks are left untouched.
+ * hands the restarted Tasks to a different agent in the same gesture β€” the
+ * goal's executor slot moves with them: `taskAgentId` when the goal routes
+ * work to a dedicated executor, otherwise the goal agent that does its own
+ * Tasks. Resolved nodes and their completed Tasks are left untouched.
*/
restart = async (
goalId: string,
@@ -1066,7 +1146,9 @@ export class GoalService {
// its tasks and live runs still belong to the old one.
let goal = graph.goal;
if (options?.agentId) {
- const updated = await this.goalModel.update(goalId, { agentId: options.agentId });
+ const updated = goal.config?.taskAgentId
+ ? await this.goalModel.updateTaskAgentId(goalId, options.agentId)
+ : await this.goalModel.update(goalId, { agentId: options.agentId });
if (!updated) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });
goal = updated;
}
@@ -1596,7 +1678,7 @@ export class GoalService {
.filter(Boolean)
.join('\n\n');
task = await this.taskService.createTask({
- assigneeAgentId: graph.goal.agentId ?? undefined,
+ assigneeAgentId: await this.resolveTaskAssignee(graph.goal),
config: { checkpoint: { topic: { after: false } } },
description: description?.slice(0, TASK_DESCRIPTION_MAX_LENGTH),
instruction: this.buildTaskInstruction(graph, frontier.title, description),
diff --git a/apps/server/src/services/goal/manager.README.md b/apps/server/src/services/goal/manager.README.md
index 81f5e731cae..a1054e3d1ee 100644
--- a/apps/server/src/services/goal/manager.README.md
+++ b/apps/server/src/services/goal/manager.README.md
@@ -1,6 +1,15 @@
# CLI main Agent Goals
-`lh goal create "Research objective" --agent <agent-id> --requirement "Delivery contract" --max-manager-turns 12 --max-rounds 10`
+`lh goal create "Research objective" --agent <agent-id> --task-agent <executor-id> --requirement "Delivery contract" --max-manager-turns 12 --max-rounds 10`
+
+The main Agent is the goal's own `agentId`: the agent that supervises the goal,
+owns its entry in the agent's goal list, and runs every planning turn. `--agent`
+defaults to `LOBEHUB_AGENT_ID` in the CLI and to `createdByAgentId` for the
+application tool. `config.manager` carries only the turn policy, never an
+identity. `--task-agent` (`config.taskAgentId`) routes the Tasks the coordinator
+creates to a dedicated executor; without it the goal agent does its own Tasks.
+`lh goal set-agent` hands supervision to another agent; `lh goal set-task-agent`
+changes the executor. Neither replaces the other.
The main Agent must have a working shell and an authenticated `lh` CLI in its
execution environment (for example a configured device Kimi/Codex Agent). Its
@@ -8,12 +17,10 @@ normal Agent configuration selects the runtime; dispatch uses the same
`execAgent` service as `lh agent run`. There is no exclusive supervisor tool set.
Manager mode is explicit: pass `--max-manager-turns` through the CLI or
`config.manager` through the API after ensuring the Agent has a working CLI.
-The application tool supplies `createdByAgentId`; the CLI inherits
-`LOBEHUB_AGENT_ID`. A person creating a Goal uses the selected `--agent` instead.
-No separate manager identity is accepted. Without explicit planning options,
-ordinary unseeded goals keep the coordinator planner. Seed/exploration/legacy
-supervision paths retain their existing planning behavior. Task assignees can
-differ, and changing them does not replace the configured main Agent.
+Without explicit planning options, ordinary unseeded goals keep the coordinator
+planner. Seed/exploration/legacy supervision paths retain their existing planning
+behavior. After a supervision handoff the next turn opens a management Topic in
+the new agent's history instead of continuing the previous agent's.
The main Agent reads `lh goal show`, `lh task view`, `lh topic view`, and document
commands. It submits a JSON file through `lh goal plan <goal-id> --token <turn> --file plan.json`. The runtime supplies `LOBEHUB_OPERATION_ID`. Plan actions:
diff --git a/apps/server/src/services/goal/manager.test.ts b/apps/server/src/services/goal/manager.test.ts
index 06c63b59a97..e6b6e52713e 100644
--- a/apps/server/src/services/goal/manager.test.ts
+++ b/apps/server/src/services/goal/manager.test.ts
@@ -189,15 +189,16 @@ describe('CLI main Agent planning', () => {
).rejects.toMatchObject({ code: 'UNAUTHORIZED' });
});
- it('explicitly dispatches the creator instead of the default Task assignee', async () => {
+ it('dispatches planning turns to the goal agent, not the task agent', async () => {
await db.insert(agents).values({ id: 'task-worker', userId });
const graph = await service().create({
- agentId: 'task-worker',
- createdByAgentId: agentId,
- title: 'Creator-managed goal',
- config: { manager: {} },
+ agentId,
+ title: 'Supervised goal',
+ config: { manager: {}, taskAgentId: 'task-worker' },
});
- expect(graph.goal.config?.manager?.agentId).toBe(agentId);
+ expect(graph.goal.agentId).toBe(agentId);
+ expect(graph.goal.config?.taskAgentId).toBe('task-worker');
+ expect(graph.goal.config?.manager).not.toHaveProperty('agentId');
expect((await service().tick(graph.goal.id)).outcome).toBe('waiting_external');
const state = (await model().findById(graph.goal.id))!.config!.managerState!;
const op = await ops().findByTopicSourceMessage(
@@ -216,7 +217,7 @@ describe('CLI main Agent planning', () => {
title: 'Selected agent',
config: { manager: {} },
});
- expect(graph.goal.config?.manager?.agentId).toBe(agentId);
+ expect(graph.goal.agentId).toBe(agentId);
expect(graph.events.every((event) => event.actorType === 'user')).toBe(true);
});
@@ -229,23 +230,26 @@ describe('CLI main Agent planning', () => {
},
);
- it('cannot select a different manager through a legacy config object', async () => {
+ it('ignores a legacy manager identity: the goal agent plans', async () => {
const config = { manager: { agentId: 'unrelated-agent', maxTurns: 5 } };
const graph = await service().create({
createdByAgentId: agentId,
config,
title: 'Bound creator',
});
- expect(graph.goal.config?.manager).toEqual({ agentId, maxTurns: 5 });
- await db.insert(agents).values({ id: 'new-task-worker', userId });
- await service().setAgent(graph.goal.id, 'new-task-worker');
- expect((await model().findById(graph.goal.id))?.config?.manager?.agentId).toBe(agentId);
+ expect(graph.goal.agentId).toBe(agentId);
+ expect(graph.goal.config?.manager).toEqual({ maxTurns: 5 });
+ await db.insert(agents).values({ id: 'next-supervisor', userId });
+ await service().setAgent(graph.goal.id, 'next-supervisor');
+ const moved = await model().findById(graph.goal.id);
+ expect(moved?.agentId).toBe('next-supervisor');
+ expect(moved?.config?.manager).toEqual({ maxTurns: 5 });
});
it('requires an accessible creator when planning options are supplied', async () => {
await expect(
service().create({ title: 'Missing creator', config: { manager: {} } }),
- ).rejects.toThrow('creating or selected Agent');
+ ).rejects.toThrow('requires the goal agent');
await expect(
service().create({ title: 'Unknown creator', createdByAgentId: 'unrelated-agent' }),
).rejects.toThrow();
@@ -272,6 +276,49 @@ describe('CLI main Agent planning', () => {
expect(vi.mocked(AiAgentService.prototype.execAgent)).toHaveBeenCalledTimes(1);
});
+ it('does not dispatch the previous supervisor when a handoff lands before the claim', async () => {
+ const { id, op } = await start();
+ await ops().recordCompletion(op.id, { status: 'done' });
+ expect((await service().tick(id)).outcome).toBe('advanced');
+ // The coordinator read the graph, then the goal was handed over before it
+ // locked the row to claim the next turn.
+ const staleGraph = await service().graph(id);
+ await db.insert(agents).values({ id: 'handoff-supervisor', userId });
+ await service().setAgent(id, 'handoff-supervisor');
+ const turnsBefore = (await model().findById(id))!.config!.managerState!.turns;
+
+ await manager().advance(staleGraph, { mayStartTurn: true });
+
+ expect(vi.mocked(AiAgentService.prototype.execAgent)).toHaveBeenCalledTimes(1);
+ expect((await model().findById(id))!.config!.managerState!.turns).toBe(turnsBefore);
+ });
+
+ it('opens the next planning turn in the new supervisor history after a handoff', async () => {
+ const { id, state, op } = await start();
+ await ops().recordCompletion(op.id, { status: 'done' });
+ expect((await service().tick(id)).outcome).toBe('advanced');
+
+ await db.insert(agents).values({ id: 'next-supervisor', userId });
+ await service().setAgent(id, 'next-supervisor');
+ expect((await service().tick(id)).outcome).toBe('waiting_external');
+
+ const next = (await model().findById(id))!.config!.managerState!;
+ expect(next.topicId).not.toBe(state.topicId);
+ const [topic] = await db.select().from(topics).where(eq(topics.id, next.topicId));
+ expect(topic?.agentId).toBe('next-supervisor');
+ // Both management topics stay out of the agent's chat sidebar.
+ const [first] = await db.select().from(topics).where(eq(topics.id, state.topicId));
+ expect(first?.trigger).toBe('goal_supervision');
+ expect(topic?.trigger).toBe('goal_supervision');
+ const nextOp = await ops().findByTopicSourceMessage(
+ next.topicId,
+ `msg_goal_manager_${next.token}`,
+ );
+ expect(nextOp?.agentId).toBe('next-supervisor');
+ // The earlier supervisor's operation no longer speaks for the goal.
+ await expect(manager().submit(id, next.token, op.id, taskPlan)).rejects.toThrow('Unrelated');
+ });
+
it('rejects wrong owner, operation, pause and changed graph without adding tasks', async () => {
const { id, state, op } = await start();
await expect(
@@ -374,7 +421,7 @@ describe('CLI main Agent planning', () => {
it('keeps server-owned manager receipts across policy updates', async () => {
const { id, state } = await start();
- await model().update(id, { config: { manager: { agentId, maxTurns: 5 } } });
+ await model().update(id, { config: { manager: { maxTurns: 5 } } });
expect((await model().findById(id))!.config!.managerState).toEqual(state);
});
@@ -566,9 +613,10 @@ describe('CLI main Agent planning', () => {
createdByAgentId: agentId,
title: 'Mixed',
});
+ expect(graph.goal.agentId).toBe(agentId);
expect(graph.goal.config).toMatchObject({
exploration: { maxExperiments: 2 },
- manager: { agentId },
+ manager: {},
});
});
});
diff --git a/apps/server/src/services/goal/manager.ts b/apps/server/src/services/goal/manager.ts
index ee801a1f2c6..16eda98fe08 100644
--- a/apps/server/src/services/goal/manager.ts
+++ b/apps/server/src/services/goal/manager.ts
@@ -12,6 +12,7 @@ import { TRPCError } from '@trpc/server';
import { eq, sql } from 'drizzle-orm';
import { z } from 'zod';
+import { TopicTrigger } from '@/const/topic';
import { AgentOperationModel } from '@/database/models/agentOperation';
import { GoalModel } from '@/database/models/goal';
import { GoalGraphModel } from '@/database/models/goalGraph';
@@ -269,10 +270,11 @@ export class GoalManagerService {
return this.startTurn(graph, problem);
};
- /** Shared entry conditions: a policy, an active Goal, and nobody waiting on a person. */
+ /** Shared entry conditions: a policy and its agent, an active Goal, and nobody waiting on a person. */
private eligible = (graph: GoalGraphSnapshot) =>
Boolean(
graph.goal.config?.manager &&
+ graph.goal.agentId &&
activeStatuses.has(graph.goal.status) &&
!graph.decisions.some((d) => d.status === 'pending'),
);
@@ -366,6 +368,8 @@ export class GoalManagerService {
): Promise<GoalTickResult | null> => {
const { goal } = graph;
const policy = goal.config!.manager!;
+ // The goal agent plans; `eligible` has already required one.
+ const agentId = goal.agentId!;
const state = goal.config?.managerState;
const nodes = graph.nodes.filter((n) => n.kind === 'task');
const unfinished = nodes.filter((n) => !terminalNodes.has(n.status));
@@ -395,8 +399,12 @@ export class GoalManagerService {
const claimed = await this.db.transaction(async (db) => {
const model = new GoalModel(db, this.userId, this.workspaceId);
const fresh = await model.lockById(goal.id);
+ // `managerSnapshot` does not cover the goal agent, so a handoff landing
+ // between the caller's graph read and this lock would otherwise dispatch
+ // the previous supervisor and spend one of the new supervisor's turns.
if (
!fresh ||
+ fresh.agentId !== agentId ||
!activeStatuses.has(fresh.status) ||
fresh.config?.managerState?.token !== state?.token ||
fresh.config?.managerState?.turns !== state?.turns ||
@@ -410,14 +418,22 @@ export class GoalManagerService {
(await this.budgetBlocked(current, db))
)
return;
+ // The management conversation lives in the goal agent's own history. After
+ // a handoff the previous agent's topic is not this agent's to continue.
+ const topicModel = new TopicModel(db, this.userId, this.workspaceId);
+ const previousTopic = state?.topicId ? await topicModel.findById(state.topicId) : undefined;
const topicId =
- state?.topicId ??
- (
- await new TopicModel(db, this.userId, this.workspaceId).create({
- agentId: policy.agentId,
- title: `Goal management: ${goal.title}`,
- })
- ).id;
+ previousTopic?.agentId === agentId
+ ? previousTopic.id
+ : (
+ await topicModel.create({
+ agentId,
+ title: `Goal management: ${goal.title}`,
+ // Read from the goal page's supervision panel; keeps the planning
+ // conversation out of the agent's chat sidebar and Recent.
+ trigger: TopicTrigger.GoalSupervision,
+ })
+ ).id;
const reviews = await this.reviews(current, db);
const next: GoalManagerState = {
...(problem
@@ -442,7 +458,7 @@ export class GoalManagerService {
const result = await new AiAgentService(this.db, this.userId, {
workspaceId: this.workspaceId,
}).execAgent({
- agentId: policy.agentId,
+ agentId,
appContext: { topicId: claimed.topicId },
clientIds: { userMessageId: `msg_goal_manager_${claimed.token}` },
autoStart: true,
@@ -481,7 +497,7 @@ export class GoalManagerService {
const model = new GoalModel(db, this.userId, this.workspaceId);
const goal = await model.lockById(goalId);
const state = goal?.config?.managerState;
- if (!goal?.config?.manager || !state || state.token !== token)
+ if (!goal?.config?.manager || !goal.agentId || !state || state.token !== token)
throw new TRPCError({
code: 'FORBIDDEN',
message: 'This planning turn does not own the Goal',
@@ -491,7 +507,10 @@ export class GoalManagerService {
this.userId,
this.workspaceId,
).findByTopicSourceMessage(state.topicId, `msg_goal_manager_${token}`);
- if (op?.id !== operationId || op.agentId !== goal.config.manager.agentId)
+ // Bound to the goal agent as it is NOW: a turn dispatched before a handoff
+ // no longer speaks for the goal.
+ const agentId = goal.agentId;
+ if (op?.id !== operationId || op.agentId !== agentId)
throw new TRPCError({ code: 'FORBIDDEN', message: 'Unrelated main Agent operation' });
const graph = await this.graph(db).getGraph(goalId);
if (
@@ -555,7 +574,7 @@ export class GoalManagerService {
message: 'Existing work must be delivered before planning or verification',
});
const authored = new GoalGraphModel(db, this.userId, this.workspaceId, {
- id: goal.config.manager.agentId,
+ id: agentId,
type: 'agent',
});
// Accepting a plan that REPLACES the inherited work has to settle it too.
@@ -592,7 +611,7 @@ export class GoalManagerService {
...task,
kind: 'task',
status: 'proposed',
- createdByAgentId: goal.config.manager.agentId,
+ createdByAgentId: agentId,
});
if (node && problem) await authored.createEdge(goalId, problem.id, node.id, 'decomposes');
}
diff --git a/apps/server/src/services/goal/supervisor/index.ts b/apps/server/src/services/goal/supervisor/index.ts
index 61a83b6964e..e4bb9524b96 100644
--- a/apps/server/src/services/goal/supervisor/index.ts
+++ b/apps/server/src/services/goal/supervisor/index.ts
@@ -9,6 +9,7 @@ import type {
} from '@lobechat/types';
import { TRPCError } from '@trpc/server';
+import { TopicTrigger } from '@/const/topic';
import { AgentModel } from '@/database/models/agent';
import { AgentOperationModel } from '@/database/models/agentOperation';
import { GoalModel } from '@/database/models/goal';
@@ -102,6 +103,7 @@ export class GoalSupervisorService {
const topic = await new TopicModel(tx, this.userId, this.workspaceId).create({
agentId: agent.id,
title: `Supervision: ${goal.title}`,
+ trigger: TopicTrigger.GoalSupervision,
});
const state = await model.updateSupervisorState(goal.id, 0, {
agentId: agent.id,
diff --git a/packages/database/src/models/goal.ts b/packages/database/src/models/goal.ts
index 8d795366dcc..f9128feea4a 100644
--- a/packages/database/src/models/goal.ts
+++ b/packages/database/src/models/goal.ts
@@ -118,6 +118,25 @@ export class GoalModel {
.where(and(eq(goals.id, id), this.ownership()));
};
+ /**
+ * Patch only `config.taskAgentId` (or drop it with `null`), for the same
+ * reason as `updatePauseReason`: a whole-config write here would race budget
+ * and acceptance edits on the same column and discard whichever landed first.
+ */
+ updateTaskAgentId = async (id: string, taskAgentId: string | null) => {
+ const [row] = await this.db
+ .update(goals)
+ .set({
+ config: taskAgentId
+ ? sql`jsonb_set(COALESCE(${goals.config}, '{}'::jsonb), '{taskAgentId}', ${JSON.stringify(taskAgentId)}::jsonb)`
+ : sql`COALESCE(${goals.config}, '{}'::jsonb) - 'taskAgentId'`,
+ updatedAt: new Date(),
+ })
+ .where(and(eq(goals.id, id), this.ownership()))
+ .returning();
+ return row as GoalItem | undefined;
+ };
+
/** Compare-and-swap only the supervisor namespace; concurrent budget edits survive. */
updateSupervisorState = async (
id: string,
diff --git a/packages/database/src/models/recent.ts b/packages/database/src/models/recent.ts
index 15b5f3b8d72..dbca9080f8c 100644
--- a/packages/database/src/models/recent.ts
+++ b/packages/database/src/models/recent.ts
@@ -42,7 +42,14 @@ export interface RecentDbItem {
// Mirrors `MAIN_SIDEBAR_EXCLUDE_TRIGGERS` in `src/const/topic.ts` plus the
// legacy `task_manager` trigger from the previous Task Manager panel.
// System-trigger topics live in their own surfaces and would clutter Recent.
-const SYSTEM_TOPIC_TRIGGERS = ['cron', 'eval', 'task_manager', 'task', 'document'];
+const SYSTEM_TOPIC_TRIGGERS = [
+ 'cron',
+ 'eval',
+ 'task_manager',
+ 'task',
+ 'document',
+ 'goal_supervision',
+];
// Excluded so tool-owned document rows don't surface as generic recent docs;
// only user-authored pages ('api') and legacy 'topic' rows remain.
diff --git a/packages/types/src/goal.ts b/packages/types/src/goal.ts
index 0830ed00a0e..3fc98b088e6 100644
--- a/packages/types/src/goal.ts
+++ b/packages/types/src/goal.ts
@@ -210,10 +210,11 @@ export const summarizeGoalSupervision = (state?: GoalSupervisionState): GoalSupe
};
};
-/** A CLI-capable agent owns planning; the coordinator owns execution and acceptance. */
+/**
+ * A CLI-capable agent owns planning; the coordinator owns execution and acceptance.
+ * The planning agent is the goal's own `agentId` β€” the policy carries no identity.
+ */
export interface GoalManagerPolicy {
- /** Server-resolved creator identity; not a separately selectable manager. */
- agentId: string;
instruction?: string;
maxTurns?: number;
}
@@ -271,12 +272,16 @@ export interface GoalConfig {
supervision?: GoalSupervisionPolicy;
/** Durable supervisor topic and bounded incident ledger. */
supervisorState?: GoalSupervisionState;
+ /**
+ * Who executes the Tasks the coordinator creates, when that is not the goal's
+ * own agent. The goal's `agentId` supervises and plans; this only routes work.
+ * Unset means the goal's agent does its own Tasks.
+ */
+ taskAgentId?: string;
}
-/** Creation accepts planning options, never a separate manager identity or runtime receipt. */
-export type GoalCreateConfig = Omit<GoalConfig, 'manager' | 'managerState' | 'supervisorState'> & {
- manager?: Omit<GoalManagerPolicy, 'agentId'>;
-};
+/** Creation accepts planning options, never a runtime receipt. */
+export type GoalCreateConfig = Omit<GoalConfig, 'managerState' | 'supervisorState'>;
/**
* The goal entity as exposed to clients β€” a mirror of the `goals` table row.
diff --git a/src/const/topic.ts b/src/const/topic.ts
index ca0d0381334..3b6299395f0 100644
--- a/src/const/topic.ts
+++ b/src/const/topic.ts
@@ -6,22 +6,27 @@
* `Document` marks topics auto-provisioned for an agent ↔ document chat panel
* (see `agentDocument.getOrCreateChatTopic`); these are surfaced through the
* document UI and should stay out of the main agent chat history.
+ * `GoalSupervision` marks the conversation a goal's supervising agent plans in
+ * (and the recovery supervisor's); it is read from the goal page's supervision
+ * panel, not from the agent's chat history.
*/
export const TopicTrigger = {
Cron: 'cron',
Document: 'document',
Eval: 'eval',
+ GoalSupervision: 'goal_supervision',
RunTask: 'task',
} as const;
/**
* Triggers to exclude from the main chat sidebar so system-owned topics
- * (cron jobs, evals, task runs, doc-anchored chat) don't pollute the user's
- * main history.
+ * (cron jobs, evals, task runs, doc-anchored chat, goal supervision) don't
+ * pollute the user's main history.
*/
export const MAIN_SIDEBAR_EXCLUDE_TRIGGERS: string[] = [
TopicTrigger.Cron,
TopicTrigger.Document,
TopicTrigger.Eval,
+ TopicTrigger.GoalSupervision,
TopicTrigger.RunTask,
];
diff --git a/src/features/AgentGoals/GoalDetailPage.tsx b/src/features/AgentGoals/GoalDetailPage.tsx
index 84e6ccc703e..9573e378516 100644
--- a/src/features/AgentGoals/GoalDetailPage.tsx
+++ b/src/features/AgentGoals/GoalDetailPage.tsx
@@ -207,7 +207,7 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {
);
const { goal, nodes } = snapshot;
- const managerConversation = goalManagerConversation(goal.config);
+ const managerConversation = goalManagerConversation(goal);
const tasks = nodes.filter((node) => node.kind === 'task').length;
const findings = nodes.filter((node) => node.kind === 'finding').length;
const open = (metric: GoalMetricKind) => () => openGoalMetric(goalId, metric);
diff --git a/src/features/AgentGoals/GoalSupervision.tsx b/src/features/AgentGoals/GoalSupervision.tsx
index e6c4b2ac71b..876626f318f 100644
--- a/src/features/AgentGoals/GoalSupervision.tsx
+++ b/src/features/AgentGoals/GoalSupervision.tsx
@@ -1,14 +1,16 @@
+import { AGENT_CHAT_TOPIC_URL } from '@lobechat/const';
import { agentDisplayName } from '@lobechat/types';
-import { Flexbox } from '@lobehub/ui';
-import { ActionIcon, Text } from '@lobehub/ui/base-ui';
-import { PanelRightCloseIcon } from 'lucide-react';
-import { useCallback } from 'react';
+import { copyToClipboard, type DropdownItem, DropdownMenu, Flexbox } from '@lobehub/ui';
+import { ActionIcon, Text, toast } from '@lobehub/ui/base-ui';
+import { CopyIcon, ExternalLink, MoreHorizontal, PanelRightCloseIcon } from 'lucide-react';
+import { useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';
import { ChatList } from '@/features/Conversation';
import MessageItem from '@/features/Conversation/Messages';
import NavHeader from '@/features/NavHeader';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
@@ -35,13 +37,44 @@ export const GoalSupervision = ({ agentId, goalId, onCollapse, topicId }: GoalSu
(index: number, id: string) => <MessageItem disableEditing id={id} index={index} />,
[],
);
+ const navigate = useWorkspaceAwareNavigate();
+ // This panel is a read-only view of the manager's conversation. Opening it in
+ // the agent's own chat is how you continue it; the id is one click away for
+ // referencing it elsewhere (`lh topic view`, a bug report), like a task run's.
+ const menuItems = useMemo<DropdownItem[]>(
+ () => [
+ {
+ icon: ExternalLink,
+ key: 'openAgentTopic',
+ label: t('taskDetail.topicMenu.openAgentTopic'),
+ onClick: () => navigate(AGENT_CHAT_TOPIC_URL(agentId, topicId)),
+ },
+ {
+ icon: CopyIcon,
+ key: 'copyTopicId',
+ label: t('taskDetail.topicMenu.copyId'),
+ onClick: async () => {
+ await copyToClipboard(topicId);
+ toast.success(t('copySuccess', { ns: 'common' }));
+ },
+ },
+ ],
+ [agentId, navigate, t, topicId],
+ );
return (
<GoalChatProvider agentId={agentId} goalId={goalId} initialTopicId={topicId}>
<Flexbox height={'100%'} style={{ overflow: 'hidden' }}>
<NavHeader
- left={<Text ellipsis>{agentTitle || t('goalProcess.manager.title')}</Text>}
showTogglePanelButton={false}
+ left={
+ <Flexbox horizontal align={'center'} gap={4} style={{ minWidth: 0 }}>
+ <Text ellipsis>{agentTitle || t('goalProcess.manager.title')}</Text>
+ <DropdownMenu items={menuItems}>
+ <ActionIcon icon={MoreHorizontal} size={'small'} />
+ </DropdownMenu>
+ </Flexbox>
+ }
right={
<ActionIcon
icon={PanelRightCloseIcon}
diff --git a/src/features/AgentGoals/ProcessControl/Graph/index.tsx b/src/features/AgentGoals/ProcessControl/Graph/index.tsx
index 457aef6997e..f9a3ee46384 100644
--- a/src/features/AgentGoals/ProcessControl/Graph/index.tsx
+++ b/src/features/AgentGoals/ProcessControl/Graph/index.tsx
@@ -14,6 +14,7 @@ import {
MarkerType,
MiniMap,
type Node as FlowNode,
+ type NodeChange,
Panel,
ReactFlow,
ReactFlowProvider,
@@ -39,6 +40,7 @@ import ExplorationEdge from './ExplorationEdge';
import { explorationMap } from './explorationMap';
import GraphNodeView, { GhostNodeView, type GraphNodeData } from './GraphNode';
import { hideKinds, layoutGraph, NODE_WIDTH } from './layout';
+import { type MeasuredSizes, mergeMeasuredSizes } from './measuredSizes';
import { revealCenter } from './revealNode';
import { useExplorationNavigation } from './useExplorationNavigation';
import { useFitViewOnResize } from './useFitViewOnResize';
@@ -366,11 +368,20 @@ const Canvas = memo<
() => hideKinds(baseNodes, graph.edges, hiddenKinds),
[baseNodes, graph.edges, hiddenKinds],
);
+ // A card's height follows its content β€” a long title wraps to four lines β€”
+ // so the per-kind estimate stacked the next rank into the cards above it.
+ // The first pass lays out on the estimate; once React Flow has measured the
+ // cards, the map lays out again on what is actually on screen.
+ const [measuredSizes, setMeasuredSizes] = useState<MeasuredSizes>({});
+ const handleNodesChange = useCallback((changes: NodeChange[]) => {
+ setMeasuredSizes((previous) => mergeMeasuredSizes(previous, changes));
+ }, []);
const positions = hasExperiments
? map.boxes
: layoutGraph(
baseNodes.filter((node) => visibleIds.has(node.id)),
[...graph.edges, ...bridges.map((bridge) => ({ ...bridge, kind: 'leads_to' as const }))],
+ measuredSizes,
);
const ghosts = useMemo(() => {
@@ -443,6 +454,12 @@ const Canvas = memo<
view: item,
};
const expanded = item.node.kind === 'experiment' && !collapsed.has(item.node.id);
+ const type = expanded
+ ? 'goalExperimentGroup'
+ : graphNodeKind(graph, item) === 'experiment'
+ ? 'goalExperiment'
+ : 'goalNode';
+ const measured = measuredSizes[item.node.id];
return {
data: expanded
? ({
@@ -455,11 +472,7 @@ const Canvas = memo<
draggable: false,
id: item.node.id,
position: { x: box?.x ?? 0, y: box?.y ?? 0 },
- type: expanded
- ? 'goalExperimentGroup'
- : graphNodeKind(graph, item) === 'experiment'
- ? 'goalExperiment'
- : 'goalNode',
+ type,
parentId: hasExperiments ? map.parents.get(item.node.id) : undefined,
...(expanded ? { style: { width: box.width, height: box.height } } : {}),
ariaLabel: graphNodeLabel(
@@ -468,7 +481,12 @@ const Canvas = memo<
item.seq,
),
width: box?.width ?? NODE_WIDTH[item.node.kind],
- initialHeight: box?.height,
+ // A relayout hands React Flow a new node object, which it treats as
+ // unmeasured: it pins the card to `initialHeight` (clipping a tall
+ // title back to the estimate) and drops the handle positions edges
+ // are drawn from. Handing the last measurement back keeps both, so
+ // only a card that has never rendered gets the estimate.
+ ...(type === 'goalNode' && measured ? { measured } : { initialHeight: box?.height }),
} satisfies FlowNode;
}),
[
@@ -485,6 +503,7 @@ const Canvas = memo<
onSelect,
hasExperiments,
map.parents,
+ measuredSizes,
],
);
@@ -632,6 +651,7 @@ const Canvas = memo<
preventScrolling={fullscreen}
proOptions={{ hideAttribution: true }}
zoomOnScroll={false}
+ onNodesChange={handleNodesChange}
onNodeClick={(_, node) => {
if (node.type !== 'goalGhost' && node.type !== 'goalExperimentGroup') onSelect(node.id);
}}
diff --git a/src/features/AgentGoals/ProcessControl/Graph/layout.test.ts b/src/features/AgentGoals/ProcessControl/Graph/layout.test.ts
index 7ccaa9db4c0..898bc2cc4d5 100644
--- a/src/features/AgentGoals/ProcessControl/Graph/layout.test.ts
+++ b/src/features/AgentGoals/ProcessControl/Graph/layout.test.ts
@@ -79,6 +79,50 @@ describe('layoutGraph', () => {
expect(boxes.w1.x).not.toBe(boxes.w2.x);
});
+ it('puts each finding under the task that produced it, not in the middle of the row', () => {
+ const boxes = layoutGraph(
+ [
+ node('p1', 'problem'),
+ node('w1'),
+ node('w2'),
+ node('w3'),
+ node('w4'),
+ node('f1', 'finding'),
+ ],
+ [
+ edge('p1', 'w1', 'decomposes'),
+ edge('p1', 'w2', 'decomposes'),
+ edge('p1', 'w3', 'decomposes'),
+ edge('p1', 'w4', 'decomposes'),
+ edge('w1', 'f1', 'produces'),
+ ],
+ );
+ const center = (id: string) => boxes[id].x + boxes[id].width / 2;
+
+ expect(center('f1')).toBe(center('w1'));
+ // Siblings under one parent still centre on it.
+ expect((center('w1') + center('w4')) / 2).toBe(center('p1'));
+ });
+
+ it('keeps neighbours in a row apart when their parents are close together', () => {
+ const boxes = layoutGraph(
+ [node('w1'), node('w2'), node('f1', 'finding'), node('f2', 'finding'), node('f3', 'finding')],
+ [edge('w1', 'f1', 'produces'), edge('w1', 'f2', 'produces'), edge('w2', 'f3', 'produces')],
+ );
+ const ordered = ['f1', 'f2', 'f3'].map((id) => boxes[id]).sort((a, b) => a.x - b.x);
+
+ for (let i = 1; i < ordered.length; i++)
+ expect(ordered[i].x).toBeGreaterThanOrEqual(ordered[i - 1].x + ordered[i - 1].width);
+ });
+
+ it('stacks the next rank below the tallest measured card, not the per-kind estimate', () => {
+ const boxes = layoutGraph([node('w1'), node('f1', 'finding')], [edge('w1', 'f1', 'produces')], {
+ w1: { height: 190 },
+ });
+
+ expect(boxes.f1.y).toBeGreaterThanOrEqual(boxes.w1.y + 190);
+ });
+
it('terminates on a cycle instead of relaxing forever', () => {
const boxes = layoutGraph(
[node('w1'), node('w2')],
diff --git a/src/features/AgentGoals/ProcessControl/Graph/layout.ts b/src/features/AgentGoals/ProcessControl/Graph/layout.ts
index 4f20ba24d16..185d7a4d485 100644
--- a/src/features/AgentGoals/ProcessControl/Graph/layout.ts
+++ b/src/features/AgentGoals/ProcessControl/Graph/layout.ts
@@ -128,7 +128,7 @@ export const hideKinds = (
export const layoutGraph = (
nodes: LayoutNode[],
edges: LayoutEdge[],
- sizes: Readonly<Record<string, Pick<LayoutBox, 'width' | 'height'>>> = {},
+ sizes: Readonly<Record<string, Partial<Pick<LayoutBox, 'width' | 'height'>>>> = {},
gaps = { column: COLUMN_GAP, rank: RANK_GAP },
): Record<string, LayoutBox> => {
const index = new Map(nodes.map((node, i) => [node.id, i]));
@@ -172,14 +172,16 @@ export const layoutGraph = (
index.get(a.id)! - index.get(b.id)!,
);
const widths = row.map((node) => sizes[node.id]?.width ?? NODE_WIDTH[node.kind]);
- const total = widths.reduce((sum, w) => sum + w, 0) + gaps.column * (row.length - 1);
- let x = -total / 2;
+ const xs = placeRow(
+ row.map((node, i) => barycenter(node, parents, order) - widths[i] / 2),
+ widths,
+ gaps.column,
+ );
let height = 0;
row.forEach((node, i) => {
const nodeHeight = sizes[node.id]?.height ?? NODE_HEIGHT[node.kind];
- boxes[node.id] = { height: nodeHeight, width: widths[i], x, y };
- order.set(node.id, x + widths[i] / 2);
- x += widths[i] + gaps.column;
+ boxes[node.id] = { height: nodeHeight, width: widths[i], x: xs[i], y };
+ order.set(node.id, xs[i] + widths[i] / 2);
height = Math.max(height, nodeHeight);
});
y += height + gaps.rank;
@@ -187,6 +189,27 @@ export const layoutGraph = (
return boxes;
};
+/**
+ * Settle one ordered row: every node wants its `desired` left edge (centred
+ * under its parents), and none may overlap its neighbour.
+ *
+ * Centring the whole row on the canvas instead put a finding between two tasks
+ * rather than under the one that produced it. A left-to-right sweep pushes each
+ * node clear of the one before it; a right-to-left sweep pulls each clear of
+ * the one after. Each sweep alone drifts the row to one side. Both keep order
+ * with at least `gap` between neighbours, so their mean does too, and a crowd
+ * that all wants the same spot ends up centred on it.
+ */
+const placeRow = (desired: number[], widths: number[], gap: number): number[] => {
+ const forward = [...desired];
+ for (let i = 1; i < forward.length; i++)
+ forward[i] = Math.max(forward[i], forward[i - 1] + widths[i - 1] + gap);
+ const backward = [...desired];
+ for (let i = backward.length - 2; i >= 0; i--)
+ backward[i] = Math.min(backward[i], backward[i + 1] - widths[i] - gap);
+ return forward.map((x, i) => (x + backward[i]) / 2);
+};
+
const barycenter = (
node: LayoutNode,
parents: Map<string, string[]>,
diff --git a/src/features/AgentGoals/ProcessControl/Graph/measuredSizes.test.ts b/src/features/AgentGoals/ProcessControl/Graph/measuredSizes.test.ts
new file mode 100644
index 00000000000..152767a5eeb
--- /dev/null
+++ b/src/features/AgentGoals/ProcessControl/Graph/measuredSizes.test.ts
@@ -0,0 +1,46 @@
+import type { NodeChange } from '@xyflow/react';
+import { describe, expect, it } from 'vitest';
+
+import { mergeMeasuredSizes } from './measuredSizes';
+
+const resize = (id: string, width: number, height: number): NodeChange => ({
+ dimensions: { height, width },
+ id,
+ type: 'dimensions',
+});
+
+describe('mergeMeasuredSizes', () => {
+ it('records the height a card actually rendered at', () => {
+ expect(mergeMeasuredSizes({}, [resize('task', 260, 146.4)])).toEqual({
+ task: { height: 147, width: 260 },
+ });
+ });
+
+ it('returns the same object when a measurement repeats, so no relayout follows', () => {
+ const previous = { task: { height: 147, width: 260 } };
+
+ expect(mergeMeasuredSizes(previous, [resize('task', 260, 147)])).toBe(previous);
+ });
+
+ it('keeps earlier cards when another one is measured', () => {
+ const next = mergeMeasuredSizes({ task: { height: 147, width: 260 } }, [
+ resize('finding', 240, 76),
+ ]);
+
+ expect(next).toEqual({
+ finding: { height: 76, width: 240 },
+ task: { height: 147, width: 260 },
+ });
+ });
+
+ it('ignores changes that are not measurements and zero-sized hidden cards', () => {
+ const previous = {};
+
+ expect(
+ mergeMeasuredSizes(previous, [
+ { id: 'task', selected: true, type: 'select' },
+ resize('hidden', 0, 0),
+ ]),
+ ).toBe(previous);
+ });
+});
diff --git a/src/features/AgentGoals/ProcessControl/Graph/measuredSizes.ts b/src/features/AgentGoals/ProcessControl/Graph/measuredSizes.ts
new file mode 100644
index 00000000000..28b2f2f5214
--- /dev/null
+++ b/src/features/AgentGoals/ProcessControl/Graph/measuredSizes.ts
@@ -0,0 +1,37 @@
+import type { NodeChange } from '@xyflow/react';
+
+export interface MeasuredSize {
+ height: number;
+ width: number;
+}
+
+export type MeasuredSizes = Readonly<Record<string, MeasuredSize>>;
+
+/**
+ * Fold React Flow's `dimensions` changes into the sizes the map lays out on.
+ *
+ * The sizes live in component state rather than being read back from React
+ * Flow's node lookup: every relayout hands React Flow new node objects, which
+ * it treats as unmeasured and clears. A layout driven by that lookup kept
+ * losing the heights it had just laid out on and fell back to the estimate.
+ *
+ * Returns `previous` itself when nothing changed, so an unchanged measurement
+ * does not trigger another layout pass.
+ */
+export const mergeMeasuredSizes = (
+ previous: MeasuredSizes,
+ changes: readonly NodeChange[],
+): MeasuredSizes => {
+ let next: Record<string, MeasuredSize> | undefined;
+ for (const change of changes) {
+ if (change.type !== 'dimensions' || !change.dimensions) continue;
+ const width = Math.ceil(change.dimensions.width);
+ const height = Math.ceil(change.dimensions.height);
+ if (!width || !height) continue;
+ const current = (next ?? previous)[change.id];
+ if (current?.width === width && current.height === height) continue;
+ next ??= { ...previous };
+ next[change.id] = { height, width };
+ }
+ return next ?? previous;
+};
diff --git a/src/features/AgentGoals/goalPresentation.test.ts b/src/features/AgentGoals/goalPresentation.test.ts
index b0be0398fb9..f63db4cca86 100644
--- a/src/features/AgentGoals/goalPresentation.test.ts
+++ b/src/features/AgentGoals/goalPresentation.test.ts
@@ -74,24 +74,37 @@ describe('summarizeGoalBudget', () => {
});
describe('goalManagerConversation', () => {
+ const consumedTurn = {
+ consumed: true,
+ snapshot: 'snapshot',
+ startedAt: '2026-09-09T00:00:00Z',
+ token: 'token',
+ topicId: 'persistent-topic',
+ turns: 6,
+ };
+
it('does not offer a empty conversation before the first planning run', () => {
- expect(goalManagerConversation(undefined)).toBeUndefined();
- expect(goalManagerConversation({ manager: { agentId: 'creator' } })).toBeUndefined();
+ expect(goalManagerConversation({ agentId: 'supervisor', config: null })).toBeUndefined();
+ expect(
+ goalManagerConversation({ agentId: 'supervisor', config: { manager: {} } }),
+ ).toBeUndefined();
+ });
+
+ it('keeps the goal agent conversation available after a planning turn is consumed', () => {
+ expect(
+ goalManagerConversation({
+ agentId: 'supervisor',
+ config: { manager: {}, managerState: consumedTurn, taskAgentId: 'executor' },
+ }),
+ ).toEqual({ agentId: 'supervisor', topicId: 'persistent-topic' });
});
- it('keeps the creator conversation available after a planning turn is consumed', () => {
+ it('offers nothing for a goal without an agent to own the conversation', () => {
expect(
goalManagerConversation({
- manager: { agentId: 'creator' },
- managerState: {
- consumed: true,
- snapshot: 'snapshot',
- startedAt: '2026-09-09T00:00:00Z',
- token: 'token',
- topicId: 'persistent-topic',
- turns: 6,
- },
+ agentId: null,
+ config: { manager: {}, managerState: consumedTurn },
}),
- ).toEqual({ agentId: 'creator', topicId: 'persistent-topic' });
+ ).toBeUndefined();
});
});
diff --git a/src/features/AgentGoals/goalPresentation.ts b/src/features/AgentGoals/goalPresentation.ts
index bb5e977ee8d..b1445a6436c 100644
--- a/src/features/AgentGoals/goalPresentation.ts
+++ b/src/features/AgentGoals/goalPresentation.ts
@@ -80,11 +80,11 @@ export const summarizeGoalBudget = (
return { kind: 'uncapped', spent: totalCost };
};
-/** The planner's persistent conversation belongs to the creator, not the task assignee. */
-export const goalManagerConversation = (
- config: GoalConfig | null | undefined,
-): { agentId: string; topicId: string } | undefined => {
- const agentId = config?.manager?.agentId;
- const topicId = config?.managerState?.topicId;
- return agentId && topicId ? { agentId, topicId } : undefined;
+/** The planner's persistent conversation belongs to the goal agent, not the task executor. */
+export const goalManagerConversation = (goal: {
+ agentId: string | null;
+ config?: GoalConfig | null;
+}): { agentId: string; topicId: string } | undefined => {
+ const topicId = goal.config?.manager ? goal.config.managerState?.topicId : undefined;
+ return goal.agentId && topicId ? { agentId: goal.agentId, topicId } : undefined;
};
diff --git a/src/features/Portal/TaskResult/Actions.tsx b/src/features/Portal/TaskResult/Actions.tsx
new file mode 100644
index 00000000000..efb4aa92c36
--- /dev/null
+++ b/src/features/Portal/TaskResult/Actions.tsx
@@ -0,0 +1,48 @@
+import { type DropdownItem, DropdownMenu } from '@lobehub/ui';
+import { ActionIcon } from '@lobehub/ui/base-ui';
+import { CopyIcon, LinkIcon, MoreHorizontal } from 'lucide-react';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useTaskCopyActions } from '@/features/AgentTasks/AgentTaskDetail/useTaskCopyActions';
+
+/**
+ * The "β‹―" that rides right behind the task name, the way the goal and
+ * supervision headers place theirs β€” the menu belongs to the thing it names,
+ * not to the panel chrome on the far edge.
+ */
+const Actions = memo(() => {
+ const { t } = useTranslation('chat');
+ // The body marks this task active while the panel is open, so the copied
+ // link is byte-for-byte the one the task page's own header copies.
+ const { copyId, copyLink, taskId } = useTaskCopyActions();
+
+ const menuItems = useMemo<DropdownItem[]>(
+ () => [
+ {
+ icon: LinkIcon,
+ key: 'copyLink',
+ label: t('taskList.contextMenu.copyLink'),
+ onClick: copyLink,
+ },
+ {
+ icon: CopyIcon,
+ key: 'copyId',
+ label: t('taskList.contextMenu.copyId'),
+ onClick: copyId,
+ },
+ ],
+ [copyId, copyLink, t],
+ );
+
+ if (!taskId) return null;
+
+ return (
+ <DropdownMenu items={menuItems}>
+ <ActionIcon icon={MoreHorizontal} size={'small'} style={{ flexShrink: 0 }} />
+ </DropdownMenu>
+ );
+});
+
+Actions.displayName = 'TaskResultPortalActions';
+export default Actions;
diff --git a/src/features/Portal/TaskResult/Title.tsx b/src/features/Portal/TaskResult/Title.tsx
index 285320c9a7d..e661d7bdf69 100644
--- a/src/features/Portal/TaskResult/Title.tsx
+++ b/src/features/Portal/TaskResult/Title.tsx
@@ -11,6 +11,7 @@ import { chatPortalSelectors } from '@/store/chat/selectors';
import { useTaskStore } from '@/store/task';
import { oneLineEllipsis } from '@/styles';
+import Actions from './Actions';
import { useLiveRun } from './useLiveRun';
const Title = memo(() => {
@@ -32,27 +33,29 @@ const Title = memo(() => {
<Text
className={oneLineEllipsis}
fontSize={13}
- style={{ color: cssVar.colorTextSecondary, flex: 1, minWidth: 0 }}
+ style={{ color: cssVar.colorTextSecondary, flex: '0 1 auto', minWidth: 0 }}
>
{liveRun.activity.title}
</Text>
+ <Actions />
</Flexbox>
);
return (
<Flexbox horizontal align={'center'} flex={1} gap={8} style={{ minWidth: 0 }}>
- <Text fontSize={14} weight={500}>
+ <Text fontSize={14} style={{ flexShrink: 0 }} weight={500}>
{t('goalDetail.taskResult')}
</Text>
{(detail?.identifier || detail?.name) && (
<Text
className={oneLineEllipsis}
fontSize={13}
- style={{ color: cssVar.colorTextSecondary, flex: 1, minWidth: 0 }}
+ style={{ color: cssVar.colorTextSecondary, flex: '0 1 auto', minWidth: 0 }}
>
{[detail.identifier, detail.name].filter(Boolean).join(' Β· ')}
</Text>
)}
+ <Actions />
</Flexbox>
);
});