π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(goal): move the supervision conversation when the Goal changes agent (#20250)
Arvin Xu26c3c7dd2123
diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.tsindex f40091b2244..ae4f55145d9 100644--- a/apps/server/src/services/goal/index.ts+++ b/apps/server/src/services/goal/index.ts@@ -1104,6 +1104,7 @@ export class GoalService {graph.goal.config?.supervisorState,),new GoalManagerService(this.db, this.userId, this.workspaceId).usage(+ graph.goal.id,graph.goal.config?.managerState,),]);@@ -1132,6 +1133,10 @@ export class GoalService {* 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`.+ *+ * The management conversation moves with supervision: it lives in the goal+ * agent's own history, so it is re-created for the new agent here instead of+ * being left pointing at the previous agent's topic until the next claim.*/setAgent = async (goalId: string,@@ -1145,11 +1150,22 @@ export class GoalService {const goal = await this.goalModel.update(goalId, { agentId });if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });+ // The receipt carries the management topic, so the caller must get the row+ // with the migrated one β not the copy read before the handoff.+ const migrated = await new GoalManagerService(+ this.db,+ this.userId,+ this.workspaceId,+ ).moveConversationTo(goalId, agentId);+const reassignedTaskIds =options?.goalOnly || goal.config?.taskAgentId? []: await this.reassignUnfinishedTasks(goalId, agentId);- return { goal, reassignedTaskIds };+ return {+ goal: migrated ? ((await this.goalModel.findById(goalId)) ?? goal) : goal,+ reassignedTaskIds,+ };};/**diff --git a/apps/server/src/services/goal/manager.README.md b/apps/server/src/services/goal/manager.README.mdindex c88b700964c..2e67f246468 100644--- a/apps/server/src/services/goal/manager.README.md+++ b/apps/server/src/services/goal/manager.README.md@@ -19,8 +19,14 @@ 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.Without explicit planning options, ordinary unseeded goals keep the coordinatorplanner. 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.+behavior. A supervision handoff moves the management conversation into the new+agent's history at once β the Goal's `managerState.topicId` is re-pointed to a+Topic created for the new agent, so the supervision panel and its "open+conversation" link follow the handoff immediately. A handoff that lands while a+turn is unsettled is migrated by the next claim instead, because `settleInFlight`+finds that turn's run through the old `topicId`. The conversations the Goal plans+in before each move are kept in `managerState.previousTopicIds` and still count+toward its management spend.The main Agent reads `lh goal show`, `lh task view`, `lh topic view`, and documentcommands. It submits a JSON file through `lh goal plan <goal-id> --token <turn> --file plan.json`. The runtime supplies `LOBEHUB_OPERATION_ID`. Plan actions:@@ -125,7 +131,9 @@ persistent device process journal. A committed plan survives an errored ending,but coordinator dispatch still waits for that terminal operation.Manager turns are capped separately (default 50, maximum 100); recorded manager-cost/tokens are included in detailed Goal spend. External subscription execution+cost/tokens are included in detailed Goal spend. A turn's source message carries+the Goal it was dispatched for, so its cost stays with that Goal after a handoff+and a conversation shared with another Goal cannot charge its turns here. External subscription executioncan be unmetered, so a zero recorded cost is not proof of zero spend. The CLI sends operation-token plan submissions to a dedicated ingestion endpoint,which checks the live operation principal and then the Goal turn binding. Normaluser credentials retain the existing scoped endpoint. Prompt instructions are not adiff --git a/apps/server/src/services/goal/manager.test.ts b/apps/server/src/services/goal/manager.test.tsindex a488f158c59..331caea09b6 100644--- a/apps/server/src/services/goal/manager.test.ts+++ b/apps/server/src/services/goal/manager.test.ts@@ -353,7 +353,7 @@ describe('CLI main Agent planning', () => {});const state = (await model().findById(graph.goal.id))!.config!.managerState!;- expect((await manager().usage(state)).totalCost).toBe(2);+ expect((await manager().usage(graph.goal.id, state)).totalCost).toBe(2);});it('keeps the adopted run in management spend after a later turn replaces the receipt', async () => {@@ -380,10 +380,11 @@ describe('CLI main Agent planning', () => {turns: 2,};- expect((await manager().usage(laterTurn)).totalCost).toBe(2);+ expect((await manager().usage(graph.goal.id, laterTurn)).totalCost).toBe(2);// After a handoff the later turn lives on another topic; the run still counts.expect(- (await manager().usage({ ...laterTurn, topicId: 'tpc_other_supervisor' })).totalCost,+ (await manager().usage(graph.goal.id, { ...laterTurn, topicId: 'tpc_other_supervisor' }))+ .totalCost,).toBe(2);});@@ -566,6 +567,131 @@ describe('CLI main Agent planning', () => {await expect(manager().submit(id, next.token, op.id, taskPlan)).rejects.toThrow('Unrelated');});+ it('moves the management conversation to the new agent at the 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: 'handoff-target', userId });+ const { goal } = await service().setAgent(id, 'handoff-target');++ // The row handed back to the caller already points at the new agent's topic,+ // so the supervision panel and its "open conversation" link follow the+ // handoff instead of staying on the previous agent until the next claim.+ const moved = (await model().findById(id))!.config!.managerState!;+ expect(moved.topicId).not.toBe(state.topicId);+ expect(goal.config?.managerState?.topicId).toBe(moved.topicId);+ const [topic] = await db.select().from(topics).where(eq(topics.id, moved.topicId));+ expect(topic?.agentId).toBe('handoff-target');+ expect(topic?.trigger).toBe('goal_supervision');+ // The conversation it left behind is retained rather than orphaned.+ expect(moved.previousTopicIds).toEqual([state.topicId]);+ });++ it('keeps counting the previous conversations in management spend', async () => {+ const { id, state, op } = await start();+ await db.update(agentOperations).set({ totalCost: 3 }).where(eq(agentOperations.id, op.id));+ await ops().recordCompletion(op.id, { status: 'done' });+ expect((await service().tick(id)).outcome).toBe('advanced');++ await db.insert(agents).values({ id: 'spend-target', userId });+ await service().setAgent(id, 'spend-target');+ expect((await service().tick(id)).outcome).toBe('waiting_external');++ const next = (await model().findById(id))!.config!.managerState!;+ // The turn now runs in the new agent's topic; the spend already booked in+ // the conversation it left still belongs to the goal's management budget.+ expect(next.topicId).not.toBe(state.topicId);+ expect((await manager().usage(id, next)).totalCost).toBe(3);+ });++ it('leaves a live turn on the previous agent topic instead of migrating mid-turn', async () => {+ const { id, state } = await start();+ await db.insert(agents).values({ id: 'mid-turn-target', userId });++ // The first turn is dispatched but not settled: `settleInFlight` finds its+ // run through `state.topicId`, so re-pointing now would strand it.+ await service().setAgent(id, 'mid-turn-target');++ const untouched = (await model().findById(id))!.config!.managerState!;+ expect(untouched.topicId).toBe(state.topicId);+ expect(untouched.previousTopicIds).toBeUndefined();+ expect(+ await db.select().from(topics).where(eq(topics.agentId, 'mid-turn-target')),+ ).toHaveLength(0);+ });++ it('migrates on the next claim after a mid-turn handoff and retains the old conversation', async () => {+ const { id, state, op } = await start();+ await db.insert(agents).values({ id: 'late-target', userId });+ await service().setAgent(id, 'late-target');++ await ops().recordCompletion(op.id, { status: 'done' });+ expect((await service().tick(id)).outcome).toBe('advanced');+ expect((await service().tick(id)).outcome).toBe('waiting_external');++ const next = (await model().findById(id))!.config!.managerState!;+ const [topic] = await db.select().from(topics).where(eq(topics.id, next.topicId));+ expect(topic?.agentId).toBe('late-target');+ // The conversation the handoff moved out of keeps counting.+ expect(next.previousTopicIds).toEqual([state.topicId]);+ });++ it('does not charge another Goalβs turns in a shared conversation to this one', async () => {+ const a = await start();+ const shared = a.state.topicId;+ // A second Goal is created from the same conversation and plans there too β+ // the shared conversation a retained topic can turn out to be.+ const sharedRunId = 'op-shared-conversation-run';+ await ops().recordStart({+ agentId,+ appContext: { sourceMessageId: 'msg_user_second_goal' },+ operationId: sharedRunId,+ topicId: shared,+ });+ const { graph: b } = await service().createFromConversation(sharedRunId, {+ title: 'Second goal',+ });+ await ops().recordCompletion(sharedRunId, { status: 'done' });+ expect((await service().tick(b.goal.id)).outcome).toBe('advanced');+ expect((await service().tick(b.goal.id)).outcome).toBe('waiting_external');+ const bState = (await model().findById(b.goal.id))!.config!.managerState!;+ const bTurn = await ops().findByTopicSourceMessage(shared, `msg_goal_manager_${bState.token}`);+ expect(bTurn).toBeTruthy();+ await db.update(agentOperations).set({ totalCost: 9 }).where(eq(agentOperations.id, bTurn!.id));++ // A hands over, retaining the shared conversation as one it moved out of.+ await ops().recordCompletion(a.op.id, { status: 'done' });+ expect((await service().tick(a.id)).outcome).toBe('advanced');+ await db.insert(agents).values({ id: 'shared-target', userId });+ await service().setAgent(a.id, 'shared-target');+ const retained = (await model().findById(a.id))!.config!.managerState!;+ expect(retained.previousTopicIds).toEqual([shared]);++ await db.update(agentOperations).set({ totalCost: 1 }).where(eq(agentOperations.id, a.op.id));+ // Only A's own turn counts; the other Goal's run in the same conversation does not.+ expect((await manager().usage(a.id, retained)).totalCost).toBe(1);+ });++ it('declines a handoff migration whose target is no longer the goal agent', async () => {+ const { id, op } = await start();+ await ops().recordCompletion(op.id, { status: 'done' });+ expect((await service().tick(id)).outcome).toBe('advanced');+ await db.insert(agents).values([+ { id: 'first-target', userId },+ { id: 'second-target', userId },+ ]);++ // Two overlapping handoffs: this call's migration runs after the later one+ // has already re-assigned the Goal, so its target is stale.+ await service().setAgent(id, 'second-target');+ expect(await manager().moveConversationTo(id, 'first-target')).toBeUndefined();++ const state = (await model().findById(id))!.config!.managerState!;+ const [topic] = await db.select().from(topics).where(eq(topics.id, state.topicId));+ expect(topic?.agentId).toBe('second-target');+ });+it('rejects wrong owner, operation, pause and changed graph without adding tasks', async () => {const { id, state, op } = await start();await expect(diff --git a/apps/server/src/services/goal/manager.ts b/apps/server/src/services/goal/manager.tsindex 34a24dc0440..5a86337907f 100644--- a/apps/server/src/services/goal/manager.ts+++ b/apps/server/src/services/goal/manager.ts@@ -10,6 +10,7 @@ import type {} from '@lobechat/types';import { TRPCError } from '@trpc/server';import { eq, sql } from 'drizzle-orm';+import pMap from 'p-map';import { z } from 'zod';import { TopicTrigger } from '@/const/topic';@@ -74,6 +75,17 @@ const TIMEOUT_MS = 20 * 60_000;/** Source message id prefix of a dispatched planning turn; the suffix is its token. */const MANAGER_SOURCE_MESSAGE_PREFIX = 'msg_goal_manager_';+/**+ * The token a planning turn is keyed by, carrying the Goal it belongs to.+ *+ * The source message `msg_goal_manager_<token>` is the only durable link from a+ * manager operation back to its Goal, so the Goal id has to sit inside it for+ * management spend to be attributable. Without it, a conversation this Goal was+ * moved out of β which can be a normal conversation that later supervised+ * another Goal β would charge that other Goal's turns to this one's budget.+ */+const managerTurnToken = (goalId: string) => `${goalId}_${randomUUID()}`;+/** Excludes only the manager's own receipt. Concurrent policy/graph changes invalidate its plan. */export const managerSnapshot = (graph: GoalGraphSnapshot) => {const { managerState: _state, ...config } = graph.goal.config ?? {};@@ -126,7 +138,7 @@ export class GoalManagerService {private readonly workspaceId?: string,) {}- usage = async (state?: GoalManagerState) => {+ usage = async (goalId: string, state?: GoalManagerState) => {// The planning topic can be the user's own conversation (`/goal`), so only// manager turns count as management spend: the dispatched ones by their// server-minted source message, the adopted one by its operation id. The@@ -136,13 +148,35 @@ export class GoalManagerService {// Later receipts replace `adopted` / `operationId`, so the adopted run is// read from the id every receipt carries forward.const adoptedId = state.adoptedOperationId ?? (state.adopted ? state.operationId : undefined);- const operations = (await model.listByTopic(state.topicId, 100)).filter(- (op) =>- op.appContext?.sourceMessageId?.startsWith(MANAGER_SOURCE_MESSAGE_PREFIX) ||- op.id === adoptedId,+ // A handoff moves later turns to the new agent's topic; the turns already+ // spent in the conversations it left behind still belong to the Goal, so+ // they are summed too instead of dropping out of its budget.+ const goalTokenPrefix = `${MANAGER_SOURCE_MESSAGE_PREFIX}${goalId}_`;+ // One read per conversation the Goal planned in. The list grows with every+ // handoff, so the fan-out is capped rather than left to the history length.+ const reads = await pMap(+ [state.topicId, ...(state.previousTopicIds ?? [])],+ async (topicId, index) => ({+ current: index === 0,+ operations: await model.listByTopic(topicId, 100),+ }),+ { concurrency: 5 },+ );+ const operations = reads.flatMap(({ current, operations: topicOperations }) =>+ topicOperations.filter((op) => {+ if (op.id === adoptedId) return true;+ const source = op.appContext?.sourceMessageId;+ // The Goal's own conversation keeps the historical prefix match: a turn+ // dispatched before the token carried the Goal id has no marker to match.+ if (current) return source?.startsWith(MANAGER_SOURCE_MESSAGE_PREFIX);+ // A conversation the Goal moved out of is matched on the Goal's own+ // marker only. It can be shared with another Goal created in the same+ // conversation, whose turns are not this Goal's spend.+ return source?.startsWith(goalTokenPrefix);+ }),);- // A handoff moves later turns to the new agent's topic; the adopted run- // stays on the original conversation and still counts.+ // The adopted run lives on the conversation that created the Goal; keep it+ // counted even when it is not among the topics read above.if (adoptedId && !operations.some((op) => op.id === adoptedId)) {const adoptedRun = await model.findById(adoptedId);if (adoptedRun) operations.push(adoptedRun);@@ -210,6 +244,53 @@ export class GoalManagerService {return state;});+ /**+ * Move the management conversation onto the agent that now supervises the Goal.+ *+ * The management conversation lives in the goal agent's own history, so+ * handing the Goal to another agent leaves `managerState.topicId` pointing at a+ * conversation the new agent does not own: the supervision panel keeps showing+ * the previous agent's planning thread, and its "open conversation" link opens+ * that agent's chat. Creating the new agent's conversation here, at the+ * handoff, keeps the panel and its link honest immediately instead of only+ * after the next planning claim.+ *+ * Declines while a turn is unclaimed in flight: `settleInFlight` finds that+ * turn's run through `state.topicId`, so re-pointing early would strand it as+ * unconfirmed and pause the Goal. `startTurn` migrates on the next claim in+ * that case. It also declines when the Goal no longer belongs to the target: an+ * overlapping handoff that landed later owns the answer, and migrating to this+ * call's stale target would leave the conversation owned by an agent the Goal+ * is not assigned to. The Goal row is locked, like every other receipt write.+ */+ moveConversationTo = async (+ goalId: string,+ agentId: string,+ ): Promise<GoalManagerState | undefined> =>+ this.db.transaction(async (db) => {+ const model = new GoalModel(db, this.userId, this.workspaceId);+ const goal = await model.lockById(goalId);+ const state = goal?.config?.managerState;+ if (!goal || !state || !state.consumed || goal.agentId !== agentId) return;+ const topicModel = new TopicModel(db, this.userId, this.workspaceId);+ const current = await topicModel.findById(state.topicId);+ if (current?.agentId === agentId) return;+ const topic = 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,+ });+ const next: GoalManagerState = {+ ...state,+ topicId: topic.id,+ previousTopicIds: [...new Set([...(state.previousTopicIds ?? []), state.topicId])],+ };+ await this.save(db, goalId, next);+ return next;+ });+private save = async (db: LobeChatDatabase, id: string, state: GoalManagerState) => {// Caller holds the owned Goal row lock. Do not overwrite concurrent policy namespaces.await db@@ -258,6 +339,7 @@ export class GoalManagerService {graph.nodes.flatMap((n) => (n.taskId ? [n.taskId] : [])),);const management = await new GoalManagerService(db, this.userId, this.workspaceId).usage(+ graph.goal.id,graph.goal.config?.managerState,);const goal = graph.goal;@@ -541,8 +623,14 @@ export class GoalManagerService {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.+ // Read it from the LOCKED row, not the caller's graph: `moveConversationTo`+ // can have migrated the conversation between the graph read and this claim,+ // and going by the stale topic would mint a second one for the same agent.+ const freshState = fresh.config?.managerState;const topicModel = new TopicModel(db, this.userId, this.workspaceId);- const previousTopic = state?.topicId ? await topicModel.findById(state.topicId) : undefined;+ const previousTopic = freshState?.topicId+ ? await topicModel.findById(freshState.topicId)+ : undefined;const topicId =previousTopic?.agentId === agentId? previousTopic.id@@ -555,6 +643,16 @@ export class GoalManagerService {trigger: TopicTrigger.GoalSupervision,})).id;+ // This claim is the other place the management topic changes (besides+ // `moveConversationTo`, which only runs between turns): a handoff that+ // landed mid-turn migrates here. The conversation being left keeps+ // counting, so it joins the history the receipt carries forward.+ const previousTopicIds = [+ ...new Set([+ ...(freshState?.previousTopicIds ?? []),+ ...(freshState?.topicId && freshState.topicId !== topicId ? [freshState.topicId] : []),+ ]),+ ];const reviews = await this.reviews(current, db);const next: GoalManagerState = {...(problem@@ -564,10 +662,11 @@ export class GoalManagerService {}: {}),...(state?.adoptedOperationId && { adoptedOperationId: state.adoptedOperationId }),+ ...(previousTopicIds.length > 0 && { previousTopicIds }),reviewSnapshot: reviews.hash,topicId,turns: (state?.turns ?? 0) + 1,- token: randomUUID(),+ token: managerTurnToken(goal.id),snapshot: managerSnapshot(current),startedAt: new Date().toISOString(),};diff --git a/packages/types/src/goal.ts b/packages/types/src/goal.tsindex 1c866270b20..263cb4302ab 100644--- a/packages/types/src/goal.ts+++ b/packages/types/src/goal.ts@@ -245,6 +245,13 @@ export interface GoalManagerState {*/dispatchNeverStarted?: boolean;operationId?: string;+ /**+ * Management conversations this Goal planned in before a handoff moved it to+ * another agent's topic. `topicId` always points at the current agent's+ * conversation; the earlier ones are kept here so the turns already spent in+ * them keep counting toward the Goal's management usage and budget.+ */+ previousTopicIds?: string[];/*** The problem this turn was invited to take over, when the coordinator handed* one over instead of opening a human gate. Its presence is what separates adiff --git a/src/features/AgentGoals/GoalSupervision.tsx b/src/features/AgentGoals/GoalSupervision.tsxindex 876626f318f..5b89a12649e 100644--- a/src/features/AgentGoals/GoalSupervision.tsx+++ b/src/features/AgentGoals/GoalSupervision.tsx@@ -3,7 +3,7 @@ import { agentDisplayName } from '@lobechat/types';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 { memo, useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';@@ -23,6 +23,23 @@ interface GoalSupervisionProps {topicId: string;}+/**+ * A management conversation freshly moved to another agent has no turns yet.+ * Say so, instead of leaving the panel with an empty list.+ */+const WaitingForFirstRun = memo(() => {+ const { t } = useTranslation('chat');+ return (+ <Flexbox align={'center'} flex={1} justify={'center'} padding={24}>+ <Text style={{ fontSize: 14, textAlign: 'center' }} type={'secondary'}>+ {t('goalProcess.manager.pending')}+ </Text>+ </Flexbox>+ );+});++WaitingForFirstRun.displayName = 'GoalSupervisionWaiting';+/** The manager's ongoing record is inspectable without sending or editing messages. */export const GoalSupervision = ({ agentId, goalId, onCollapse, topicId }: GoalSupervisionProps) => {const { t } = useTranslation('chat');@@ -85,7 +102,7 @@ export const GoalSupervision = ({ agentId, goalId, onCollapse, topicId }: GoalSu}/><Flexbox flex={1} style={{ minHeight: 0, overflow: 'hidden' }}>- <ChatList disableActionsBar itemContent={itemContent} />+ <ChatList disableActionsBar itemContent={itemContent} welcome={<WaitingForFirstRun />} /></Flexbox></Flexbox></GoalChatProvider>