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(topic): hand a topic's goal to the agent the topic moves to (#21383)

Arvin Xub70bcdaae2d3
diff --git a/apps/server/src/routers/lambda/topic/update.ts b/apps/server/src/routers/lambda/topic/update.ts
index e1efc8bc6a5..c028c58a4ea 100644
--- a/apps/server/src/routers/lambda/topic/update.ts
+++ b/apps/server/src/routers/lambda/topic/update.ts
@@ -7,7 +7,9 @@ import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
+import { TopicRepository } from '@/database/repositories/topic';
import { router } from '@/libs/trpc/lambda';
+import { GoalTopicHandoffService } from '@/server/services/goal/topicHandoff';
import { assertWorkspaceRowManageable } from '../_helpers/assertWorkspaceRowManageable';
import {
@@ -123,8 +125,22 @@ export const updateRouter = router({
// `assertCreatorTopicTargets` for why this guard sits at the RPC
// boundary rather than in the model defaults.
await assertCreatorTopicTargets(guardCtx(ctx), input.topicIds);
-
- return ctx.topicRepo.batchMoveToAgent(input.topicIds, input.targetAgentId);
+ // A goal supervised from a moved topic follows it to the target agent;
+ // left on the previous agent it would keep dispatching there. The move
+ // and every handoff commit together, so a failed handoff never leaves a
+ // topic moved without its goal. Moving first locks the topic rows, and
+ // the goals bound to them are locked and checked after it.
+ const workspaceId = ctx.workspaceId ?? undefined;
+ return ctx.serverDB.transaction(async (tx) => {
+ await new TopicRepository(tx, ctx.userId, workspaceId).batchMoveToAgent(
+ input.topicIds,
+ input.targetAgentId,
+ );
+ const goalHandoff = new GoalTopicHandoffService(tx, ctx.userId, workspaceId);
+ const goals = await goalHandoff.lockFollowing(input.topicIds, input.targetAgentId);
+ for (const goal of goals) assertWorkspaceRowManageable(ctx, goal.userId, 'goal');
+ return { movedGoalIds: await goalHandoff.handOver(goals, input.targetAgentId) };
+ });
}),
cancelRateLimitContinuation: topicProcedure
.use(withScopedPermission('topic:update'))
diff --git a/apps/server/src/services/goal/topicHandoff.test.ts b/apps/server/src/services/goal/topicHandoff.test.ts
new file mode 100644
index 00000000000..f45ae0f35dc
--- /dev/null
+++ b/apps/server/src/services/goal/topicHandoff.test.ts
@@ -0,0 +1,144 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getTestDB } from '@/database/core/getTestDB';
+import { GoalModel } from '@/database/models/goal';
+import { TaskModel } from '@/database/models/task';
+import {
+ agents,
+ goalEdges,
+ goalEvents,
+ goalNodes,
+ goals,
+ tasks,
+ topics,
+ users,
+} from '@/database/schemas';
+import { topicRouter } from '@/server/routers/lambda/topic';
+
+import type * as AssignmentModule from './assignment';
+import { GoalService } from './index';
+
+vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: () => db }));
+vi.mock('@/libs/oidc-provider/access-control', () => ({ assertOIDCUserActive: async () => {} }));
+// Fails the Nth `setAgent` call when set; `setAgent` is an instance field, so
+// it is wrapped per instance rather than spied on the prototype.
+const handoff = vi.hoisted(() => ({ calls: 0, failOnCall: 0 }));
+vi.mock('./assignment', async (importOriginal) => {
+ const actual = await importOriginal<typeof AssignmentModule>();
+ class GoalAssignmentService extends actual.GoalAssignmentService {
+ constructor(...args: ConstructorParameters<typeof actual.GoalAssignmentService>) {
+ super(...args);
+ const setAgent = this.setAgent;
+ this.setAgent = async (...setAgentArgs) => {
+ handoff.calls += 1;
+ if (handoff.calls === handoff.failOnCall) throw new Error('Goal not found');
+ return setAgent(...setAgentArgs);
+ };
+ }
+ }
+ return { ...actual, GoalAssignmentService };
+});
+vi.mock('@/database/models/rbac', () => ({
+ RbacModel: class {
+ hasAnyPermission = async () => true;
+ },
+}));
+
+const db = await getTestDB();
+const userId = 'goal-topic-handoff-user';
+const sourceAgentId = 'goal-topic-handoff-source';
+const targetAgentId = 'goal-topic-handoff-target';
+const topicId = 'tpc_goal_topic_handoff';
+
+const caller = () => topicRouter.createCaller({ userId } as any);
+const goalModel = () => new GoalModel(db, userId);
+
+beforeEach(async () => {
+ await db.insert(users).values({ id: userId }).onConflictDoNothing();
+ await db.insert(agents).values([
+ { id: sourceAgentId, userId },
+ { id: targetAgentId, userId },
+ ]);
+ await db.insert(topics).values({ agentId: sourceAgentId, id: topicId, userId });
+});
+
+afterEach(async () => {
+ vi.restoreAllMocks();
+ handoff.calls = 0;
+ handoff.failOnCall = 0;
+ for (const table of [goalEdges, goalEvents, goalNodes, goals, topics, tasks, agents, users])
+ await db.delete(table);
+});
+
+/** A goal supervised from `topicId` by the source agent, with one Task still to do. */
+async function goalBoundToTopic() {
+ const graph = await new GoalService(db, userId).create({
+ agentId: sourceAgentId,
+ tasks: ['Verify on device'],
+ title: 'Goal run from a conversation',
+ });
+ const taskNode = graph.nodes.find((node) => node.kind === 'task')!;
+ const task = await new TaskModel(db, userId).create({
+ assigneeAgentId: sourceAgentId,
+ instruction: 'Verify on device',
+ status: 'paused',
+ });
+ await db.update(goalNodes).set({ taskId: task.id }).where(eq(goalNodes.id, taskNode.id));
+ await db
+ .update(goals)
+ .set({
+ config: { manager: {}, managerState: { consumed: true, topicId, turns: 4 } } as any,
+ status: 'running',
+ subjectId: topicId,
+ subjectType: 'topic',
+ })
+ .where(eq(goals.id, graph.goal.id));
+ return { id: graph.goal.id, taskId: task.id };
+}
+
+describe('topic.batchMoveTopics with a goal bound to the topic', () => {
+ it('hands the goal and its unfinished Tasks to the target agent', async () => {
+ const { id, taskId } = await goalBoundToTopic();
+
+ const result = await caller().batchMoveTopics({ targetAgentId, topicIds: [topicId] });
+
+ expect(result).toEqual({ movedGoalIds: [id] });
+ const goal = (await goalModel().findById(id))!;
+ expect(goal).toMatchObject({ agentId: targetAgentId, subjectId: topicId });
+ // The moved conversation is the target's now, so planning keeps landing there.
+ expect(goal.config?.managerState?.topicId).toBe(topicId);
+ expect((await new TaskModel(db, userId).findById(taskId))!.assigneeAgentId).toBe(targetAgentId);
+ });
+
+ it('leaves finished goals with the agent that ran them', async () => {
+ const { id } = await goalBoundToTopic();
+ await db.update(goals).set({ status: 'achieved' }).where(eq(goals.id, id));
+
+ const result = await caller().batchMoveTopics({ targetAgentId, topicIds: [topicId] });
+
+ expect(result).toEqual({ movedGoalIds: [] });
+ expect((await goalModel().findById(id))!.agentId).toBe(sourceAgentId);
+ });
+
+ it('rolls the move back when a handoff fails, so no topic leaves its goal behind', async () => {
+ const first = await goalBoundToTopic();
+ const second = await goalBoundToTopic();
+ handoff.failOnCall = 2;
+
+ await expect(
+ caller().batchMoveTopics({ targetAgentId, topicIds: [topicId] }),
+ ).rejects.toThrow();
+
+ const [topic] = await db.select().from(topics).where(eq(topics.id, topicId));
+ expect(topic.agentId).toBe(sourceAgentId);
+ // The handoff that succeeded before the failure is undone with the move.
+ for (const { id, taskId } of [first, second]) {
+ expect((await goalModel().findById(id))!.agentId).toBe(sourceAgentId);
+ expect((await new TaskModel(db, userId).findById(taskId))!.assigneeAgentId).toBe(
+ sourceAgentId,
+ );
+ }
+ });
+});
diff --git a/apps/server/src/services/goal/topicHandoff.ts b/apps/server/src/services/goal/topicHandoff.ts
new file mode 100644
index 00000000000..cf57adf8236
--- /dev/null
+++ b/apps/server/src/services/goal/topicHandoff.ts
@@ -0,0 +1,53 @@
+import type { GoalItem } from '@lobechat/types';
+
+import { GoalModel } from '@/database/models/goal';
+import type { LobeChatDatabase } from '@/database/type';
+
+import { GoalAssignmentService } from './assignment';
+
+/**
+ * Keeps a goal with the conversation it is supervised from when that
+ * conversation moves to another agent.
+ *
+ * Moving a topic rewrites only the conversation rows. A goal bound to it kept
+ * its previous agent, so the coordinator went on dispatching the goal's Tasks
+ * to that agent, planned in a new hidden conversation of that agent, and
+ * refused the new agent's run in the moved conversation β€” the goal looked
+ * frozen from the conversation the user was now working in. The goal is
+ * handed over the way `lh goal set-agent` does: the target becomes its
+ * supervisor, its unfinished Tasks follow unless it has a dedicated executor,
+ * and its planning turns keep landing in the moved conversation, which the
+ * target now owns.
+ *
+ * Construct it on the transaction that moves the topics. A handoff that fails
+ * after the move would otherwise leave the topic moved and its goal behind β€”
+ * the very state this exists to prevent β€” so the failure has to roll the move
+ * back with it.
+ */
+export class GoalTopicHandoffService {
+ private assignment: GoalAssignmentService;
+ private goalModel: GoalModel;
+
+ constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
+ this.assignment = new GoalAssignmentService(db, userId, workspaceId);
+ this.goalModel = new GoalModel(db, userId, workspaceId);
+ }
+
+ /**
+ * Lock the goals that must follow these topics to `targetAgentId`. Throws
+ * when the target cannot supervise one of them, which rolls the move back
+ * instead of leaving the goal on the previous agent.
+ */
+ lockFollowing = async (topicIds: string[], targetAgentId: string): Promise<GoalItem[]> => {
+ const bound = await this.goalModel.lockUnfinishedBySubjectTopics(topicIds);
+ const following = bound.filter((goal) => goal.agentId !== targetAgentId);
+ for (const goal of following) await this.assignment.assertUsableForGoal(goal, targetAgentId);
+ return following;
+ };
+
+ /** Hand the locked goals to `targetAgentId`. */
+ handOver = async (goals: GoalItem[], targetAgentId: string): Promise<string[]> => {
+ for (const goal of goals) await this.assignment.setAgent(goal.id, targetAgentId);
+ return goals.map((goal) => goal.id);
+ };
+}
diff --git a/packages/database/src/models/goal.ts b/packages/database/src/models/goal.ts
index d036a108ea7..eb81d4aa08b 100644
--- a/packages/database/src/models/goal.ts
+++ b/packages/database/src/models/goal.ts
@@ -106,6 +106,28 @@ export class GoalModel {
return row?.goal;
};
+ /**
+ * Lock the unfinished goals supervised from these conversations
+ * (`subject_type = 'topic'`). Finished goals are left out: nothing dispatches
+ * for them, so the agent they were run by stays part of their record. Call
+ * inside a transaction; the locks hold the rows until it commits.
+ */
+ lockUnfinishedBySubjectTopics = async (topicIds: string[]): Promise<GoalItem[]> => {
+ if (topicIds.length === 0) return [];
+ return this.db
+ .select()
+ .from(goals)
+ .where(
+ and(
+ eq(goals.subjectType, 'topic'),
+ inArray(goals.subjectId, topicIds),
+ notInArray(goals.status, [...TERMINAL_GOAL_STATUSES]),
+ this.ownership(),
+ ),
+ )
+ .for('update');
+ };
+
/** The Goal that owns a graph node, or undefined when the node is not in the caller's scope. */
findByNode = async (nodeId: string): Promise<GoalItem | undefined> => {
const [row] = await this.db