🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(goal): pick the main agent and its planning model on the goal page (#21070)
Arvin Xu1961760f9c73
diff --git a/apps/server/src/routers/lambda/goal/configuration.ts b/apps/server/src/routers/lambda/goal/configuration.tsindex 1bfd72e7c56..467ea50eb56 100644--- a/apps/server/src/routers/lambda/goal/configuration.ts+++ b/apps/server/src/routers/lambda/goal/configuration.ts@@ -173,6 +173,50 @@ export const configurationRouter = router({mapGoalError(error, 'setTaskAgent');}}),+ /**+ * Pick the model the goal agent plans with (`null` falls back to the agent's+ * own). Tasks keep their own model.+ */+ setModel: goalWriteProcedure+ .input(+ idInput.extend({+ modelConfig: z.object({ model: z.string().min(1), provider: z.string().min(1) }).nullable(),+ }),+ )+ .mutation(async ({ ctx, input: { id, modelConfig } }) => {+ 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.setModel(id, modelConfig);+ return { data, message: 'Goal model updated', success: true };+ } catch (error) {+ mapGoalError(error, 'setModel');+ }+ }),+ /**+ * Pick the model the goal's Tasks run on (`null` falls back to their+ * executor's own). Unfinished Tasks switch with it.+ */+ setTaskModel: goalWriteProcedure+ .input(+ idInput.extend({+ modelConfig: z.object({ model: z.string().min(1), provider: z.string().min(1) }).nullable(),+ }),+ )+ .mutation(async ({ ctx, input: { id, modelConfig } }) => {+ 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.setTaskModel(id, modelConfig);+ return { data, message: 'Goal task model updated', success: true };+ } catch (error) {+ mapGoalError(error, 'setTaskModel');+ }+ }),setBudget: goalWriteProcedure.input(idInput.extend({diff --git a/apps/server/src/routers/lambda/goal/index.procedures.test.ts b/apps/server/src/routers/lambda/goal/index.procedures.test.tsindex 627ead52414..1cad5dcf63d 100644--- a/apps/server/src/routers/lambda/goal/index.procedures.test.ts+++ b/apps/server/src/routers/lambda/goal/index.procedures.test.ts@@ -58,7 +58,9 @@ function expected(): Array<['setAgent', 'mutation', 13],['setBudget', 'mutation', 13],['setMetricCriteria', 'mutation', 13],+ ['setModel', 'mutation', 13],['setTaskAgent', 'mutation', 13],+ ['setTaskModel', 'mutation', 13],['start', 'mutation', 13],['startOperation', 'mutation', 8],['submitOperationPlan', 'mutation', 8],diff --git a/apps/server/src/services/goal/GoalService/__tests__/clarification.test.ts b/apps/server/src/services/goal/GoalService/__tests__/clarification.test.tsindex a83f9e89696..036d83f8bb5 100644--- a/apps/server/src/services/goal/GoalService/__tests__/clarification.test.ts+++ b/apps/server/src/services/goal/GoalService/__tests__/clarification.test.ts@@ -106,7 +106,7 @@ describe('GoalService', () => {// The re-plan receives the answer and, even though the planner still// reports a blocking question, proceeds on assumptions: one round only.expect((await service.tick(graph.goal.id)).outcome).toBe('advanced');- expect(planner).toHaveBeenLastCalledWith({+ expect(planner.mock.lastCall?.[0]).toMatchObject({clarifications: [{ answer: '开发者 (只关心 SDK)', question: '这份说明给谁看?' }],requirement: expect.any(String),});diff --git a/apps/server/src/services/goal/GoalService/__tests__/surface.test.ts b/apps/server/src/services/goal/GoalService/__tests__/surface.test.tsindex 44931d82640..0d03bcc9441 100644--- a/apps/server/src/services/goal/GoalService/__tests__/surface.test.ts+++ b/apps/server/src/services/goal/GoalService/__tests__/surface.test.ts@@ -105,8 +105,10 @@ const METHODS = ['setAgent','setBudget','setMetricCriteria',+ 'setModel','setPauseReason','setTaskAgent',+ 'setTaskModel','settleTerminalAcceptance','status','stopFencedTasks',diff --git a/apps/server/src/services/goal/GoalService/creation.ts b/apps/server/src/services/goal/GoalService/creation.tsindex c4a40ba7730..f2c0155ba68 100644--- a/apps/server/src/services/goal/GoalService/creation.ts+++ b/apps/server/src/services/goal/GoalService/creation.ts@@ -9,6 +9,7 @@ import { TopicModel } from '@/database/models/topic';import { assertAgentUsableBy } from '@/database/utils/agent-access';import { VerifyPlanGeneratorService } from '../../verify/planGenerator';+import { GoalAssignmentService, staleModelSlots } from '../assignment';import { GoalManagerService } from '../manager';import { DEFAULT_MANAGER_MAX_TURNS } from '../recoveryPolicy';import { seedGoalTasks } from '../seedTasks';@@ -147,10 +148,17 @@ export const bindTopic = async ({ agentId, operationId, topicId },{ force: options?.force },);- const reassignedTaskIds =- bound.previousAgentId === agentId- ? []- : await ctx.inTransaction(tx).followGoalAgent(bound.goal, agentId, options?.goalOnly);+ if (bound.previousAgentId === agentId) return { bound, reassignedTaskIds: [] };+ // The previous agent's model overrides do not carry to the new one.+ const assignment = new GoalAssignmentService(tx, ctx.userId, ctx.workspaceId);+ const goal = await assignment.dropModelOverride(+ bound.goal,+ staleModelSlots(+ { agentId: bound.previousAgentId ?? null, config: bound.goal.config },+ bound.goal,+ ),+ );+ const reassignedTaskIds = await assignment.followGoalAgent(goal, agentId, options?.goalOnly);return { bound, reassignedTaskIds };});return {diff --git a/apps/server/src/services/goal/GoalService/dispatch.ts b/apps/server/src/services/goal/GoalService/dispatch.tsindex 84b41e9eb45..b923c7af9bf 100644--- a/apps/server/src/services/goal/GoalService/dispatch.ts+++ b/apps/server/src/services/goal/GoalService/dispatch.ts@@ -8,6 +8,7 @@ import { GoalGraphModel } from '@/database/models/goalGraph';import { TaskModel } from '@/database/models/task';import { TaskRunnerService } from '../../taskRunner';+import { GoalAssignmentService } from '../assignment';import { learnedRulesClause, planSkillIdentifier } from '../batchPlanSkill';import { GOAL_ACCEPTANCE_TASK_TITLE } from '../decideNextMove';import { clearDeviceDispatchStreak, parkDeviceUnavailableDispatch } from '../deviceDispatchStreak';@@ -76,11 +77,17 @@ export const createResponsibleTask = async (const batchUnit = frontier.kind === 'task' && ctx.isBatchMember(graph, frontier.id);const planSkill = batchUnit ? rollout?.planSkill : undefined;const learnedRules = batchUnit ? (rollout?.learnings ?? []) : [];+ const assignment = await new GoalAssignmentService(+ ctx.db,+ ctx.userId,+ ctx.workspaceId,+ ).newTaskAssignment(graph.goal);task = await ctx.taskService.createTask({- assigneeAgentId: await ctx.resolveTaskAssignee(graph.goal),+ assigneeAgentId: assignment.assigneeAgentId,config: {checkpoint: { topic: { after: false } },...(planSkill ? { skills: [planSkillIdentifier(planSkill)] } : {}),+ ...assignment.model,},description: description?.slice(0, TASK_DESCRIPTION_MAX_LENGTH),instruction: ctx.buildTaskInstruction(graph, frontier.title, description),@@ -123,6 +130,12 @@ export const createResponsibleTask = async (outcome: 'waiting_external',};}+ // A handoff or Task-model change committed while this Task was being+ // created scanned the graph before the bind; align it with the goal now.+ await new GoalAssignmentService(ctx.db, ctx.userId, ctx.workspaceId).syncBoundTask(+ goalId,+ task.id,+ );} catch (error) {if (acceptanceId) {await ctx.acceptanceService.acceptanceModel.delete(acceptanceId).catch(() => {});diff --git a/apps/server/src/services/goal/GoalService/editing.ts b/apps/server/src/services/goal/GoalService/editing.tsindex 1b36680879d..e0b7cc510d7 100644--- a/apps/server/src/services/goal/GoalService/editing.ts+++ b/apps/server/src/services/goal/GoalService/editing.ts@@ -4,19 +4,17 @@ import { TRPCError } from '@trpc/server';import { GoalGraphModel } from '@/database/models/goalGraph';import { TaskModel } from '@/database/models/task';import { TaskTopicModel } from '@/database/models/taskTopic';-import { assertAgentUsableBy } from '@/database/utils/agent-access';import { TaskService } from '../../task';+import { GoalAssignmentService } from '../assignment';import {GOAL_ACCEPTANCE_TASK_TITLE,NO_FRONTIER_PAUSE_REASON,TERMINAL_NODE_STATUSES,} from '../decideNextMove';-import { GoalManagerService } from '../manager';import { managerTurnsSpent } from '../recoveryPolicy';import { isGoalReportNode } from '../report';import type { CreateGoalNodeInput, GoalServiceContext } from './types';-import { goalTaskAgentId } from './utils';/*** The graph model whose audit trail names `agentId` as the author, or the@@ -65,127 +63,50 @@ export const updateRequirement = async (};/**- * 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`.- *- * 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.+ * Who works on a goal and with which model lives in `GoalAssignmentService`:+ * handoffs, the Task executor and both model slots share its locked+ * transactions, so these methods only bind it to this service's principal.*/-export const setAgent = async (- ctx: GoalServiceContext,- goalId: string,- agentId: string,- options?: { goalOnly?: boolean },-): Promise<{ goal: GoalItem; reassignedTaskIds: string[] }> => {- await assertAgentUsableBy(ctx.db, agentId, {- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });- const goal = await ctx.goalModel.update(goalId, { agentId });- if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });+const assignmentFor = (ctx: GoalServiceContext) =>+ new GoalAssignmentService(ctx.db, ctx.userId, ctx.workspaceId);- // 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(- ctx.db,- ctx.userId,- ctx.workspaceId,- ).moveConversationTo(goalId, agentId);+/** Hand the goal to a different agent; see `GoalAssignmentService.setAgent`. */+export const setAgent = (+ ctx: GoalServiceContext,+ ...args: Parameters<GoalAssignmentService['setAgent']>+) => assignmentFor(ctx).setAgent(...args);- const reassignedTaskIds = await ctx.followGoalAgent(goal, agentId, options?.goalOnly);- return {- goal: migrated ? ((await ctx.goalModel.findById(goalId)) ?? goal) : goal,- reassignedTaskIds,- };-};+/** Unfinished Tasks follow a new goal agent; see `GoalAssignmentService.followGoalAgent`. */+export const followGoalAgent = (+ ctx: GoalServiceContext,+ ...args: Parameters<GoalAssignmentService['followGoalAgent']>+) => assignmentFor(ctx).followGoalAgent(...args);-/**- * After the goal agent changed: when that agent also does the goal's Tasks,- * unfinished ones follow it unless the caller keeps them (`goalOnly`). A goal- * with a dedicated executor keeps its Tasks there.- */-export const followGoalAgent = async (+/** Route Tasks to a dedicated executor; see `GoalAssignmentService.setTaskAgent`. */+export const setTaskAgent = (ctx: GoalServiceContext,- goal: Pick<GoalItem, 'config' | 'id'>,- agentId: string,- goalOnly?: boolean,-) => (goalOnly || goal.config?.taskAgentId ? [] : ctx.reassignUnfinishedTasks(goal.id, agentId));+ ...args: Parameters<GoalAssignmentService['setTaskAgent']>+) => assignmentFor(ctx).setTaskAgent(...args);-/**- * 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.- */-export const setTaskAgent = async (+/** The model planning turns run on; see `GoalAssignmentService.setModel`. */+export const setModel = (ctx: GoalServiceContext,- goalId: string,- agentId: string | null,- options?: { goalOnly?: boolean },-): Promise<{ goal: GoalItem; reassignedTaskIds: string[] }> => {- if (agentId) {- await assertAgentUsableBy(ctx.db, agentId, {- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });- }- const current = await ctx.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 ctx.goalModel.updateTaskAgentId(- goalId,- agentId && agentId !== current.agentId ? agentId : null,- );- if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });+ ...args: Parameters<GoalAssignmentService['setModel']>+) => assignmentFor(ctx).setModel(...args);- const assignee = goalTaskAgentId(goal);- const reassignedTaskIds =- options?.goalOnly || !assignee ? [] : await ctx.reassignUnfinishedTasks(goalId, assignee);- return { goal, reassignedTaskIds };-};+/** The model the goal's Tasks run on; see `GoalAssignmentService.setTaskModel`. */+export const setTaskModel = (+ ctx: GoalServiceContext,+ ...args: Parameters<GoalAssignmentService['setTaskModel']>+) => assignmentFor(ctx).setTaskModel(...args);-/**- * 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.- */-export const resolveTaskAssignee = async (ctx: GoalServiceContext, goal: GoalItem) => {- const taskAgentId = goal.config?.taskAgentId;- if (taskAgentId && !(await ctx.agentModel.existsById(taskAgentId)))- return goal.agentId ?? undefined;- return goalTaskAgentId(goal);-};+/** The agent the next coordinator-created Task goes to. */+export const resolveTaskAssignee = (ctx: GoalServiceContext, goal: GoalItem) =>+ assignmentFor(ctx).resolveTaskAssignee(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.- */-export const reassignUnfinishedTasks = async (- ctx: GoalServiceContext,- goalId: string,- agentId: string,-) => {- const graph = await ctx.requireGraph(goalId);- const taskIds = graph.nodes.flatMap((node) => (node.taskId ? [node.taskId] : []));- const reassigned: string[] = [];- for (const task of await ctx.taskModel.findByIds(taskIds)) {- if (task.status === 'completed' || task.status === 'canceled') continue;- if (task.assigneeAgentId === agentId) continue;- await ctx.taskModel.update(task.id, { assigneeAgentId: agentId });- reassigned.push(task.id);- }- return reassigned;-};+/** Move unfinished Tasks (and their model) to `agentId`. */+export const reassignUnfinishedTasks = (ctx: GoalServiceContext, goalId: string, agentId: string) =>+ assignmentFor(ctx).reassignUnfinishedTasks(goalId, agentId);/*** Task access under the goal owner's principal — the identity the goal'sdiff --git a/apps/server/src/services/goal/GoalService/index.ts b/apps/server/src/services/goal/GoalService/index.tsindex 679cc0dc80c..5facb1cf454 100644--- a/apps/server/src/services/goal/GoalService/index.ts+++ b/apps/server/src/services/goal/GoalService/index.ts@@ -45,7 +45,9 @@ import {retireNodes,setAgent,setBudget,+ setModel,setTaskAgent,+ setTaskModel,stopFencedTasks,updateRequirement,} from './editing';@@ -266,8 +268,10 @@ export class GoalService {setAgent: (...args) => self.setAgent(...args),setBudget: (...args) => self.setBudget(...args),setMetricCriteria: (...args) => self.setMetricCriteria(...args),+ setModel: (...args) => self.setModel(...args),setPauseReason: (...args) => self.setPauseReason(...args),setTaskAgent: (...args) => self.setTaskAgent(...args),+ setTaskModel: (...args) => self.setTaskModel(...args),settleTerminalAcceptance: (...args) => self.settleTerminalAcceptance(...args),status: (...args) => self.status(...args),stopFencedTasks: (...args) => self.stopFencedTasks(...args),@@ -384,6 +388,10 @@ export class GoalService {setTaskAgent = (...args: MethodArgs<typeof setTaskAgent>) => setTaskAgent(this.context, ...args);+ setModel = (...args: MethodArgs<typeof setModel>) => setModel(this.context, ...args);++ setTaskModel = (...args: MethodArgs<typeof setTaskModel>) => setTaskModel(this.context, ...args);+private resolveTaskAssignee = (...args: MethodArgs<typeof resolveTaskAssignee>) =>resolveTaskAssignee(this.context, ...args);diff --git a/apps/server/src/services/goal/GoalService/lifecycle.ts b/apps/server/src/services/goal/GoalService/lifecycle.tsindex fc7ffc99860..3c4ca2b0466 100644--- a/apps/server/src/services/goal/GoalService/lifecycle.ts+++ b/apps/server/src/services/goal/GoalService/lifecycle.ts@@ -1,18 +1,19 @@-import type { GoalGraphSnapshot, GoalItem, GoalStatus } from '@lobechat/types';+import type { GoalGraphSnapshot, GoalItem, GoalStatus, TaskItem } from '@lobechat/types';import { TRPCError } from '@trpc/server';import { GoalModel } from '@/database/models/goal';import { GoalGraphModel } from '@/database/models/goalGraph';import { TaskModel } from '@/database/models/task';import { TaskTopicModel } from '@/database/models/taskTopic';-import { assertAgentUsableBy } from '@/database/utils/agent-access';+import { GoalAssignmentService } from '../assignment';import { GOAL_ACCEPTANCE_TASK_TITLE, TERMINAL_NODE_STATUSES } from '../decideNextMove';import { GoalManagerService } from '../manager';import { resolveOperationLeaseTimeout } from '../recoveryPolicy';import { isGoalReportNode } from '../report';import { GoalSupervisorService } from '../supervisor';import type { GoalServiceContext } from './types';+import { goalTaskAgentId } from './utils';const draftNotStarted = (goalId: string) =>new TRPCError({@@ -180,13 +181,9 @@ export const restart = async (goalId: string,options?: { agentId?: string },): Promise<{ goal: GoalItem; restartedTaskIds: string[] }> => {- if (options?.agentId) {- await assertAgentUsableBy(ctx.db, options.agentId, {- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });- }const graph = await ctx.requireGraph(goalId);+ const assignment = new GoalAssignmentService(ctx.db, ctx.userId, ctx.workspaceId);+ if (options?.agentId) await assignment.assertUsableForGoal(graph.goal, options.agentId);const unfinishedNodes = graph.nodes.filter((node) =>@@ -219,6 +216,7 @@ export const restart = async (}const restartedTaskIds: string[] = [];+ let candidates: TaskItem[] = [];if (unfinishedTaskIds.length > 0) {const runningTopics = await ctx.taskTopicModel.findRunningByTaskIds(unfinishedTaskIds);for (const topic of runningTopics) {@@ -228,29 +226,43 @@ export const restart = async (// tick dispatching concurrently moves the row between our read and the// write, the CAS loses, and that task is skipped instead of yanked out// from under a freshly claimed run (which would double-dispatch it).- for (const task of await ctx.taskModel.findByIds(unfinishedTaskIds)) {- if (task.status === 'completed') continue;- const reset = await ctx.taskModel.updateStatusIfCurrent(task.id, task.status, 'backlog', {- error: null,- });- if (!reset) continue;- if (options?.agentId) {- await ctx.taskModel.update(task.id, { assigneeAgentId: options.agentId });+ candidates = (await ctx.taskModel.findByIds(unfinishedTaskIds)).filter(+ (task) => task.status !== 'completed',+ );+ if (!options?.agentId) {+ for (const task of candidates) {+ const reset = await ctx.taskModel.updateStatusIfCurrent(task.id, task.status, 'backlog', {+ error: null,+ });+ if (reset) restartedTaskIds.push(task.id);}- restartedTaskIds.push(task.id);}}// The handoff lands only after the interrupts succeeded — a cancelTopic// failure above must not leave the goal pointing at the new agent while- // its tasks and live runs still belong to the old one.+ // its tasks and live runs still belong to the old one. The Tasks restart+ // onto the new agent inside the handoff's own transaction, so no tick can+ // claim one with the new assignee but the previous executor's model.let goal = graph.goal;if (options?.agentId) {- const updated = goal.config?.taskAgentId- ? await ctx.goalModel.updateTaskAgentId(goalId, options.agentId)- : await ctx.goalModel.update(goalId, { agentId: options.agentId });- if (!updated) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });- goal = updated;+ const agentId = options.agentId;+ const handed = await assignment.handOver(+ goalId,+ (model, current) =>+ current.config?.taskAgentId+ ? model.updateTaskAgentId(goalId, agentId)+ : model.update(goalId, { agentId }),+ (scoped, handedGoal, previous) =>+ scoped.restartTasks(+ handedGoal,+ candidates,+ agentId,+ goalTaskAgentId(previous) !== goalTaskAgentId(handedGoal),+ ),+ );+ goal = handed.goal;+ restartedTaskIds.push(...handed.movedTaskIds);}// A restart is an explicit "start over": a goal parked by a budget stop ordiff --git a/apps/server/src/services/goal/GoalService/planning.ts b/apps/server/src/services/goal/GoalService/planning.tsindex 7d938a007fe..ac142845245 100644--- a/apps/server/src/services/goal/GoalService/planning.ts+++ b/apps/server/src/services/goal/GoalService/planning.ts@@ -104,7 +104,7 @@ export const planDecomposition = async (// so: the server log and the first task's audit event carry the cause.let plannerFailure: string | undefined;const plan = await generator- .decompose({ clarifications, requirement })+ .decompose({ clarifications, goalConfig: graph.goal.config, requirement }).catch((error: unknown) => {plannerFailure = describePlannerFailure(error);console.error(diff --git a/apps/server/src/services/goal/GoalService/types.ts b/apps/server/src/services/goal/GoalService/types.tsindex d75a190f62d..d4fc81f8619 100644--- a/apps/server/src/services/goal/GoalService/types.ts+++ b/apps/server/src/services/goal/GoalService/types.ts@@ -46,7 +46,9 @@ import type {retireNodes,setAgent,setBudget,+ setModel,setTaskAgent,+ setTaskModel,stopFencedTasks,updateRequirement,} from './editing';@@ -253,8 +255,10 @@ export interface GoalServiceContext {setAgent: Bound<typeof setAgent>;setBudget: Bound<typeof setBudget>;setMetricCriteria: Bound<typeof setMetricCriteria>;+ setModel: Bound<typeof setModel>;setPauseReason: Bound<typeof setPauseReason>;setTaskAgent: Bound<typeof setTaskAgent>;+ setTaskModel: Bound<typeof setTaskModel>;settleTerminalAcceptance: Bound<typeof settleTerminalAcceptance>;status: Bound<typeof status>;stopFencedTasks: Bound<typeof stopFencedTasks>;diff --git a/apps/server/src/services/goal/assignment.modelPolicy.test.ts b/apps/server/src/services/goal/assignment.modelPolicy.test.tsnew file mode 100644index 00000000000..f013105380b--- /dev/null+++ b/apps/server/src/services/goal/assignment.modelPolicy.test.ts@@ -0,0 +1,256 @@+// @vitest-environment node+import { randomUUID } from 'node:crypto';++import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import * as businessAiProvider from '@/business/server/aiProvider';+import { getTestDB } from '@/database/core/getTestDB';+import { TaskModel } from '@/database/models/task';+import {+ agents,+ aiModels,+ aiProviders,+ goals,+ tasks,+ users,+ workspaceMembers,+ workspaces,+} from '@/database/schemas';+import * as featureFlags from '@/server/featureFlags';++import { GoalAssignmentService } from './assignment';+import { GoalService } from './index';+import * as scheduler from './scheduler';++const db = await getTestDB();+const authorId = `goal-policy-author-${randomUUID()}`;+const memberId = `goal-policy-member-${randomUUID()}`;+const fixedAgentId = `goal-policy-fixed-${randomUUID()}`;+const openAgentId = `goal-policy-open-${randomUUID()}`;+const gemini = { model: 'gemini-3.8-flash', provider: 'google' };+let workspaceId: string;++/** A goal owned by `userId` whose main agent is `agentId`. */+const goalFor = async (userId: string, agentId: string) => {+ const graph = await new GoalService(db, userId, workspaceId).create({ agentId, title: 'Policy' });+ return graph.goal.id;+};++beforeEach(async () => {+ vi.spyOn(scheduler, 'scheduleGoalAdvance').mockResolvedValue();+ await db.insert(users).values([{ id: authorId }, { id: memberId }]);+ const [workspace] = await db+ .insert(workspaces)+ .values({ name: 'ws', primaryOwnerId: authorId, slug: `ws-${randomUUID()}` })+ .returning();+ workspaceId = workspace.id;+ await db.insert(workspaceMembers).values([+ { role: 'owner', userId: authorId, workspaceId },+ { role: 'member', userId: memberId, workspaceId },+ ]);+ await db.insert(agents).values([+ {+ agencyConfig: { modelSelectionPolicy: 'fixed' },+ id: fixedAgentId,+ model: 'gpt-4o-mini',+ provider: 'openai',+ slug: `fixed-${randomUUID()}`,+ userId: authorId,+ visibility: 'public',+ workspaceId,+ },+ {+ agencyConfig: { modelSelectionPolicy: 'member' },+ id: openAgentId,+ model: 'gpt-4o-mini',+ provider: 'openai',+ slug: `open-${randomUUID()}`,+ userId: authorId,+ visibility: 'public',+ workspaceId,+ },+ ]);+});++afterEach(async () => {+ vi.restoreAllMocks();+ await db.delete(tasks).where(eq(tasks.workspaceId, workspaceId));+ await db.delete(goals).where(eq(goals.workspaceId, workspaceId));+ await db.delete(agents).where(eq(agents.workspaceId, workspaceId));+ await db.delete(workspaces).where(eq(workspaces.id, workspaceId));+ await db.delete(users).where(eq(users.id, authorId));+ await db.delete(users).where(eq(users.id, memberId));+});++describe('goal model overrides on a fixed-model Agent', () => {+ it("refuses a member's planning or Task model, but lets them clear it", async () => {+ const goalId = await goalFor(memberId, fixedAgentId);+ const member = new GoalAssignmentService(db, memberId, workspaceId);++ await expect(member.setModel(goalId, gemini)).rejects.toMatchObject({ code: 'FORBIDDEN' });+ await expect(member.setTaskModel(goalId, gemini)).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ await expect(member.setModel(goalId, null)).resolves.toBeTruthy();+ });++ it('lets the Agent author override it', async () => {+ const goalId = await goalFor(authorId, fixedAgentId);++ const goal = await new GoalAssignmentService(db, authorId, workspaceId).setModel(+ goalId,+ gemini,+ );++ expect(goal.config).toMatchObject({ model: 'gemini-3.8-flash' });+ });++ it('lets a member override an Agent in member-selection mode', async () => {+ const goalId = await goalFor(memberId, openAgentId);++ const goal = await new GoalAssignmentService(db, memberId, workspaceId).setModel(+ goalId,+ gemini,+ );++ expect(goal.config).toMatchObject({ model: 'gemini-3.8-flash' });+ });++ it("switches the owner's private Tasks when a Workspace admin sets the Task model", async () => {+ const privateAgentId = `goal-policy-private-${randomUUID()}`;+ await db.insert(agents).values({+ id: privateAgentId,+ model: 'gpt-4o-mini',+ provider: 'openai',+ slug: `private-${randomUUID()}`,+ userId: memberId,+ visibility: 'private',+ workspaceId,+ });+ const memberGoals = new GoalService(db, memberId, workspaceId);+ const graph = await memberGoals.create({+ agentId: privateAgentId,+ tasks: ['Only task'],+ title: 'Private work',+ });+ const { taskId } = await memberGoals.tick(graph.goal.id);+ const ownTask = () => new TaskModel(db, memberId, workspaceId).findById(taskId!);+ expect((await ownTask())?.visibility).toBe('private');++ // The Workspace owner acts on the member's goal; the Task is still the member's.+ await new GoalAssignmentService(db, authorId, workspaceId).setTaskModel(graph.goal.id, gemini);++ expect((await ownTask())?.config).toMatchObject({ model: 'gemini-3.8-flash' });+ });++ it("falls back to the member's private executor's model when an admin clears the Task model", async () => {+ const privateExecutorId = `goal-policy-private-exec-${randomUUID()}`;+ await db.insert(agents).values({+ id: privateExecutorId,+ model: 'deepseek-chat',+ provider: 'deepseek',+ slug: `private-exec-${randomUUID()}`,+ userId: memberId,+ visibility: 'private',+ workspaceId,+ });+ const memberGoals = new GoalService(db, memberId, workspaceId);+ const graph = await memberGoals.create({+ agentId: openAgentId,+ config: { taskAgentId: privateExecutorId },+ tasks: ['Only task'],+ title: 'Private executor',+ });+ const { taskId } = await memberGoals.tick(graph.goal.id);+ const ownTask = () => new TaskModel(db, memberId, workspaceId).findById(taskId!);+ expect((await ownTask())?.assigneeAgentId).toBe(privateExecutorId);++ const admin = new GoalAssignmentService(db, authorId, workspaceId);+ await admin.setTaskModel(graph.goal.id, gemini);+ await admin.setTaskModel(graph.goal.id, null);++ // The executor is still the member's private Agent, invisible to the admin.+ expect((await ownTask())?.config).toMatchObject({+ model: 'deepseek-chat',+ provider: 'deepseek',+ });+ });++ it("refuses an admin's pick of a model the goal's owner cannot use", async () => {+ // The member's plan hides the model the admin's picker still offers.+ vi.spyOn(businessAiProvider, 'getHiddenBuiltinModelsForUser').mockImplementation(+ async (userId) => (userId === memberId ? [{ id: gemini.model, providerId: 'google' }] : []),+ );+ const goalId = await goalFor(memberId, openAgentId);+ const admin = new GoalAssignmentService(db, authorId, workspaceId);++ // The goal runs as the member, who could not run that model.+ await expect(admin.setModel(goalId, gemini)).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ await expect(admin.setTaskModel(goalId, gemini)).rejects.toMatchObject({+ code: 'BAD_REQUEST',+ });+ // A model the member can run is still fine.+ await db.insert(aiModels).values({+ enabled: true,+ id: 'gemini-team',+ providerId: 'google',+ userId: authorId,+ workspaceId,+ });+ await expect(+ admin.setModel(goalId, { model: 'gemini-team', provider: 'google' }),+ ).resolves.toBeTruthy();+ });++ it('refuses a device-only provider for planning, but not for Tasks', async () => {+ vi.spyOn(featureFlags, 'getServerFeatureFlagsStateFromRuntimeConfig').mockResolvedValue({+ enableLlmRelay: true,+ } as Awaited<ReturnType<typeof featureFlags.getServerFeatureFlagsStateFromRuntimeConfig>>);+ await db.insert(aiProviders).values({+ enabled: true,+ fetchOnClient: true,+ id: 'ollama',+ source: 'builtin',+ userId: memberId,+ workspaceId,+ });+ await db.insert(aiModels).values({+ enabled: true,+ id: 'llama3.1',+ providerId: 'ollama',+ userId: memberId,+ workspaceId,+ });+ const goalId = await goalFor(memberId, openAgentId);+ const local = { model: 'llama3.1', provider: 'ollama' };+ const member = new GoalAssignmentService(db, memberId, workspaceId);++ // Planning advances in the background, with no device to reach it.+ await expect(member.setModel(goalId, local)).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ await expect(member.setTaskModel(goalId, local)).resolves.toBeTruthy();+ });++ it("refuses to hand a member's goal to an admin's private Agent", async () => {+ const adminPrivateId = `goal-policy-admin-private-${randomUUID()}`;+ await db.insert(agents).values({+ id: adminPrivateId,+ slug: `admin-private-${randomUUID()}`,+ userId: authorId,+ visibility: 'private',+ workspaceId,+ });+ const goalId = await goalFor(memberId, openAgentId);+ const admin = new GoalAssignmentService(db, authorId, workspaceId);++ // The member's background runs could never reach the admin's private Agent.+ await expect(admin.setAgent(goalId, adminPrivateId)).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ await expect(admin.setTaskAgent(goalId, adminPrivateId)).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ // A shared Agent the member can use is still fine.+ await expect(admin.setAgent(goalId, fixedAgentId)).resolves.toBeTruthy();+ });+});diff --git a/apps/server/src/services/goal/assignment.taskModel.test.ts b/apps/server/src/services/goal/assignment.taskModel.test.tsnew file mode 100644index 00000000000..1cc2f1e01ee--- /dev/null+++ b/apps/server/src/services/goal/assignment.taskModel.test.ts@@ -0,0 +1,282 @@+// @vitest-environment node+import { eq, sql } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { getTestDB } from '@/database/core/getTestDB';+import { AgentOperationModel } from '@/database/models/agentOperation';+import { TaskModel } from '@/database/models/task';+import {+ agentOperations,+ agents,+ goalEdges,+ goalEvents,+ goalNodeDecisions,+ goalNodes,+ goals,+ messages,+ tasks,+ taskTopics,+ topics,+ users,+} from '@/database/schemas';+import { AiAgentService } from '@/server/services/aiAgent';++import { GoalAssignmentService } from './assignment';+import { GoalService } from './index';+import * as scheduler from './scheduler';++const db = await getTestDB();+const userId = 'goal-task-model-user';+const agentId = 'goal-task-model-agent';+const otherAgentId = 'goal-task-model-other';+let seq = 0;+const service = () => new GoalService(db, userId);++beforeEach(async () => {+ await db.insert(users).values({ id: userId }).onConflictDoNothing();+ await db.insert(agents).values([+ { id: agentId, model: 'gpt-4o-mini', provider: 'openai', slug: 'task-model-agent', userId },+ {+ id: otherAgentId,+ model: 'deepseek-chat',+ provider: 'deepseek',+ slug: 'task-model-other',+ userId,+ },+ ]);+ vi.spyOn(scheduler, 'scheduleGoalAdvance').mockResolvedValue();+ vi.spyOn(AiAgentService.prototype, 'execAgent').mockImplementation(async (params) => {+ const operationId = `op-task-model-${++seq}`;+ const topicId = params.appContext!.topicId!;+ await new AgentOperationModel(db, userId).recordStart({+ agentId: params.agentId,+ appContext: { sourceMessageId: params.clientIds?.userMessageId },+ operationId,+ topicId,+ });+ return {+ agentId: params.agentId!,+ assistantMessageId: 'm',+ autoStarted: true,+ createdAt: new Date().toISOString(),+ message: 'started',+ operationId,+ status: 'running',+ success: true,+ timestamp: new Date().toISOString(),+ topicId,+ userMessageId: 'u',+ };+ });+});++afterEach(async () => {+ vi.restoreAllMocks();+ for (const table of [+ goalNodeDecisions,+ goalEdges,+ goalEvents,+ goalNodes,+ goals,+ agentOperations,+ messages,+ taskTopics,+ topics,+ tasks,+ agents,+ users,+ ])+ await db.delete(table);+});++const taskModelOf = async (taskId: string) => {+ const task = await new TaskModel(db, userId).findById(taskId);+ const config = (task?.config ?? {}) as { model?: string; provider?: string };+ return { assignee: task?.assigneeAgentId, model: config.model, provider: config.provider };+};++/** A goal whose first Task the coordinator has created. */+const goalWithTask = async () => {+ const graph = await service().create({ agentId, tasks: ['Only task'], title: 'Task model' });+ const created = await service().tick(graph.goal.id);+ return { goalId: graph.goal.id, taskId: created.taskId! };+};++describe('goal task model override', () => {+ it('pins the next coordinator-created Task to the override', async () => {+ const graph = await service().create({ agentId, tasks: ['Only task'], title: 'Pinned' });+ await service().setTaskModel(graph.goal.id, { model: 'gemini-3.8-flash', provider: 'google' });++ const created = await service().tick(graph.goal.id);++ expect(await taskModelOf(created.taskId!)).toMatchObject({+ model: 'gemini-3.8-flash',+ provider: 'google',+ });+ });++ it("switches unfinished Tasks, and back to the executor's own model on clear", async () => {+ const { goalId, taskId } = await goalWithTask();+ expect(await taskModelOf(taskId)).toMatchObject({ model: 'gpt-4o-mini', provider: 'openai' });++ const picked = await service().setTaskModel(goalId, {+ model: 'gemini-3.8-flash',+ provider: 'google',+ });+ expect(picked.config).toMatchObject({ taskModel: 'gemini-3.8-flash', taskProvider: 'google' });+ expect(await taskModelOf(taskId)).toMatchObject({ model: 'gemini-3.8-flash' });++ const cleared = await service().setTaskModel(goalId, null);+ expect(cleared.config).not.toHaveProperty('taskModel');+ expect(await taskModelOf(taskId)).toMatchObject({ model: 'gpt-4o-mini', provider: 'openai' });+ });++ it("drops the override on an executor change and moves Tasks to the new executor's model", async () => {+ const { goalId, taskId } = await goalWithTask();+ await service().setTaskModel(goalId, { model: 'gemini-3.8-flash', provider: 'google' });++ const handed = await service().setTaskAgent(goalId, otherAgentId);++ expect(handed.goal.config).not.toHaveProperty('taskModel');+ expect(await taskModelOf(taskId)).toEqual({+ assignee: otherAgentId,+ model: 'deepseek-chat',+ provider: 'deepseek',+ });+ });++ it('keeps the Task model when the goal agent changes under a dedicated executor', async () => {+ const graph = await service().create({ agentId, title: 'Dedicated' });+ await service().setTaskAgent(graph.goal.id, otherAgentId);+ await service().setTaskModel(graph.goal.id, { model: 'gemini-3.8-flash', provider: 'google' });++ // The executor stays the dedicated one, so its Task model is still valid.+ const handed = await service().setAgent(graph.goal.id, otherAgentId);++ expect(handed.goal.config).toMatchObject({ taskModel: 'gemini-3.8-flash' });+ });++ it("moves restarted Tasks to the new agent's model when restart hands the goal over", async () => {+ const { goalId, taskId } = await goalWithTask();+ await service().setTaskModel(goalId, { model: 'gemini-3.8-flash', provider: 'google' });++ const restarted = await service().restart(goalId, { agentId: otherAgentId });++ expect(restarted.goal.config).not.toHaveProperty('taskModel');+ expect(await taskModelOf(taskId)).toEqual({+ assignee: otherAgentId,+ model: 'deepseek-chat',+ provider: 'deepseek',+ });+ });++ it('drops pinned Task models for an executor that inherits defaults', async () => {+ const plainAgentId = 'goal-task-model-plain';+ await db.insert(agents).values({ id: plainAgentId, slug: 'task-model-plain', userId });+ const { goalId, taskId } = await goalWithTask();++ // Handed to an executor without a model of its own: nothing to pin.+ await service().setTaskAgent(goalId, plainAgentId);+ expect(await taskModelOf(taskId)).toEqual({+ assignee: plainAgentId,+ model: undefined,+ provider: undefined,+ });++ await service().setTaskModel(goalId, { model: 'gemini-3.8-flash', provider: 'google' });+ expect(await taskModelOf(taskId)).toMatchObject({ model: 'gemini-3.8-flash' });++ // Clearing the goal's pick returns the Task to the executor's default.+ await service().setTaskModel(goalId, null);+ expect(await taskModelOf(taskId)).toMatchObject({ model: undefined, provider: undefined });+ });++ it('leaves finished Tasks on the model they ran with', async () => {+ const { goalId, taskId } = await goalWithTask();+ await new TaskModel(db, userId).updateStatus(taskId, 'completed');++ await service().setTaskModel(goalId, { model: 'gemini-3.8-flash', provider: 'google' });++ expect(await taskModelOf(taskId)).toMatchObject({ model: 'gpt-4o-mini', provider: 'openai' });+ });++ it('re-pins a just-bound Task when the Task model changed while it was created', async () => {+ const { goalId, taskId } = await goalWithTask();+ const assignment = new GoalAssignmentService(db, userId);+ // A Task-model change that committed while this Task was being created,+ // and whose propagation read the graph before the Task was bound.+ await db+ .update(goals)+ .set({+ config: sql`${goals.config} || '{"taskModel":"gemini-3.8-flash","taskProvider":"google"}'::jsonb`,+ })+ .where(eq(goals.id, goalId));++ await assignment.syncBoundTask(goalId, taskId);+ expect(await taskModelOf(taskId)).toMatchObject({ model: 'gemini-3.8-flash' });++ // And the reverse: created on an override that was cleared meanwhile.+ await db+ .update(goals)+ .set({ config: sql`${goals.config} - 'taskModel' - 'taskProvider'` })+ .where(eq(goals.id, goalId));+ await assignment.syncBoundTask(goalId, taskId);+ expect(await taskModelOf(taskId)).toMatchObject({ model: 'gpt-4o-mini', provider: 'openai' });+ });++ it('moves a just-bound Task to the executor a handoff named while it was created', async () => {+ const { goalId, taskId } = await goalWithTask();+ // An executor handoff that committed before this Task was bound.+ await db+ .update(goals)+ .set({+ config: sql`${goals.config} || ${JSON.stringify({ taskAgentId: otherAgentId })}::jsonb`,+ })+ .where(eq(goals.id, goalId));++ await new GoalAssignmentService(db, userId).syncBoundTask(goalId, taskId);++ // Assignee and model move together — never the old executor on the new model.+ expect(await taskModelOf(taskId)).toEqual({+ assignee: otherAgentId,+ model: 'deepseek-chat',+ provider: 'deepseek',+ });+ });++ it('re-pins a Task already on the new executor to that executor’s model', async () => {+ const { goalId, taskId } = await goalWithTask();+ // Individually moved to the other agent earlier, still pinned to a model it chose.+ const taskModel = new TaskModel(db, userId);+ await taskModel.update(taskId, { assigneeAgentId: otherAgentId });+ await taskModel.updateTaskConfig(taskId, { model: 'gemini-3.8-flash', provider: 'google' });++ await service().setTaskAgent(goalId, otherAgentId);++ expect(await taskModelOf(taskId)).toEqual({+ assignee: otherAgentId,+ model: 'deepseek-chat',+ provider: 'deepseek',+ });+ });++ it("drops a deleted executor's Task model when new Tasks fall back to the goal agent", async () => {+ const graph = await service().create({+ agentId,+ config: { taskAgentId: otherAgentId },+ tasks: ['Only task'],+ title: 'Deleted executor',+ });+ await service().setTaskModel(graph.goal.id, { model: 'gemini-3.8-flash', provider: 'google' });+ await db.delete(agents).where(eq(agents.id, otherAgentId));++ const created = await service().tick(graph.goal.id);++ // The goal agent takes over on its own model, not the gone executor's pick.+ expect(await taskModelOf(created.taskId!)).toEqual({+ assignee: agentId,+ model: 'gpt-4o-mini',+ provider: 'openai',+ });+ });+});diff --git a/apps/server/src/services/goal/assignment.ts b/apps/server/src/services/goal/assignment.tsnew file mode 100644index 00000000000..86c907ee1c0--- /dev/null+++ b/apps/server/src/services/goal/assignment.ts@@ -0,0 +1,536 @@+import type { GoalItem, TaskItem } from '@lobechat/types';+import { resolveAgentModelSelectionPolicy } from '@lobechat/types';+import { TRPCError } from '@trpc/server';+import { and, eq, inArray, notInArray, sql } from 'drizzle-orm';++import { AgentModel } from '@/database/models/agent';+import { GoalModel } from '@/database/models/goal';+import { GoalGraphModel } from '@/database/models/goalGraph';+import { TaskModel } from '@/database/models/task';+import { agents, tasks } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';+import { assertAgentUsableBy } from '@/database/utils/agent-access';++import { isResourceAuthorOrAdmin } from '../resourcePermission';+import { resolveMissingTaskModelConfig } from '../task/modelSnapshot';+import { goalTaskAgentId } from './GoalService/utils';+import { GoalManagerService } from './manager';+import { assertGoalModelRunnable, goalTaskModelOverride } from './modelConfig';++const goalNotFound = () => new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });++type ModelConfig = { model: string; provider: string };+type ModelSlot = 'planning' | 'task';++/**+ * The model overrides a handoff leaves stale: the planning model belongs to+ * the goal agent, the Task model to whoever actually does the Tasks — which,+ * without a dedicated executor, is the goal agent too.+ */+export const staleModelSlots = (+ previous: Pick<GoalItem, 'agentId' | 'config'>,+ next: Pick<GoalItem, 'agentId' | 'config'>,+): ModelSlot[] => [+ ...(previous.agentId === next.agentId ? [] : (['planning'] as const)),+ ...(goalTaskAgentId(previous) === goalTaskAgentId(next) ? [] : (['task'] as const)),+];++/**+ * A Task config's model keys set to `model`, or removed with `undefined` so the+ * Task inherits its executor's default — a single atomic JSONB write.+ */+const taskModelPatch = (model?: Partial<ModelConfig>) =>+ model+ ? sql`COALESCE(${tasks.config}, '{}'::jsonb) || ${JSON.stringify(model)}::jsonb`+ : sql`COALESCE(${tasks.config}, '{}'::jsonb) - 'model' - 'provider'`;++/**+ * The goal's Task model, unless it belonged to a dedicated executor that is+ * gone: a handoff clears the override with the executor, and a deleted executor+ * (Tasks fall back to the goal agent) is the same change made implicitly.+ */+const liveTaskModelOverride = (goal: GoalItem, executor: string | undefined) => {+ const dedicated = goal.config?.taskAgentId;+ return dedicated && executor !== dedicated ? {} : goalTaskModelOverride(goal.config);+};++/** Whether a Task config already carries exactly `model` (or none, for `undefined`). */+const pinsModel = (config: unknown, model?: Partial<ModelConfig>) => {+ const current = (config ?? {}) as { model?: unknown; provider?: unknown };+ return current.model === model?.model && current.provider === model?.provider;+};++/**+ * Who works on a goal and with which model: the goal agent that supervises and+ * plans, the executor its Tasks go to, and the model planning turns run on.+ */+export class GoalAssignmentService {+ private agentModel: AgentModel;+ private goalModel: GoalModel;+ private graphModel: GoalGraphModel;+ private taskModel: TaskModel;++ constructor(+ private db: LobeChatDatabase,+ private userId: string,+ private workspaceId?: string,+ ) {+ this.agentModel = new AgentModel(db, userId, workspaceId);+ this.goalModel = new GoalModel(db, userId, workspaceId);+ this.graphModel = new GoalGraphModel(db, userId, workspaceId);+ this.taskModel = new TaskModel(db, userId, workspaceId);+ }++ private assertUsable = (agentId: string) =>+ assertAgentUsableBy(this.db, agentId, { userId: this.userId, workspaceId: this.workspaceId });++ /**+ * The caller must be allowed to pick the agent, and the goal's owner must be+ * able to run it: background advances act as the owner, so a private Agent of+ * an admin acting on someone else's goal would be unreachable to every later+ * planning turn, or silently skipped as a missing executor.+ */+ assertUsableForGoal = async (goal: Pick<GoalItem, 'userId'> | string, agentId: string) => {+ await this.assertUsable(agentId);+ const ownerId =+ typeof goal === 'string' ? (await this.goalModel.findById(goal))?.userId : goal.userId;+ if (!ownerId) throw goalNotFound();+ if (ownerId === this.userId) return;+ await assertAgentUsableBy(this.db, agentId, {+ userId: ownerId,+ workspaceId: this.workspaceId,+ }).catch(() => {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: "The goal's owner cannot use this Agent; pick one they have access to",+ });+ });+ };++ /**+ * 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`.+ *+ * 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,+ agentId: string,+ options?: { goalOnly?: boolean },+ ): Promise<{ goal: GoalItem; reassignedTaskIds: string[] }> => {+ await this.assertUsableForGoal(goalId, agentId);+ // With a dedicated executor the Tasks stay where they are; otherwise the+ // goal agent does them, so the unfinished ones follow it.+ const { goal, movedTaskIds: reassignedTaskIds } = await this.handOver(+ goalId,+ (model) => model.update(goalId, { agentId }),+ async (scoped, handed) =>+ options?.goalOnly || handed.config?.taskAgentId+ ? []+ : scoped.reassignUnfinishedTasks(goalId, agentId),+ );++ // 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);++ return {+ goal: migrated ? ((await this.goalModel.findById(goalId)) ?? goal) : goal,+ reassignedTaskIds,+ };+ };++ /**+ * Pick the model the goal agent plans with, or fall back to that agent's own+ * model with `null`. Only planning turns read it — Tasks keep their own model+ * — and a turn already running keeps the model it started on.+ */+ setModel = async (goalId: string, modelConfig: ModelConfig | null): Promise<GoalItem> =>+ this.writeModelOverride(goalId, modelConfig, 'planning');++ /**+ * Pick the model the goal's Tasks run on, or fall back to their executor's own+ * model with `null`. Tasks the coordinator creates from here on are pinned to+ * it, and unfinished ones switch with it; a run already going keeps its model.+ */+ setTaskModel = async (goalId: string, modelConfig: ModelConfig | null): Promise<GoalItem> =>+ // The goal and its unfinished Tasks switch in one commit under the goal+ // lock, so an executor handoff cannot interleave and leave either stale.+ this.writeModelOverride(goalId, modelConfig, 'task', async (scoped, goal) => {+ const executor = await scoped.resolveTaskAssignee(goal);+ // Without a model to pin (an executor that inherits defaults), the Tasks+ // drop theirs, as a Task newly created for that executor would have none.+ const next =+ modelConfig ?? (executor ? await scoped.agentModelOf(executor, goal) : undefined);+ await scoped.pinUnfinishedTaskModels(goal.id, next);+ });++ /**+ * Check the slot's agent and write its override under the goal row lock, so+ * an agent handoff racing this write cannot slip in between: the check always+ * sees the agent the override will actually apply to.+ */+ private writeModelOverride = async (+ goalId: string,+ modelConfig: ModelConfig | null,+ slot: 'planning' | 'task',+ /** Runs in the same transaction after the write, still under the lock. */+ after?: (scoped: GoalAssignmentService, goal: GoalItem) => Promise<void>,+ ): Promise<GoalItem> => {+ if (modelConfig) {+ // The owner never changes, so the availability check needs no lock.+ const owner = await new GoalModel(this.db, this.userId, this.workspaceId).findById(goalId);+ if (!owner) throw goalNotFound();+ await assertGoalModelRunnable(this.db, owner, slot, modelConfig);+ }+ return this.db.transaction(async (tx) => {+ const model = new GoalModel(tx, this.userId, this.workspaceId);+ const current = await model.lockById(goalId);+ if (!current) throw goalNotFound();+ // Reads inside the transaction go through it, not around it.+ const scoped = new GoalAssignmentService(tx, this.userId, this.workspaceId);+ if (modelConfig) {+ const agentId =+ slot === 'task' ? await scoped.resolveTaskAssignee(current) : current.agentId;+ if (agentId) await scoped.assertModelSelectable(agentId);+ }+ const goal = await model.updateModelConfig(goalId, modelConfig, slot);+ if (!goal) throw goalNotFound();+ await after?.(scoped, goal);+ return goal;+ });+ };++ /**+ * Pin every unfinished Task of the goal to `model`, or drop their pinned model+ * with `undefined` — one set-based write however many Tasks the goal has.+ */+ private pinUnfinishedTaskModels = async (goalId: string, model?: Partial<ModelConfig>) => {+ const { tasks: unfinished } = await this.unfinishedTasks(goalId);+ if (unfinished.length === 0) return;+ await this.db+ .update(tasks)+ .set({ config: taskModelPatch(model), updatedAt: new Date() })+ .where(+ and(+ // Ids were read through the goal owner's scope.+ inArray(+ tasks.id,+ unfinished.map((task) => task.id),+ ),+ notInArray(tasks.status, ['completed', 'canceled']),+ ),+ );+ };++ /**+ * A model override was picked against the previous agent — its provider, or a+ * runtime that agent does not share — so a new agent starts from its own.+ */+ dropModelOverride = async (goal: GoalItem, slots: ('planning' | 'task')[]) => {+ let current = goal;+ for (const slot of slots) {+ const [model, provider] =+ slot === 'task'+ ? [current.config?.taskModel, current.config?.taskProvider]+ : [current.config?.model, current.config?.provider];+ if (model || provider)+ current = (await this.goalModel.updateModelConfig(goal.id, null, slot)) ?? current;+ }+ return current;+ };++ /**+ * A goal override is an explicit per-run model, which outranks an Agent's+ * policy at run time. So when the author pinned the model of a public+ * Workspace Agent (`fixed`), only they or a Workspace admin may override it+ * here — the same people who could change it on the Agent itself.+ */+ private assertModelSelectable = async (agentId: string) => {+ const agent = await this.db.query.agents.findFirst({+ columns: { agencyConfig: true, userId: true, visibility: true, workspaceId: true },+ where: eq(agents.id, agentId),+ });+ if (!agent || agent.userId === this.userId) return;+ const workspaceId = agent.workspaceId ?? undefined;+ const visibility = (agent.visibility as 'private' | 'public' | null) ?? 'public';+ const policy = resolveAgentModelSelectionPolicy({+ agencyConfig: agent.agencyConfig ?? undefined,+ visibility,+ workspaceId,+ });+ if (policy !== 'fixed' || !workspaceId || visibility === 'private') return;+ const canManage = await isResourceAuthorOrAdmin({+ db: this.db,+ meta: { userId: agent.userId, visibility, workspaceId },+ resourceType: 'agent',+ userId: this.userId,+ workspaceId,+ });+ if (!canManage)+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: "This Agent's author fixed its model; only they or an admin can override it",+ });+ };++ /**+ * Point the goal at a new agent and drop the overrides that belonged to the+ * previous one in the same commit, so a coordinator tick can never dispatch+ * the new agent on the previous agent's model in between.+ */+ handOver = (+ goalId: string,+ write: (model: GoalModel, current: GoalItem) => Promise<GoalItem | undefined>,+ /**+ * Moves the goal's Tasks along with the handoff, under the same lock, so a+ * Task-model write or a coordinator claim cannot land between the handoff+ * and the move. Returns the ids of the Tasks it moved.+ */+ moveTasks?: (+ scoped: GoalAssignmentService,+ goal: GoalItem,+ previous: GoalItem,+ ) => Promise<string[]>,+ ): Promise<{ goal: GoalItem; movedTaskIds: string[]; previous: GoalItem }> =>+ this.db.transaction(async (tx) => {+ const model = new GoalModel(tx, this.userId, this.workspaceId);+ const previous = await model.lockById(goalId);+ if (!previous) throw goalNotFound();+ const updated = await write(model, previous);+ if (!updated) throw goalNotFound();+ const scoped = new GoalAssignmentService(tx, this.userId, this.workspaceId);+ const goal = await scoped.dropModelOverride(updated, staleModelSlots(previous, updated));+ const movedTaskIds = (await moveTasks?.(scoped, goal, previous)) ?? [];+ return { goal, movedTaskIds, previous };+ });++ /**+ * Move one Task to an executor and/or model in a single commit: a Task+ * claimed between the two writes would otherwise run the new executor on the+ * previous one's pinned model. `model: undefined` removes the Task's pinned+ * model so it inherits its executor's default.+ */+ private retargetTask = (+ owner: Pick<GoalItem, 'userId'>,+ taskId: string,+ change: { agentId?: string; model: Partial<ModelConfig> | undefined },+ ) =>+ this.db.transaction(async (tx) => {+ const taskModel = new TaskModel(tx, owner.userId, this.workspaceId);+ if (change.agentId) await taskModel.update(taskId, { assigneeAgentId: change.agentId });+ if (change.model) {+ await taskModel.updateTaskConfig(taskId, change.model);+ return;+ }+ // The id was read through the owner's scope.+ await tx+ .update(tasks)+ .set({ config: taskModelPatch(undefined), updatedAt: new Date() })+ .where(eq(tasks.id, taskId));+ });++ /**+ * The model a Task assigned to this agent would be created with — read as the+ * goal's owner, who creates its Tasks and may run them on a private Agent.+ */+ private agentModelOf = async (+ agentId: string,+ owner: Pick<GoalItem, 'userId'>,+ ): Promise<Partial<ModelConfig> | undefined> => {+ const info = await this.agentModelFor(owner).getAgentSnapshotForTaskCreate(agentId);+ return info?.snapshot+ ? resolveMissingTaskModelConfig({}, info.snapshot, info.modelOverrideProvider)+ : undefined;+ };++ /**+ * After the goal agent changed: when that agent also does the goal's Tasks,+ * unfinished ones follow it unless the caller keeps them (`goalOnly`). A goal+ * with a dedicated executor keeps its Tasks there.+ */+ followGoalAgent = async (+ goal: Pick<GoalItem, 'config' | 'id'>,+ agentId: string,+ goalOnly?: boolean,+ ) => (goalOnly || goal.config?.taskAgentId ? [] : this.reassignUnfinishedTasks(goal.id, agentId));++ /**+ * 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 this.assertUsableForGoal(goalId, agentId);+ const { goal, movedTaskIds } = await this.handOver(+ goalId,+ (model, current) =>+ // Naming the goal agent itself is the same as clearing: one agent, one slot.+ model.updateTaskAgentId(goalId, agentId && agentId !== current.agentId ? agentId : null),+ async (scoped, handed) => {+ const assignee = goalTaskAgentId(handed);+ return options?.goalOnly || !assignee+ ? []+ : scoped.reassignUnfinishedTasks(goalId, assignee);+ },+ );+ return { goal, reassignedTaskIds: movedTaskIds };+ };++ /**+ * 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.+ */+ resolveTaskAssignee = async (goal: GoalItem) => {+ const taskAgentId = goal.config?.taskAgentId;+ // As the goal's owner: an admin acting on a member's goal cannot see the+ // member's private executor, which is still very much there.+ if (taskAgentId && !(await this.agentModelFor(goal).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.+ */+ reassignUnfinishedTasks = async (goalId: string, agentId: string) => {+ const { goal: owner, tasks: unfinished } = await this.unfinishedTasks(goalId);+ const model = await this.expectedTaskModel(owner, agentId);+ const reassigned: string[] = [];+ for (const task of unfinished) {+ const moved = task.assigneeAgentId !== agentId;+ // A Task already on this executor may still carry a model pinned for+ // another one; it is re-pinned even though it does not move.+ if (!moved && pinsModel(task.config, model)) continue;+ await this.retargetTask(owner, task.id, { agentId: moved ? agentId : undefined, model });+ if (moved) reassigned.push(task.id);+ }+ return reassigned;+ };++ /**+ * The model a goal's Task for `executor` should be pinned to: the goal's own+ * Task model when it has one, else the model a Task created for that+ * executor would carry (the previous executor's snapshot may name another+ * runtime entirely).+ */+ private expectedTaskModel = async (+ goal: GoalItem,+ executor: string | undefined,+ ): Promise<Partial<ModelConfig> | undefined> => {+ const override = liveTaskModelOverride(goal, executor);+ if (override.model) return override;+ return executor ? this.agentModelOf(executor, goal) : undefined;+ };++ /**+ * The executor a new Task goes to and the model it is pinned to, resolved+ * together: when the dedicated executor was deleted and Tasks fall back to+ * the goal agent, the deleted executor's Task model goes with it.+ */+ newTaskAssignment = async (goal: GoalItem) => {+ const assigneeAgentId = await this.resolveTaskAssignee(goal);+ return { assigneeAgentId, model: liveTaskModelOverride(goal, assigneeAgentId) };+ };++ /**+ * Restart `candidates` onto `agentId` inside a handoff transaction: each is+ * reset to `backlog` by compare-and-swap (a Task a tick claims meanwhile is+ * skipped, not yanked out of its run) and reassigned in the same commit as+ * the handoff — re-pinned to the new executor's model when the executor+ * changed, so no tick can dispatch it on the previous executor's model.+ */+ restartTasks = async (+ goal: GoalItem,+ candidates: Pick<TaskItem, 'id' | 'status'>[],+ agentId: string,+ executorChanged: boolean,+ ): Promise<string[]> => {+ const taskModel = this.taskModelFor(goal);+ const model = executorChanged ? await this.agentModelOf(agentId, goal) : undefined;+ const restarted: string[] = [];+ for (const task of candidates) {+ const reset = await taskModel.updateStatusIfCurrent(task.id, task.status, 'backlog', {+ error: null,+ });+ if (!reset) continue;+ if (executorChanged) await this.retargetTask(goal, task.id, { agentId, model });+ else await taskModel.update(task.id, { assigneeAgentId: agentId });+ restarted.push(task.id);+ }+ return restarted;+ };++ /**+ * Align a Task the coordinator just bound with the goal as it is now: an+ * executor handoff or Task-model change that committed while the Task was+ * being created scanned the graph before the bind and missed it. Both the+ * assignee and the model are aligned — fixing only one would pair an+ * executor with another's model. Taking the goal lock orders this after any+ * such change (or that change after the bind, so it sees the Task itself).+ */+ syncBoundTask = (goalId: string, taskId: string) =>+ this.db.transaction(async (tx) => {+ const current = await new GoalModel(tx, this.userId, this.workspaceId).lockById(goalId);+ if (!current) return;+ const scoped = new GoalAssignmentService(tx, this.userId, this.workspaceId);+ const task = await scoped.taskModelFor(current).findById(taskId);+ if (!task) return;+ const executor = await scoped.resolveTaskAssignee(current);+ const model = await scoped.expectedTaskModel(current, executor);+ const moved = !!executor && task.assigneeAgentId !== executor;+ if (!moved && pinsModel(task.config, model)) return;+ await scoped.retargetTask(current, taskId, {+ agentId: moved ? executor : undefined,+ model,+ });+ });++ /**+ * Tasks belong to the goal's owner, so a Workspace admin acting on someone+ * else's goal reads and writes them under the owner — the caller's own scope+ * would miss the owner's private Tasks.+ */+ private agentModelFor = (goal: Pick<GoalItem, 'userId'>) =>+ goal.userId === this.userId+ ? this.agentModel+ : new AgentModel(this.db, goal.userId, this.workspaceId);++ private taskModelFor = (goal: Pick<GoalItem, 'userId'>) =>+ goal.userId === this.userId+ ? this.taskModel+ : new TaskModel(this.db, goal.userId, this.workspaceId);++ private unfinishedTasks = async (goalId: string) => {+ const graph = await this.graphModel.getGraph(goalId);+ if (!graph) throw goalNotFound();+ const taskModel = this.taskModelFor(graph.goal);+ const taskIds = graph.nodes.flatMap((node) => (node.taskId ? [node.taskId] : []));+ const unfinished = (await taskModel.findByIds(taskIds)).filter(+ (task) => task.status !== 'completed' && task.status !== 'canceled',+ );+ return { goal: graph.goal, tasks: unfinished };+ };+}diff --git a/apps/server/src/services/goal/bindTopic.test.ts b/apps/server/src/services/goal/bindTopic.test.tsindex 6f7a4b911ed..4f5e69295ab 100644--- a/apps/server/src/services/goal/bindTopic.test.ts+++ b/apps/server/src/services/goal/bindTopic.test.ts@@ -206,6 +206,19 @@ describe('GoalService.bindTopic', () => {expect(event.reason).toContain(boundTopicId);});+ it("drops the previous agent's model overrides when binding moves the goal to another agent", async () => {+ const { id } = await standaloneGoalMidRun(otherAgentId);+ await service().setModel(id, { model: 'gemini-3.8-flash', provider: 'google' });+ await service().setTaskModel(id, { model: 'gpt-5.6-luna', provider: 'openai' });++ await service().bindTopic(id, runOpId);++ const goal = (await model().findById(id))!;+ expect(goal.agentId).toBe(agentId);+ expect(goal.config).not.toHaveProperty('model');+ expect(goal.config).not.toHaveProperty('taskModel');+ });+it('dispatches the next planning turn into the bound topic', async () => {const { id } = await standaloneGoalMidRun();await service().bindTopic(id, runOpId);diff --git a/apps/server/src/services/goal/criteriaGenerator.test.ts b/apps/server/src/services/goal/criteriaGenerator.test.tsindex cd44f6dc6f8..f68fc84ba27 100644--- a/apps/server/src/services/goal/criteriaGenerator.test.ts+++ b/apps/server/src/services/goal/criteriaGenerator.test.ts@@ -121,4 +121,15 @@ describe('GoalCriteriaGeneratorService', () => {title: 'Publish benchmark paper',});});++ it("plans a goal's decomposition on the goal's own planning model", async () => {+ const goalConfig = { model: 'gemini-3.8-flash', provider: 'google' };+ generateObject.mockResolvedValueOnce({ problemStatement: 'p', tasks: [] });++ await new GoalCriteriaGeneratorService({} as never, 'user-1')+ .decompose({ goalConfig, requirement: 'Upgrade office editing' })+ .catch(() => undefined);++ expect(resolveGoalModelConfig).toHaveBeenCalledWith({}, 'user-1', goalConfig);+ });});diff --git a/apps/server/src/services/goal/criteriaGenerator.ts b/apps/server/src/services/goal/criteriaGenerator.tsindex b0fbddada65..8edc7af1b10 100644--- a/apps/server/src/services/goal/criteriaGenerator.ts+++ b/apps/server/src/services/goal/criteriaGenerator.ts@@ -15,7 +15,7 @@ import {VERIFY_ON_FAIL_ACTIONS,VERIFY_VERIFIER_TYPES,} from '@lobechat/prompts';-import type { RequiredEvidenceSpec, VerifyCheckItem } from '@lobechat/types';+import type { GoalConfig, RequiredEvidenceSpec, VerifyCheckItem } from '@lobechat/types';import { RequestTrigger } from '@lobechat/types';import debug from 'debug';import { z } from 'zod';@@ -192,11 +192,16 @@ export class GoalCriteriaGeneratorService {* schema failure; the coordinator then falls back to a single task seeded* from the raw requirement and records why, instead of stalling the goal.*/- async decompose(params: {+ async decompose({+ goalConfig,+ ...params+ }: {clarifications?: GoalClarificationAnswer[];+ /** Carries the goal's planning-model pick, which outranks the system goal model. */+ goalConfig?: GoalConfig | null;requirement: string;}): Promise<GoalDecompositionDraft> {- const modelConfig = await resolveGoalModelConfig(this.db, this.userId);+ const modelConfig = await resolveGoalModelConfig(this.db, this.userId, goalConfig);const ai = new AiGenerationService(this.db, this.userId, this.workspaceId);const raw = await ai.generateObject({diff --git a/apps/server/src/services/goal/explorationPlanner.ts b/apps/server/src/services/goal/explorationPlanner.tsindex 11c7f35ca49..a315129422a 100644--- a/apps/server/src/services/goal/explorationPlanner.ts+++ b/apps/server/src/services/goal/explorationPlanner.ts@@ -5,7 +5,7 @@ import {GOAL_EXPLORE_JSON_SCHEMA,GOAL_EXPLORE_PROMPT_VERSION,} from '@lobechat/prompts';-import { RequestTrigger } from '@lobechat/types';+import { type GoalConfig, RequestTrigger } from '@lobechat/types';import { z } from 'zod';import type { LobeChatDatabase } from '@/database/type';@@ -50,8 +50,11 @@ export class GoalExplorationPlanner {private readonly workspaceId?: string,) {}- async plan(input: GoalExploreInput): Promise<GoalExplorationPlan> {- const model = await resolveGoalModelConfig(this.db, this.userId);+ async plan(+ input: GoalExploreInput,+ goalConfig?: GoalConfig | null,+ ): Promise<GoalExplorationPlan> {+ const model = await resolveGoalModelConfig(this.db, this.userId, goalConfig);const result = await new AiGenerationService(this.db,this.userId,diff --git a/apps/server/src/services/goal/exploreGraph.ts b/apps/server/src/services/goal/exploreGraph.tsindex 1db119abdd3..f6999bdf4f1 100644--- a/apps/server/src/services/goal/exploreGraph.ts+++ b/apps/server/src/services/goal/exploreGraph.ts@@ -45,45 +45,48 @@ export async function exploreGraph(params: {message: 'Graph changed or another advance is already exploring',};try {- const decision = await new GoalExplorationPlanner(db, userId, workspaceId).plan({- requirement: graph.goal.requirement ?? graph.goal.title,- instruction: policy.instruction,- maxExperiments: policy.maxExperiments,- experiments: graph.nodes- .filter(- (node) =>- node.kind === 'experiment' ||- (node.kind === 'task' &&- node.title !== GOAL_ACCEPTANCE_TASK_TITLE &&- !experimentOwner(graph, node.id) &&- !isProtocolRevision(graph, node.id)),- )- .map((node) => ({- id: node.id,- title: node.title,- status: node.status,- results: experimentResults(graph, node.id),- // Tells the planner which experiments a previous turn authored, so it can- // judge whether its own last move helped before repeating that direction.- derivedFromId: graph.edges.find(- (edge) => edge.sourceNodeId === node.id && edge.kind === 'derived_from',- )?.targetNodeId,- // An uncontained seed cannot hold a correction, so it reports none left- // rather than inviting a choice the apply step would refuse.- revisionsRemaining:- node.kind === 'experiment' || experimentOwner(graph, node.id)- ? Math.max(MAX_PROTOCOL_REVISIONS - protocolRevisionCount(graph, node.id), 0)- : 0,- inputVersionIds: graph.workVersions- .filter(- (version) =>- experimentScope(graph, node.id).has(version.nodeId) &&- version.relation === 'produced' &&- version.work,- )- .map((version) => version.workVersionId),- })),- });+ const decision = await new GoalExplorationPlanner(db, userId, workspaceId).plan(+ {+ requirement: graph.goal.requirement ?? graph.goal.title,+ instruction: policy.instruction,+ maxExperiments: policy.maxExperiments,+ experiments: graph.nodes+ .filter(+ (node) =>+ node.kind === 'experiment' ||+ (node.kind === 'task' &&+ node.title !== GOAL_ACCEPTANCE_TASK_TITLE &&+ !experimentOwner(graph, node.id) &&+ !isProtocolRevision(graph, node.id)),+ )+ .map((node) => ({+ id: node.id,+ title: node.title,+ status: node.status,+ results: experimentResults(graph, node.id),+ // Tells the planner which experiments a previous turn authored, so it can+ // judge whether its own last move helped before repeating that direction.+ derivedFromId: graph.edges.find(+ (edge) => edge.sourceNodeId === node.id && edge.kind === 'derived_from',+ )?.targetNodeId,+ // An uncontained seed cannot hold a correction, so it reports none left+ // rather than inviting a choice the apply step would refuse.+ revisionsRemaining:+ node.kind === 'experiment' || experimentOwner(graph, node.id)+ ? Math.max(MAX_PROTOCOL_REVISIONS - protocolRevisionCount(graph, node.id), 0)+ : 0,+ inputVersionIds: graph.workVersions+ .filter(+ (version) =>+ experimentScope(graph, node.id).has(version.nodeId) &&+ version.relation === 'produced' &&+ version.work,+ )+ .map((version) => version.workVersionId),+ })),+ },+ graph.goal.config,+ );const result = await model.apply(goalId, claim.token, decision);if (result.outcome === 'stale')return {diff --git a/apps/server/src/services/goal/manager/index.ts b/apps/server/src/services/goal/manager/index.tsindex 0fe3abef259..1bb1b884081 100644--- a/apps/server/src/services/goal/manager/index.ts+++ b/apps/server/src/services/goal/manager/index.ts@@ -24,6 +24,7 @@ import { readDeviceDispatchRoute } from '@/server/services/aiAgent/helpers/heterimport { TopicStartReservationError } from '@/server/services/aiAgent/topicStartReservation';import { deviceGateway } from '@/server/services/deviceGateway';+import { goalModelOverride } from '../modelConfig';import { countUnchargedRuns, DEFAULT_MANAGER_MAX_TURNS } from '../recoveryPolicy';import { scheduleGoalAdvance } from '../scheduler';import { recoveryEligibility } from '../supervisor/policy';@@ -592,6 +593,8 @@ export class GoalManagerService {});return {...next,+ // Read under the lock, so a model picked just before this turn applies to it.+ modelOverride: goalModelOverride(fresh.config),earlierFeedback: listed.filter((n) => !isNew(n)).map(note),newFeedback: listed.filter(isNew).map(note),omittedFeedback: {@@ -614,6 +617,7 @@ export class GoalManagerService {clientIds: { userMessageId: `msg_goal_manager_${claimed.token}` },autoStart: true,maxSteps: 80,+ ...claimed.modelOverride,userInterventionConfig: { approvalMode: 'headless' },prompt: buildGoalManagerPrompt({goalId: goal.id,diff --git a/apps/server/src/services/goal/modelConfig.test.ts b/apps/server/src/services/goal/modelConfig.test.tsnew file mode 100644index 00000000000..9c0e2a6b586--- /dev/null+++ b/apps/server/src/services/goal/modelConfig.test.ts@@ -0,0 +1,35 @@+// @vitest-environment node+import { describe, expect, it, vi } from 'vitest';++import { resolveGoalModelConfig } from './modelConfig';++const getUserSettings = vi.hoisted(() => vi.fn());++vi.mock('@/database/models/user', () => ({+ UserModel: class {+ getUserSettings = getUserSettings;+ },+}));++describe('resolveGoalModelConfig', () => {+ it("uses the goal's planning model without reading the system setting", async () => {+ await expect(+ resolveGoalModelConfig({} as never, 'user-1', {+ model: 'gemini-3.8-flash',+ provider: 'google',+ }),+ ).resolves.toEqual({ model: 'gemini-3.8-flash', provider: 'google' });+ expect(getUserSettings).not.toHaveBeenCalled();+ });++ it('falls back to the system goal model without a complete goal pick', async () => {+ getUserSettings.mockResolvedValue({+ systemAgent: { goal: { model: 'system-goal', provider: 'system-provider' } },+ });++ const resolved = await resolveGoalModelConfig({} as never, 'user-1', { model: 'gemini-only' });++ expect(getUserSettings).toHaveBeenCalled();+ expect(resolved).toMatchObject({ model: 'system-goal', provider: 'system-provider' });+ });+});diff --git a/apps/server/src/services/goal/modelConfig.ts b/apps/server/src/services/goal/modelConfig.tsindex b0b9f449ce0..993145d1152 100644--- a/apps/server/src/services/goal/modelConfig.ts+++ b/apps/server/src/services/goal/modelConfig.ts@@ -1,10 +1,26 @@-import type { UserSystemAgentConfig } from '@lobechat/types';+import type { GoalConfig, ProviderConfig, UserSystemAgentConfig } from '@lobechat/types';+import { TRPCError } from '@trpc/server';import { UserModel } from '@/database/models/user';+import { AiInfraRepos } from '@/database/repositories/aiInfra';import type { LobeChatDatabase } from '@/database/type';+import { getServerGlobalConfig } from '@/server/globalConfig';+import { resolveProviderRelay } from '@/server/modules/AgentRuntime/llmRelay/resolveLlmExecutionSite';+import { getUserScopedAiProviderRuntimeState } from '@/server/services/aiProviderAccess';import { resolveSystemAgentModelConfig } from '@/server/services/systemAgent/modelConfig';-export const resolveGoalModelConfig = async (db: LobeChatDatabase, userId: string) => {+/**+ * The model the goal's own planning runs on: the goal's planning-model pick+ * when it has one, otherwise the user's system goal model. Callers that plan+ * for no particular goal (or diagnose rather than plan) omit `goalConfig`.+ */+export const resolveGoalModelConfig = async (+ db: LobeChatDatabase,+ userId: string,+ goalConfig?: GoalConfig | null,+) => {+ if (goalConfig?.model && goalConfig.provider)+ return { model: goalConfig.model, provider: goalConfig.provider };const settings = await new UserModel(db, userId).getUserSettings();const systemAgent = settings?.systemAgent as Partial<UserSystemAgentConfig> | undefined;@@ -13,3 +29,61 @@ export const resolveGoalModelConfig = async (db: LobeChatDatabase, userId: strintaskKey: 'goal',});};++/**+ * The goal's own pick for its planning turns, as `execAgent` params. Empty when+ * the goal has none, so the run keeps the goal agent's model.+ */+export const goalModelOverride = (config?: GoalConfig | null) => ({+ ...(config?.model && { model: config.model }),+ ...(config?.provider && { provider: config.provider }),+});++/**+ * The goal's own pick for its Tasks, as Task config. Empty when the goal has+ * none, so a new Task takes its executor's model as usual.+ */+export const goalTaskModelOverride = (config?: GoalConfig | null) => ({+ ...(config?.taskModel && { model: config.taskModel }),+ ...(config?.taskProvider && { provider: config.taskProvider }),+});++/**+ * Refuse a model the goal could not run on. Its planning and Tasks run as the+ * goal's owner, so the pick must be among the models the owner's picker would+ * offer — not merely the caller's, such as a Workspace admin editing a+ * member's goal. Planning also advances in the background with no device+ * attached, so it cannot use a provider only the owner's device reaches.+ */+export const assertGoalModelRunnable = async (+ db: LobeChatDatabase,+ owner: { userId: string; workspaceId?: string | null },+ slot: 'planning' | 'task',+ { model, provider }: { model: string; provider: string },+) => {+ const workspaceId = owner.workspaceId ?? undefined;+ const { aiProvider } = await getServerGlobalConfig();+ const repos = new AiInfraRepos(+ db,+ owner.userId,+ aiProvider as Record<string, ProviderConfig>,+ workspaceId,+ );+ const { enabledAiModels } = await getUserScopedAiProviderRuntimeState(owner.userId, () =>+ repos.getAiProviderRuntimeState(),+ );+ if (!enabledAiModels.some((item) => item.id === model && item.providerId === provider))+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: "This model is not available to the goal's owner",+ });++ if (+ slot === 'planning' &&+ (await resolveProviderRelay({ db, provider, userId: owner.userId, workspaceId }))+ )+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'This provider runs only on a device, which background goal planning cannot reach',+ });+};diff --git a/apps/server/src/services/goal/modelOverride.test.ts b/apps/server/src/services/goal/modelOverride.test.tsnew file mode 100644index 00000000000..42ef946262b--- /dev/null+++ b/apps/server/src/services/goal/modelOverride.test.ts@@ -0,0 +1,155 @@+// @vitest-environment node+import type { GoalConfig } from '@lobechat/types';+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { getTestDB } from '@/database/core/getTestDB';+import { AgentOperationModel } from '@/database/models/agentOperation';+import {+ agentOperations,+ agents,+ goalEdges,+ goalEvents,+ goalNodeDecisions,+ goalNodes,+ goals,+ messages,+ topics,+ users,+} from '@/database/schemas';+import { AiAgentService } from '@/server/services/aiAgent';++import { GoalService } from './index';+import * as modelConfig from './modelConfig';+import * as scheduler from './scheduler';++const db = await getTestDB();+const userId = 'goal-model-override-user';+const agentId = 'goal-model-override-agent';+const otherAgentId = 'goal-model-override-other';+let seq = 0;+const service = () => new GoalService(db, userId);+const execAgent = () => vi.mocked(AiAgentService.prototype.execAgent);++beforeEach(async () => {+ // What this suite pins is how picks are stored, not which models the owner has.+ vi.spyOn(modelConfig, 'assertGoalModelRunnable').mockResolvedValue();+ await db.insert(users).values({ id: userId }).onConflictDoNothing();+ await db.insert(agents).values([+ { id: agentId, slug: 'model-override-agent', userId },+ { id: otherAgentId, slug: 'model-override-other', userId },+ ]);+ vi.spyOn(scheduler, 'scheduleGoalAdvance').mockResolvedValue();+ vi.spyOn(AiAgentService.prototype, 'execAgent').mockImplementation(async (params) => {+ const operationId = `op-model-override-${++seq}`;+ const topicId = params.appContext!.topicId!;+ await new AgentOperationModel(db, userId).recordStart({+ agentId: params.agentId,+ appContext: { sourceMessageId: params.clientIds?.userMessageId },+ operationId,+ topicId,+ });+ return {+ agentId: params.agentId!,+ assistantMessageId: 'm',+ autoStarted: true,+ createdAt: new Date().toISOString(),+ message: 'started',+ operationId,+ status: 'running',+ success: true,+ timestamp: new Date().toISOString(),+ topicId,+ userMessageId: 'u',+ };+ });+});++afterEach(async () => {+ vi.restoreAllMocks();+ for (const table of [+ goalNodeDecisions,+ goalEdges,+ goalEvents,+ goalNodes,+ goals,+ agentOperations,+ messages,+ topics,+ agents,+ users,+ ])+ await db.delete(table);+});++/** A manager-mode goal whose first planning turn has been dispatched. */+const startManagedGoal = async (extraConfig: Partial<GoalConfig> = {}) => {+ const graph = await service().create({+ config: { manager: { maxTurns: 4 } },+ createdByAgentId: agentId,+ title: 'Managed goal',+ });+ // Supervision would take over the turn; see the same setup in manager.test.ts.+ await db+ .update(goals)+ .set({ config: { manager: { maxTurns: 4 }, ...extraConfig } })+ .where(eq(goals.id, graph.goal.id));+ expect((await service().tick(graph.goal.id)).outcome).toBe('waiting_external');+ return graph.goal.id;+};++describe('goal planning model override', () => {+ it('runs the planning turn on the override', async () => {+ await startManagedGoal({ model: 'deepseek-v4.1-flash', provider: 'deepseek' });++ expect(execAgent().mock.calls[0][0]).toMatchObject({+ agentId,+ model: 'deepseek-v4.1-flash',+ provider: 'deepseek',+ });+ });++ it("runs the planning turn on the agent's own model without one", async () => {+ await startManagedGoal();++ const params = execAgent().mock.calls[0][0];+ expect(params).not.toHaveProperty('model');+ expect(params).not.toHaveProperty('provider');+ });++ it('patches only the model keys, and clears them with null', async () => {+ const graph = await service().create({+ agentId,+ config: { maxConcurrentTasks: 2 },+ title: 'Model override',+ });++ const picked = await service().setModel(graph.goal.id, {+ model: 'deepseek-v4.1-flash',+ provider: 'deepseek',+ });+ expect(picked.config).toMatchObject({+ maxConcurrentTasks: 2,+ model: 'deepseek-v4.1-flash',+ provider: 'deepseek',+ });++ const cleared = await service().setModel(graph.goal.id, null);+ expect(cleared.config).not.toHaveProperty('model');+ expect(cleared.config).not.toHaveProperty('provider');+ expect(cleared.config?.maxConcurrentTasks).toBe(2);+ });++ it('drops the override when the goal changes agent, not when it is re-picked', async () => {+ const graph = await service().create({ agentId, title: 'Handover' });+ await service().setModel(graph.goal.id, { model: 'gpt-5', provider: 'openai' });++ const same = await service().setAgent(graph.goal.id, agentId);+ expect(same.goal.config?.model).toBe('gpt-5');++ const handed = await service().setAgent(graph.goal.id, otherAgentId);+ expect(handed.goal.agentId).toBe(otherAgentId);+ expect(handed.goal.config).not.toHaveProperty('model');+ expect(handed.goal.config).not.toHaveProperty('provider');+ });+});diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex e440d82b34f..c54a0250afc 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -282,6 +282,8 @@"connectAgent.providerDesc.qoder": "Qoder coding agent CLI","connectAgent.providerDesc.trae": "TRAE Enterprise coding agent CLI","createGoal.addCriterion": "Add criterion",+ "createGoal.agentsHint": "The main agent plans and supervises the goal; tasks go to the executor, or to the main agent when none is chosen.",+ "createGoal.agentsTitle": "Agents","createGoal.back": "Back","createGoal.budgetTitle": "Budget","createGoal.contextHint": "Add constraints, source material, or anything the Agent should know",@@ -587,6 +589,7 @@"goalDetail.acceptance": "Acceptance checks","goalDetail.acceptanceError": "Could not load acceptance checks.","goalDetail.acceptanceProgress": "Acceptance progress",+ "goalDetail.agentManagedByOwner": "Only the goal's creator or a Workspace admin can change its agents","goalDetail.agentRun": "Agent run","goalDetail.closeConfirm.achieved.content": "Runs still in progress will be stopped and no new tasks will start. You can reopen the goal from this menu.","goalDetail.closeConfirm.achieved.ok": "Mark achieved",@@ -603,6 +606,9 @@"goalDetail.executionPlan": "Current execution plan","goalDetail.instruction": "Goal instruction","goalDetail.latestRuns": "Recent executions",+ "goalDetail.mainAgent": "Main agent · plans and supervises this goal",+ "goalDetail.mainAgentLabel": "Plan",+ "goalDetail.mainAgentUnassigned": "Choose main agent","goalDetail.metrics.agentRuns": "Agent runs","goalDetail.metrics.latestAcceptance": "Latest acceptance","goalDetail.metrics.planItems": "Plan items",@@ -612,6 +618,7 @@"goalDetail.metrics.taskExecutions": "Task executions","goalDetail.metrics.totalCost": "Total cost","goalDetail.metrics.totalDuration": "Total runtime",+ "goalDetail.modelFixed": "This Agent's author fixed its model; only they or an admin can pick another for this goal","goalDetail.moreActions": "More goal actions","goalDetail.noChecks": "No acceptance checks yet","goalDetail.noDefinition": "No goal definition yet.",@@ -619,7 +626,12 @@"goalDetail.notFoundDescription": "This goal may have been deleted or is no longer accessible.","goalDetail.notFoundTitle": "Goal not found","goalDetail.openExecution": "Open execution task",+ "goalDetail.planningModel": "Planning model · used by the main agent for planning turns","goalDetail.subtasks": "Subtasks",+ "goalDetail.taskAgent": "Executor · does the tasks under this goal",+ "goalDetail.taskAgentFollowsMain": "Same as main agent",+ "goalDetail.taskAgentLabel": "Execute",+ "goalDetail.taskModel": "Task model · used by the goal's tasks, including unfinished ones","goalDetail.taskResult": "Task result","goalDetail.taskStatus": "Execution status","goalDetail.unnamedRun": "Untitled run",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex dd11f089927..184bb743b87 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -282,6 +282,8 @@"connectAgent.providerDesc.qoder": "Qoder 编码助理 CLI","connectAgent.providerDesc.trae": "TRAE 企业版编码助理 CLI","createGoal.addCriterion": "添加验收标准",+ "createGoal.agentsHint": "主 Agent 负责规划和监督目标;任务交给执行 Agent,不选则由主 Agent 自己完成。",+ "createGoal.agentsTitle": "负责的 Agent","createGoal.back": "返回","createGoal.budgetTitle": "预算","createGoal.contextHint": "补充约束、参考资料或 Agent 开始前需要知道的信息",@@ -587,6 +589,7 @@"goalDetail.acceptance": "验收检查","goalDetail.acceptanceError": "无法加载验收检查。","goalDetail.acceptanceProgress": "验收进度",+ "goalDetail.agentManagedByOwner": "只有目标创建者或工作区管理员可以修改负责的 Agent","goalDetail.agentRun": "Agent 运行","goalDetail.closeConfirm.achieved.content": "仍在运行的任务会被中止,也不会再开始新的任务。之后可以在这个菜单里重新打开目标。","goalDetail.closeConfirm.achieved.ok": "标记为已达成",@@ -603,6 +606,9 @@"goalDetail.executionPlan": "当前执行计划","goalDetail.instruction": "目标说明","goalDetail.latestRuns": "最近执行",+ "goalDetail.mainAgent": "主 Agent · 负责规划和监督这个目标",+ "goalDetail.mainAgentLabel": "规划",+ "goalDetail.mainAgentUnassigned": "选择主 Agent","goalDetail.metrics.agentRuns": "Agent 运行次数","goalDetail.metrics.latestAcceptance": "最后验收结果","goalDetail.metrics.planItems": "计划项",@@ -612,6 +618,7 @@"goalDetail.metrics.taskExecutions": "Task 执行次数","goalDetail.metrics.totalCost": "累计消耗成本","goalDetail.metrics.totalDuration": "累计运行时间",+ "goalDetail.modelFixed": "这个 Agent 的模型已被作者固定,只有作者或管理员能为目标另选模型","goalDetail.moreActions": "更多目标操作","goalDetail.noChecks": "暂时没有验收检查","goalDetail.noDefinition": "暂时没有目标定义。",@@ -619,7 +626,12 @@"goalDetail.notFoundDescription": "该目标可能已被删除或你已无法访问。","goalDetail.notFoundTitle": "找不到目标","goalDetail.openExecution": "打开执行任务",+ "goalDetail.planningModel": "规划模型 · 主 Agent 规划时使用","goalDetail.subtasks": "子任务",+ "goalDetail.taskAgent": "执行 Agent · 负责完成这个目标下的任务",+ "goalDetail.taskAgentFollowsMain": "同主 Agent",+ "goalDetail.taskAgentLabel": "执行",+ "goalDetail.taskModel": "执行模型 · 目标下的任务使用,未完成的任务也会切换","goalDetail.taskResult": "任务结果","goalDetail.taskStatus": "执行状态","goalDetail.unnamedRun": "未命名运行",diff --git a/packages/database/src/models/goal.ts b/packages/database/src/models/goal.tsindex 893d09004ca..d036a108ea7 100644--- a/packages/database/src/models/goal.ts+++ b/packages/database/src/models/goal.ts@@ -157,6 +157,35 @@ export class GoalModel {return row as GoalItem | undefined;};+ /**+ * Patch only one model slot of `config` — `model`/`provider` for planning+ * turns, `taskModel`/`taskProvider` for Tasks — or drop it with `null`, for+ * the same reason as `updateTaskAgentId`.+ */+ updateModelConfig = async (+ id: string,+ modelConfig: { model: string; provider: string } | null,+ slot: 'planning' | 'task' = 'planning',+ ) => {+ const [modelKey, providerKey] =+ slot === 'task' ? ['taskModel', 'taskProvider'] : ['model', 'provider'];+ const patch = modelConfig && {+ [modelKey]: modelConfig.model,+ [providerKey]: modelConfig.provider,+ };+ const [row] = await this.db+ .update(goals)+ .set({+ config: patch+ ? sql`COALESCE(${goals.config}, '{}'::jsonb) || ${JSON.stringify(patch)}::jsonb`+ : sql`COALESCE(${goals.config}, '{}'::jsonb) - ${modelKey}::text - ${providerKey}::text`,+ updatedAt: new Date(),+ })+ .where(and(eq(goals.id, id), this.ownership()))+ .returning();+ return row as GoalItem | undefined;+ };+/*** Claim the queued wake for a Task waiting on a usage-window reset, so that* repeated ticks before the reset (the sweep, Task events, manual advances)diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 161d792b021..abda1a353ed 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -2137,6 +2137,9 @@ export default {'createGoal.costBudgetPlaceholder': 'No cap','createGoal.createFailed': 'Failed to create goal','createGoal.back': 'Back',+ 'createGoal.agentsHint':+ 'The main agent plans and supervises the goal; tasks go to the executor, or to the main agent when none is chosen.',+ 'createGoal.agentsTitle': 'Agents','createGoal.budgetTitle': 'Budget','createGoal.contextLabel': 'Context for the Agent','createGoal.contextHint': 'Add constraints, source material, or anything the Agent should know',@@ -2289,6 +2292,8 @@ export default {'goalTask.step.queued': 'Not started','goalList.title': 'Goals','goalDetail.acceptance': 'Acceptance checks',+ 'goalDetail.agentManagedByOwner':+ "Only the goal's creator or a Workspace admin can change its agents",'goalAcceptance.add': 'Add criterion','goalAcceptance.edit': 'Edit','goalAcceptance.empty': 'No criteria yet — add the outcomes the final acceptance should check.',@@ -2319,6 +2324,9 @@ export default {'The complete task tree and latest runs for this goal.','goalDetail.instruction': 'Goal instruction','goalDetail.latestRuns': 'Recent executions',+ 'goalDetail.mainAgent': 'Main agent · plans and supervises this goal',+ 'goalDetail.mainAgentLabel': 'Plan',+ 'goalDetail.mainAgentUnassigned': 'Choose main agent','goalDetail.closeConfirm.achieved.content':'Runs still in progress will be stopped and no new tasks will start. You can reopen the goal from this menu.','goalDetail.closeConfirm.achieved.ok': 'Mark achieved',@@ -2332,6 +2340,13 @@ export default {'goalDetail.deleteConfirm.ok': 'Delete goal','goalDetail.deleteConfirm.title': 'Delete this goal?','goalDetail.moreActions': 'More goal actions',+ 'goalDetail.modelFixed':+ "This Agent's author fixed its model; only they or an admin can pick another for this goal",+ 'goalDetail.planningModel': 'Planning model · used by the main agent for planning turns',+ 'goalDetail.taskAgent': 'Executor · does the tasks under this goal',+ 'goalDetail.taskAgentFollowsMain': 'Same as main agent',+ 'goalDetail.taskAgentLabel': 'Execute',+ 'goalDetail.taskModel': "Task model · used by the goal's tasks, including unfinished ones",'goalDetail.metrics.planItems': 'Plan items','goalDetail.metrics.progress': 'Progress','goalDetail.metrics.agentRuns': 'Agent runs',diff --git a/packages/types/src/goal.ts b/packages/types/src/goal.tsindex 73312ea50c1..499277fbf00 100644--- a/packages/types/src/goal.ts+++ b/packages/types/src/goal.ts@@ -1,5 +1,5 @@import type { GoalReportDispatch, GoalReportState } from './goalReport';-import type { GoalRolloutRetro, GoalRolloutVerifier } from './goalRetro';+import type { GoalRolloutPolicy, GoalRolloutState } from './goalRollout';import type { InitialGoalOverviewContext } from './stepContext';import type { AcceptanceStatus, VerifyCheckTally } from './verify';import type { WorkType } from './work';@@ -453,345 +453,6 @@ export interface GoalUnderstanding {updatedAt: string;}-/**- * Batch rollout trigger. `off`/absent keeps the ordinary decomposition: a goal- * that is not one repeated mould never grows a batch node, and the coordinator- * reads none of the rollout code paths. `canary` probes first, proves the class- * is fully automatic at a gate, then releases the rest in waves; `full` skips- * the probe and delivers every unit as one wave.- */-export type GoalRolloutTrigger = 'canary' | 'full' | 'off';--/**- * One axis the repeated units vary along. Recorded so the gate can refuse a- * green whose coverage never took a value on some axis — the half the probe- * happened to miss (a `cold-start` value discovered only later).- */-export interface GoalRolloutVariantAxis {- /** Axis name, e.g. "cold-start", "auth-boundary". */- axis: string;- /** Concrete values the repeated units take on this axis. */- values: string[];-}--/**- * Batch rollout policy. Lives on the JSONB `config` column like the other goal- * policies — the graph's own vocabulary (`goal_nodes.kind`) carries the shape,- * so nothing here needs a schema of its own.- */-export interface GoalRolloutPolicy {- /** Probe size K — how many representative units run before the gate. */- canarySize?: number;- /**- * How many structurally identical units make one batch worth gating. Below it- * the ordinary per-unit decomposition is cheaper than the ceremony.- */- minHomogeneousUnits?: number;- /** Why the planner judged this batch homogeneous; kept for the gate report. */- spec?: {- /** R2 condition: after masking concrete names, is the transform still one? */- repeatable: boolean;- /** The reusable transformation, in the planner's words. */- recipeOutline?: string;- variantAxes?: GoalRolloutVariantAxis[];- };- trigger: GoalRolloutTrigger;- /**- * Notes for individual roster units, keyed by unit title. A main Agent that- * declares the batch can give each unit its own pointers (files, edge cases);- * a released unit's brief is the recipe plus its note.- */- unitBriefs?: Record<string, string>;- /**- * Roster of every homogeneous unit in the goal, probes included and in- * delivery order. Probes are the first, fully-briefed units; the coordinator- * materializes the rest from here one wave at a time, so the graph never- * shows the whole fan-out at build time.- */- units?: string[];- /** Mass wave size M — how many units are released per wave after the gate. */- waveSize?: number;-}--/**- * One condition the release gate judged. Mirrors `evaluateRolloutGate`: the- * same keys, in the same order, with what each one found — so the person can see- * why a gate passed or held, not only that it did.- */-export type GoalRolloutGateCheckKey =- | 'axes_covered'- /** Every person's intervention in the batch was accounted for by its retro. */- | 'interventions_accounted'- | 'no_open_decision'- | 'plan_written'- /** The batch's delivered units passed the verifier its retro produced. */- | 'reverified'- | 'units_settled'- | 'units_succeeded';--export interface GoalRolloutGateCheck {- /** For a count check: how many of `total` held, e.g. 5 of 5 units ran through. */- count?: number;- /** Free-form specifics, such as an uncovered `axis=value`. */- details?: string[];- key: GoalRolloutGateCheckKey;- /** The nodes the check is about — the units that failed, the open decision. */- nodeIds?: string[];- passed: boolean;- total?: number;-}--/**- * One gate verdict and what the coordinator did with it. Appended on every- * release and every hold, so the gate keeps its own record instead of the- * decision's prose being the only trace.- */-export interface GoalRolloutGateEvaluation {- /** Who approved a release; absent on holds and on releases from before approvals existed. */- approvedBy?: 'agent' | 'user';- /** ISO time of the verdict. */- at: string;- /** What the gate judged; empty when a unit's own check held the batch (R6). */- checks: GoalRolloutGateCheck[];- /** The coordinator's English summary, kept for the trace. */- message?: string;- /** The unit whose own check held the batch, when `trigger` is `unit`. */- nodeId?: string;- outcome: 'blocked' | 'released';- /** Units the release put into the next wave. */- releasedCount?: number;- /** The recipe revision (round) this verdict belongs to. */- revision: number;- /**- * 1-based ordinal of this verdict within its round. Written by the- * coordinator so it keeps counting after older verdicts were dropped.- */- seq?: number;- /** `gate`: the gate judged a settled wave. `unit`: one unit failed its own check. */- trigger: 'gate' | 'unit';- /**- * The roster wave a release put out, counted across every round. Written by- * the coordinator because the log is capped — counting the kept entries would- * renumber the history once the oldest fall off.- */- wave?: number;- /** Waves released in this round when the verdict was taken (after a release). */- waveIndex: number;-}--/**- * Where a batch rollout currently stands. `release_review`: the gate passed and- * the next wave waits on a person's approval — always before a round's first- * mass wave, and later whenever the main Agent escalates a release.- */-export type GoalRolloutPhase =- | 'probe'- | 'assay'- | 'mass'- | 'pattern_break'- | 'release_review'- /** The owner sent the plan back; the main Agent is rewriting it for the owner to review again. */- | 'plan_revision'- /**- * The round's probes settled; the main Agent rewrites the plan from them, and- * the gate judges them straight from here (`release_review` / `pattern_break`).- */- | 'plan_distill'- | 'done';--/**- * Who approved releasing one wave. A passed gate only proves the checks held;- * the release itself is a decision: a person approves a round's first wave, and- * the main Agent (or a person it escalated to) every later one.- */-export interface GoalRolloutReleaseApproval {- at: string;- by: 'agent' | 'user';- /** The main Agent's reason, or the person's note. */- reason?: string;- /** The recipe revision (round) the approval belongs to. */- revision: number;- /** The round's `waveIndex` the approval releases from. */- waveIndex: number;-}--/**- * Coordinator-owned rollout progress. Written by decomposition and by the- * coordinator's own gate moves, never by a policy edit — the same rule that- * keeps `managerState` server-owned.- */-/**- * What one break taught the batch: a rule in the batch's expertise domain,- * which every later unit's acceptance adds as a clause it must meet.- */-export interface GoalRolloutLearning {- /**- * Legacy: a standalone criterion compiled from the rule by an earlier- * version. Nothing mounts it — later units' acceptance carries `rule` as a- * clause of its requirement instead.- */- criterionId?: string;- lessonCode?: string;- lessonId: string;- /** The round whose gate broke and taught it. */- revision: number;- /** The whole correction, as written — `title` is its one-line label. */- rule?: string;- title: string;-}--/** The batch's execution plan, kept as a skill in the user's own skill library. */-export interface GoalRolloutPlanSkill {- /** The skill bundle's document id. */- id: string;- /** The skill's name: units load it as `user-skills:<name>`. */- name: string;-}--/** One unit a release gate reports on: a probe, or a member of the last released wave. */-export interface GoalReleaseGateUnit {- /** The unit's own acceptance, when it was verified. */- acceptance?: { checks?: { failed: number; passed: number; total: number }; id: string };- /** Deliverables it produced: pull requests, reports, documents. */- artifacts: { documentId?: string; title: string; type: string; url?: string }[];- /** The unit's own brief: what it was asked to do. */- brief?: string;- nodeId: string;- /** Runs the unit took; more than one means it was reworked. */- runs: number;- status: GoalNodeStatus;- taskId?: string;- title: string;- tokens: number;-}--/**- * Everything the owner decides a release gate on, frozen when the gate opens.- * Rides the gate's acceptance round so the review page reads one snapshot- * instead of reassembling the batch from the live graph.- */-export interface GoalReleaseGateDossier {- /** The goal's supervising agent — who reports the gate to the owner. */- agentId?: string;- /** Gate checks the coordinator judged; advice, not the decision. */- checks: GoalRolloutGateCheck[];- /** The main Agent's reasoning when it brought the release back. */- diagnosis?: string;- goalId: string;- goalTitle: string;- /**- * `probes`: the first move from probes to batch execution, always a person's.- * `escalated`: the main Agent declined to release a later wave.- * `unattended`: no main Agent could take a later release.- */- kind: 'escalated' | 'probes' | 'unattended';- /** The units the next wave releases, with their own notes. */- nextWave: { brief?: string; title: string }[];- /** The recipe every unit follows: the plan skill's current version. */- plan: { content: string; revision: number; skillId?: string; skillName?: string };- /** Units still owed after the next wave. */- remainingAfter: number;- /** Units the decision is judged on, in display order. */- units: GoalReleaseGateUnit[];- /** 1-based roster wave the decision releases. */- wave: number;-}--export interface GoalRolloutState {- /** The gate (Assay) decision node, once decomposition created it. */- assayNodeId?: string;- /** The `batch` container node. */- batchNodeId: string;- /**- * The probe set the plan was last distilled from (see `probeSetKey`), or- * skipped for want of a main Agent turn. Set while still in `plan_distill`, it- * tells the gate the plan is ready to judge the probes on. Re-opened or re-run- * probes form a new set and are distilled again.- */- distilledProbes?: string;- /**- * Gate verdicts, oldest first. Each round keeps its most recent few, so a- * round that was judged never loses its latest verdict to later rounds.- */- gateLog?: GoalRolloutGateEvaluation[];- /** The expertise domain the batch's breaks teach, once one has. */- learningDomainId?: string;- /** Every rule a break taught, oldest first. */- learnings?: GoalRolloutLearning[];- /**- * Node ids of the mass tasks the current round released, oldest wave first.- * A restarted canary starts a new round and clears it.- */- massNodeIds?: string[];- /**- * The main Agent's plan rewritten from the settled probes, while the phase is- * `plan_distill`. The next advance lands it as the plan skill's next version- * and judges the gate in the same step.- */- pendingDistill?: { reason: string; recipe: string };- /**- * The owner's correction a sent-back release waits on, while the phase is- * `plan_revision`. The main Agent rewrites the plan from it (`revisedRecipe`)- * and names the delivered units the correction covers (`rerun`). Those units- * run again on the rewrite as a new round of experiments before the owner- * reviews it; with none to re-run, the rewrite returns to the review at once.- */- pendingRevision?: {- correction: string;- /**- * Node ids (or titles) of the reviewed round's units to run again on the- * rewrite. Absent re-runs every one of them; empty re-runs none.- */- rerun?: string[];- revisedReason?: string;- revisedRecipe?: string;- };- /** Phase the rollout is in; the coordinator reads this to pick its move. */- phase: GoalRolloutPhase;- /** The execution plan as a user skill; each Template revision is one of its versions. */- planSkill?: GoalRolloutPlanSkill;- /**- * The plan skill version each round runs on, by round (`templateRevision`).- * A round's plan can be rewritten in place — the owner sends it back at its- * release gate and the main Agent rewrites it — so a round is not always on- * the version numbered after it. Absent entries mean version = round.- */- planVersions?: Record<string, number>;- /** Node ids of the probe tasks that must run before the gate passes. */- probeNodeIds: string[];- /**- * The approval the next wave is released on. Valid only for the round and- * `waveIndex` it names, so a release never rides on an earlier wave's approval.- */- releaseApproval?: GoalRolloutReleaseApproval;- /** How many roster entries have been materialized (probes + released waves). */- releasedCount?: number;- /** The acceptance the held release is reviewed on, when one could be opened. */- releaseGateAcceptanceId?: string;- /** The decision node a held release waits on, while the phase is `release_review`. */- releaseReviewNodeId?: string;- /** One retro per execution — the probes, then each roster wave — oldest first. */- retros?: GoalRolloutRetro[];- /** Node id of the current Template (finding) node. */- templateNodeId?: string;- /** Current Template revision; incremented each time the recipe is revised. */- templateRevision: number;- /**- * The class still to deliver, in delivery order; probes come first. Starts as- * the full roster. A pattern break re-cuts it to what is still owed — the- * re-opened probes, the broken units past the canary size, then whatever was- * never released — so waves deliver only the remainder and units already- * delivered under the old recipe drop out.- */- unitTitles?: string[];- /** The batch's verifier, once a retro produced one. */- verifier?: GoalRolloutVerifier;- /** How many mass waves have been released. */- waveIndex: number;- /** Roster waves released so far across every round; `waveIndex` restarts per round. */- wavesReleased?: number;-}-export interface GoalConfig {acceptance?: GoalAcceptancePolicy;/**@@ -810,12 +471,20 @@ export interface GoalConfig {* before the first result came back. Null/undefined uses the default.*/maxConcurrentTasks?: number | null;+ /**+ * The model the goal agent plans with, overriding that agent's own model for+ * planning turns only. Unset means the agent's own model. Always written+ * together with `provider`, and dropped when the goal changes agent.+ */+ model?: string;/** Who the current pause belongs to; cleared when the goal runs again. */pausedBy?: GoalPauseReason;/** Coordinator-owned lease for initial decomposition; not a user policy. */planningCheckpoint?: { expiresAt: string; token: string };/** Retained after release to distinguish lease-aware retries from legacy planners. */planningProtocol?: 'lease-v1';+ /** Provider of `model`; set and cleared with it. */+ provider?: string;/*** Coordinator-owned: when the queued wake for a Task waiting on a usage-window* reset fires. One wake per Goal, so ticks before the reset do not queue more.@@ -841,6 +510,14 @@ export interface GoalConfig {* Unset means the goal's agent does its own Tasks.*/taskAgentId?: string;+ /**+ * The model the goal's Tasks run on, overriding their executor's own model.+ * Applied to Tasks the coordinator creates and to unfinished ones when set.+ * Written together with `taskProvider`, dropped when the executor changes.+ */+ taskModel?: string;+ /** Provider of `taskModel`; set and cleared with it. */+ taskProvider?: string;/** Coordinator-owned; written by decomposition, never by a policy edit. */understanding?: GoalUnderstanding;}diff --git a/packages/types/src/goalRollout.ts b/packages/types/src/goalRollout.tsnew file mode 100644index 00000000000..5a6cc678b09--- /dev/null+++ b/packages/types/src/goalRollout.ts@@ -0,0 +1,341 @@+import type { GoalNodeStatus } from './goal';+import type { GoalRolloutRetro, GoalRolloutVerifier } from './goalRetro';++/**+ * Batch rollout trigger. `off`/absent keeps the ordinary decomposition: a goal+ * that is not one repeated mould never grows a batch node, and the coordinator+ * reads none of the rollout code paths. `canary` probes first, proves the class+ * is fully automatic at a gate, then releases the rest in waves; `full` skips+ * the probe and delivers every unit as one wave.+ */+export type GoalRolloutTrigger = 'canary' | 'full' | 'off';++/**+ * One axis the repeated units vary along. Recorded so the gate can refuse a+ * green whose coverage never took a value on some axis — the half the probe+ * happened to miss (a `cold-start` value discovered only later).+ */+export interface GoalRolloutVariantAxis {+ /** Axis name, e.g. "cold-start", "auth-boundary". */+ axis: string;+ /** Concrete values the repeated units take on this axis. */+ values: string[];+}++/**+ * Batch rollout policy. Lives on the JSONB `config` column like the other goal+ * policies — the graph's own vocabulary (`goal_nodes.kind`) carries the shape,+ * so nothing here needs a schema of its own.+ */+export interface GoalRolloutPolicy {+ /** Probe size K — how many representative units run before the gate. */+ canarySize?: number;+ /**+ * How many structurally identical units make one batch worth gating. Below it+ * the ordinary per-unit decomposition is cheaper than the ceremony.+ */+ minHomogeneousUnits?: number;+ /** Why the planner judged this batch homogeneous; kept for the gate report. */+ spec?: {+ /** R2 condition: after masking concrete names, is the transform still one? */+ repeatable: boolean;+ /** The reusable transformation, in the planner's words. */+ recipeOutline?: string;+ variantAxes?: GoalRolloutVariantAxis[];+ };+ trigger: GoalRolloutTrigger;+ /**+ * Notes for individual roster units, keyed by unit title. A main Agent that+ * declares the batch can give each unit its own pointers (files, edge cases);+ * a released unit's brief is the recipe plus its note.+ */+ unitBriefs?: Record<string, string>;+ /**+ * Roster of every homogeneous unit in the goal, probes included and in+ * delivery order. Probes are the first, fully-briefed units; the coordinator+ * materializes the rest from here one wave at a time, so the graph never+ * shows the whole fan-out at build time.+ */+ units?: string[];+ /** Mass wave size M — how many units are released per wave after the gate. */+ waveSize?: number;+}++/**+ * One condition the release gate judged. Mirrors `evaluateRolloutGate`: the+ * same keys, in the same order, with what each one found — so the person can see+ * why a gate passed or held, not only that it did.+ */+export type GoalRolloutGateCheckKey =+ | 'axes_covered'+ /** Every person's intervention in the batch was accounted for by its retro. */+ | 'interventions_accounted'+ | 'no_open_decision'+ | 'plan_written'+ /** The batch's delivered units passed the verifier its retro produced. */+ | 'reverified'+ | 'units_settled'+ | 'units_succeeded';++export interface GoalRolloutGateCheck {+ /** For a count check: how many of `total` held, e.g. 5 of 5 units ran through. */+ count?: number;+ /** Free-form specifics, such as an uncovered `axis=value`. */+ details?: string[];+ key: GoalRolloutGateCheckKey;+ /** The nodes the check is about — the units that failed, the open decision. */+ nodeIds?: string[];+ passed: boolean;+ total?: number;+}++/**+ * One gate verdict and what the coordinator did with it. Appended on every+ * release and every hold, so the gate keeps its own record instead of the+ * decision's prose being the only trace.+ */+export interface GoalRolloutGateEvaluation {+ /** Who approved a release; absent on holds and on releases from before approvals existed. */+ approvedBy?: 'agent' | 'user';+ /** ISO time of the verdict. */+ at: string;+ /** What the gate judged; empty when a unit's own check held the batch (R6). */+ checks: GoalRolloutGateCheck[];+ /** The coordinator's English summary, kept for the trace. */+ message?: string;+ /** The unit whose own check held the batch, when `trigger` is `unit`. */+ nodeId?: string;+ outcome: 'blocked' | 'released';+ /** Units the release put into the next wave. */+ releasedCount?: number;+ /** The recipe revision (round) this verdict belongs to. */+ revision: number;+ /**+ * 1-based ordinal of this verdict within its round. Written by the+ * coordinator so it keeps counting after older verdicts were dropped.+ */+ seq?: number;+ /** `gate`: the gate judged a settled wave. `unit`: one unit failed its own check. */+ trigger: 'gate' | 'unit';+ /**+ * The roster wave a release put out, counted across every round. Written by+ * the coordinator because the log is capped — counting the kept entries would+ * renumber the history once the oldest fall off.+ */+ wave?: number;+ /** Waves released in this round when the verdict was taken (after a release). */+ waveIndex: number;+}++/**+ * Where a batch rollout currently stands. `release_review`: the gate passed and+ * the next wave waits on a person's approval — always before a round's first+ * mass wave, and later whenever the main Agent escalates a release.+ */+export type GoalRolloutPhase =+ | 'probe'+ | 'assay'+ | 'mass'+ | 'pattern_break'+ | 'release_review'+ /** The owner sent the plan back; the main Agent is rewriting it for the owner to review again. */+ | 'plan_revision'+ /**+ * The round's probes settled; the main Agent rewrites the plan from them, and+ * the gate judges them straight from here (`release_review` / `pattern_break`).+ */+ | 'plan_distill'+ | 'done';++/**+ * Who approved releasing one wave. A passed gate only proves the checks held;+ * the release itself is a decision: a person approves a round's first wave, and+ * the main Agent (or a person it escalated to) every later one.+ */+export interface GoalRolloutReleaseApproval {+ at: string;+ by: 'agent' | 'user';+ /** The main Agent's reason, or the person's note. */+ reason?: string;+ /** The recipe revision (round) the approval belongs to. */+ revision: number;+ /** The round's `waveIndex` the approval releases from. */+ waveIndex: number;+}++/**+ * Coordinator-owned rollout progress. Written by decomposition and by the+ * coordinator's own gate moves, never by a policy edit — the same rule that+ * keeps `managerState` server-owned.+ */+/**+ * What one break taught the batch: a rule in the batch's expertise domain,+ * which every later unit's acceptance adds as a clause it must meet.+ */+export interface GoalRolloutLearning {+ /**+ * Legacy: a standalone criterion compiled from the rule by an earlier+ * version. Nothing mounts it — later units' acceptance carries `rule` as a+ * clause of its requirement instead.+ */+ criterionId?: string;+ lessonCode?: string;+ lessonId: string;+ /** The round whose gate broke and taught it. */+ revision: number;+ /** The whole correction, as written — `title` is its one-line label. */+ rule?: string;+ title: string;+}++/** The batch's execution plan, kept as a skill in the user's own skill library. */+export interface GoalRolloutPlanSkill {+ /** The skill bundle's document id. */+ id: string;+ /** The skill's name: units load it as `user-skills:<name>`. */+ name: string;+}++/** One unit a release gate reports on: a probe, or a member of the last released wave. */+export interface GoalReleaseGateUnit {+ /** The unit's own acceptance, when it was verified. */+ acceptance?: { checks?: { failed: number; passed: number; total: number }; id: string };+ /** Deliverables it produced: pull requests, reports, documents. */+ artifacts: { documentId?: string; title: string; type: string; url?: string }[];+ /** The unit's own brief: what it was asked to do. */+ brief?: string;+ nodeId: string;+ /** Runs the unit took; more than one means it was reworked. */+ runs: number;+ status: GoalNodeStatus;+ taskId?: string;+ title: string;+ tokens: number;+}++/**+ * Everything the owner decides a release gate on, frozen when the gate opens.+ * Rides the gate's acceptance round so the review page reads one snapshot+ * instead of reassembling the batch from the live graph.+ */+export interface GoalReleaseGateDossier {+ /** The goal's supervising agent — who reports the gate to the owner. */+ agentId?: string;+ /** Gate checks the coordinator judged; advice, not the decision. */+ checks: GoalRolloutGateCheck[];+ /** The main Agent's reasoning when it brought the release back. */+ diagnosis?: string;+ goalId: string;+ goalTitle: string;+ /**+ * `probes`: the first move from probes to batch execution, always a person's.+ * `escalated`: the main Agent declined to release a later wave.+ * `unattended`: no main Agent could take a later release.+ */+ kind: 'escalated' | 'probes' | 'unattended';+ /** The units the next wave releases, with their own notes. */+ nextWave: { brief?: string; title: string }[];+ /** The recipe every unit follows: the plan skill's current version. */+ plan: { content: string; revision: number; skillId?: string; skillName?: string };+ /** Units still owed after the next wave. */+ remainingAfter: number;+ /** Units the decision is judged on, in display order. */+ units: GoalReleaseGateUnit[];+ /** 1-based roster wave the decision releases. */+ wave: number;+}++export interface GoalRolloutState {+ /** The gate (Assay) decision node, once decomposition created it. */+ assayNodeId?: string;+ /** The `batch` container node. */+ batchNodeId: string;+ /**+ * The probe set the plan was last distilled from (see `probeSetKey`), or+ * skipped for want of a main Agent turn. Set while still in `plan_distill`, it+ * tells the gate the plan is ready to judge the probes on. Re-opened or re-run+ * probes form a new set and are distilled again.+ */+ distilledProbes?: string;+ /**+ * Gate verdicts, oldest first. Each round keeps its most recent few, so a+ * round that was judged never loses its latest verdict to later rounds.+ */+ gateLog?: GoalRolloutGateEvaluation[];+ /** The expertise domain the batch's breaks teach, once one has. */+ learningDomainId?: string;+ /** Every rule a break taught, oldest first. */+ learnings?: GoalRolloutLearning[];+ /**+ * Node ids of the mass tasks the current round released, oldest wave first.+ * A restarted canary starts a new round and clears it.+ */+ massNodeIds?: string[];+ /**+ * The main Agent's plan rewritten from the settled probes, while the phase is+ * `plan_distill`. The next advance lands it as the plan skill's next version+ * and judges the gate in the same step.+ */+ pendingDistill?: { reason: string; recipe: string };+ /**+ * The owner's correction a sent-back release waits on, while the phase is+ * `plan_revision`. The main Agent rewrites the plan from it (`revisedRecipe`)+ * and names the delivered units the correction covers (`rerun`). Those units+ * run again on the rewrite as a new round of experiments before the owner+ * reviews it; with none to re-run, the rewrite returns to the review at once.+ */+ pendingRevision?: {+ correction: string;+ /**+ * Node ids (or titles) of the reviewed round's units to run again on the+ * rewrite. Absent re-runs every one of them; empty re-runs none.+ */+ rerun?: string[];+ revisedReason?: string;+ revisedRecipe?: string;+ };+ /** Phase the rollout is in; the coordinator reads this to pick its move. */+ phase: GoalRolloutPhase;+ /** The execution plan as a user skill; each Template revision is one of its versions. */+ planSkill?: GoalRolloutPlanSkill;+ /**+ * The plan skill version each round runs on, by round (`templateRevision`).+ * A round's plan can be rewritten in place — the owner sends it back at its+ * release gate and the main Agent rewrites it — so a round is not always on+ * the version numbered after it. Absent entries mean version = round.+ */+ planVersions?: Record<string, number>;+ /** Node ids of the probe tasks that must run before the gate passes. */+ probeNodeIds: string[];+ /**+ * The approval the next wave is released on. Valid only for the round and+ * `waveIndex` it names, so a release never rides on an earlier wave's approval.+ */+ releaseApproval?: GoalRolloutReleaseApproval;+ /** How many roster entries have been materialized (probes + released waves). */+ releasedCount?: number;+ /** The acceptance the held release is reviewed on, when one could be opened. */+ releaseGateAcceptanceId?: string;+ /** The decision node a held release waits on, while the phase is `release_review`. */+ releaseReviewNodeId?: string;+ /** One retro per execution — the probes, then each roster wave — oldest first. */+ retros?: GoalRolloutRetro[];+ /** Node id of the current Template (finding) node. */+ templateNodeId?: string;+ /** Current Template revision; incremented each time the recipe is revised. */+ templateRevision: number;+ /**+ * The class still to deliver, in delivery order; probes come first. Starts as+ * the full roster. A pattern break re-cuts it to what is still owed — the+ * re-opened probes, the broken units past the canary size, then whatever was+ * never released — so waves deliver only the remainder and units already+ * delivered under the old recipe drop out.+ */+ unitTitles?: string[];+ /** The batch's verifier, once a retro produced one. */+ verifier?: GoalRolloutVerifier;+ /** How many mass waves have been released. */+ waveIndex: number;+ /** Roster waves released so far across every round; `waveIndex` restarts per round. */+ wavesReleased?: number;+}diff --git a/packages/types/src/index.ts b/packages/types/src/index.tsindex 77d794340db..88cab98f211 100644--- a/packages/types/src/index.ts+++ b/packages/types/src/index.ts@@ -37,6 +37,7 @@ export * from './generation';export * from './goal';export * from './goalReport';export * from './goalRetro';+export * from './goalRollout';export * from './goalSubscription';export * from './heteroSessionImport';export * from './home';diff --git a/packages/types/src/verify.ts b/packages/types/src/verify.tsindex 662fbaca1d4..d4a7070f6ff 100644--- a/packages/types/src/verify.ts+++ b/packages/types/src/verify.ts@@ -1,5 +1,5 @@import type { VerifyCheckDefinition } from './acceptanceFlow';-import type { GoalReleaseGateDossier } from './goal';+import type { GoalReleaseGateDossier } from './goalRollout';/*** Verify (delivery checker) domain types — the shared vocabulary, frozen-item* shape, Toulmin narrative, and rubric run-policy config. Kept here (not in thediff --git a/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsx b/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsxindex 8623d4fee1e..e8750e06419 100644--- a/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsx+++ b/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsx@@ -43,7 +43,8 @@ import { usePermission } from '@/hooks/usePermission';import { goalService } from '@/services/goal';import { shinyTextStyles } from '@/styles';-import { buildGoalCreateInput, buildReviewedGoalContent } from './goalConfig';+import GoalAgentPill from '../GoalAgentPill';+import { buildGoalAgents, buildGoalCreateInput, buildReviewedGoalContent } from './goalConfig';import { createFallbackGoalCriterion, generateGoalCriteria } from './goalCriteria';import { deriveGoalTitle } from './goalTitle';@@ -241,6 +242,10 @@ const CreateGoalContent = memo<CreateGoalContentProps>((props) => {name: initialTitle ?? '',});const [remainingSeconds, setRemainingSeconds] = useState(GENERATION_ESTIMATE_SECONDS);+ // Who plans the goal (its main agent) and who does its Tasks. Unset executor+ // means the main agent does them itself.+ const [plannerId, setPlannerId] = useState(agentId);+ const [executorId, setExecutorId] = useState<string>();const editor = useEditor();const instructionRef = useRef(plan.instruction);@@ -369,10 +374,12 @@ const CreateGoalContent = memo<CreateGoalContentProps>((props) => {setIsCreating(true);try {+ const { agentId: goalAgentId, taskAgentId } = buildGoalAgents(plannerId, executorId);const graph = await goalService.create({- agentId,+ agentId: goalAgentId,config: {recovery: { maxAttemptsPerTask: resolveGoalAttemptBudget(plan.maxIterations) },+ ...(taskAgentId ? { taskAgentId } : {}),},// `maxIterations` is the per-Task attempt budget above; it is not the// graph-wide round cap, which counts runs across every Task and would@@ -405,7 +412,7 @@ const CreateGoalContent = memo<CreateGoalContentProps>((props) => {} finally {setIsCreating(false);}- }, [agentId, canCreate, close, onCreated, plan, projectId, t]);+ }, [canCreate, close, executorId, onCreated, plan, plannerId, projectId, t]);const handlePrimaryAction =step === 'describe' ? handleNext : step === 'review' ? handleSubmit : undefined;@@ -592,6 +599,42 @@ const CreateGoalContent = memo<CreateGoalContentProps>((props) => {</CriterionList></Flexbox>+ <Flexbox className={styles.reviewSection} gap={10}>+ <Text fontSize={13} weight={600}>+ {t('createGoal.agentsTitle')}+ </Text>+ <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>+ <GoalAgentPill+ agentId={plannerId}+ disabled={!canCreate}+ disabledReason={reason}+ label={t('goalDetail.mainAgentLabel')}+ placeholder={t('goalDetail.mainAgentUnassigned')}+ tooltip={t('goalDetail.mainAgent')}+ onChange={(next) => {+ if (!next) return;+ setPlannerId(next);+ // One agent, one slot: the new main agent does its own Tasks.+ if (next === executorId) setExecutorId(undefined);+ }}+ />+ {plannerId && (+ <GoalAgentPill+ agentId={executorId}+ disabled={!canCreate}+ disabledReason={reason}+ label={t('goalDetail.taskAgentLabel')}+ placeholder={t('goalDetail.taskAgentFollowsMain')}+ tooltip={t('goalDetail.taskAgent')}+ onChange={(next) => setExecutorId(next && next !== plannerId ? next : undefined)}+ />+ )}+ </Flexbox>+ <Text className={styles.sectionHint} fontSize={12}>+ {t('createGoal.agentsHint')}+ </Text>+ </Flexbox>+<Flexbox className={styles.reviewSection} gap={10}><Text fontSize={13} weight={600}>{t('createGoal.budgetTitle')}diff --git a/src/features/AgentGoals/CreateGoalModal/goalConfig.test.ts b/src/features/AgentGoals/CreateGoalModal/goalConfig.test.tsindex 15ecd949ae5..58755484e0a 100644--- a/src/features/AgentGoals/CreateGoalModal/goalConfig.test.ts+++ b/src/features/AgentGoals/CreateGoalModal/goalConfig.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from 'vitest';import {+ buildGoalAgents,buildGoalCreateInput,buildReviewedGoalContent,deriveInitialGoalCriterionTitle,@@ -60,3 +61,20 @@ describe('buildReviewedGoalContent', () => {});});});++describe('buildGoalAgents', () => {+ it('routes Tasks to a dedicated executor', () => {+ expect(buildGoalAgents('agt_plan', 'agt_exec')).toEqual({+ agentId: 'agt_plan',+ taskAgentId: 'agt_exec',+ });+ });++ it('leaves Tasks with the main agent when no other executor is picked', () => {+ expect(buildGoalAgents('agt_plan')).toEqual({ agentId: 'agt_plan', taskAgentId: undefined });+ expect(buildGoalAgents('agt_plan', 'agt_plan')).toEqual({+ agentId: 'agt_plan',+ taskAgentId: undefined,+ });+ });+});diff --git a/src/features/AgentGoals/CreateGoalModal/goalConfig.ts b/src/features/AgentGoals/CreateGoalModal/goalConfig.tsindex 0e62945ccc0..972487c5b3f 100644--- a/src/features/AgentGoals/CreateGoalModal/goalConfig.ts+++ b/src/features/AgentGoals/CreateGoalModal/goalConfig.ts@@ -43,3 +43,13 @@ export const buildReviewedGoalContent = (instruction: string) => ({problemDescription: instruction,requirement: instruction,});++/**+ * Who the goal goes to: its main agent, plus a dedicated executor only when one+ * was picked that is not the main agent — naming the main agent there is the+ * same as leaving Tasks with it.+ */+export const buildGoalAgents = (plannerId?: string, executorId?: string) => ({+ agentId: plannerId,+ taskAgentId: executorId && executorId !== plannerId ? executorId : undefined,+});diff --git a/src/features/AgentGoals/GoalAgentModelConfig.tsx b/src/features/AgentGoals/GoalAgentModelConfig.tsxnew file mode 100644index 00000000000..6db6c838e3c--- /dev/null+++ b/src/features/AgentGoals/GoalAgentModelConfig.tsx@@ -0,0 +1,84 @@+import { Flexbox } from '@lobehub/ui';+import { useTranslation } from 'react-i18next';++import GoalAgentPill from './GoalAgentPill';+import { useGoalAgentModel } from './useGoalAgentModel';++interface GoalAgentModelConfigProps {+ /** Only the goal's owner may hand it over, the same rule as restart. */+ disabled?: boolean;+ /** Why `disabled` holds, so a read-only viewer learns the actual restriction. */+ disabledReason?: string;+ goalId: string;+ /** The agent the page route is scoped to; see `useGoalAgentModel`. */+ routeAgentId?: string;+}++/**+ * Who plans the goal and who does its Tasks, each with the model it runs on+ * behind a settings button — like a Task's assignee and model.+ */+const GoalAgentModelConfig = ({+ disabled,+ disabledReason,+ goalId,+ routeAgentId,+}: GoalAgentModelConfigProps) => {+ const { t } = useTranslation('chat');+ const { executor, planner, viewerIsOwner } = useGoalAgentModel({ goalId, routeAgentId });++ return (+ <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }} wrap={'wrap'}>+ <GoalAgentPill+ agentId={planner.agentId}+ disabled={disabled}+ disabledReason={disabledReason}+ hidePrivateAgents={!viewerIsOwner}+ label={t('goalDetail.mainAgentLabel')}+ placeholder={t('goalDetail.mainAgentUnassigned')}+ tooltip={t('goalDetail.mainAgent')}+ // An external runtime brings its own model, not a provider model.+ model={+ planner.agentId && !planner.heterogeneousType+ ? {+ lockedReason: planner.modelLocked ? t('goalDetail.modelFixed') : undefined,+ onChange: planner.changeModel,+ providerIds: planner.providerIds,+ ready: planner.modelReady,+ title: t('goalDetail.planningModel'),+ value: planner.model,+ }+ : undefined+ }+ onChange={planner.changeAgent}+ />+ {/* Tasks go to the main agent until one is named, so there is no executor+ to pick before the goal has a main agent. */}+ {planner.agentId && (+ <GoalAgentPill+ agentId={executor.agentId}+ disabled={disabled}+ disabledReason={disabledReason}+ hidePrivateAgents={!viewerIsOwner}+ label={t('goalDetail.taskAgentLabel')}+ placeholder={t('goalDetail.taskAgentFollowsMain')}+ tooltip={t('goalDetail.taskAgent')}+ model={+ planner.agentId && !executor.heterogeneousType+ ? {+ lockedReason: executor.modelLocked ? t('goalDetail.modelFixed') : undefined,+ onChange: executor.changeModel,+ ready: executor.modelReady,+ title: t('goalDetail.taskModel'),+ value: executor.model,+ }+ : undefined+ }+ onChange={executor.changeAgent}+ />+ )}+ </Flexbox>+ );+};++export default GoalAgentModelConfig;diff --git a/src/features/AgentGoals/GoalAgentPill.tsx b/src/features/AgentGoals/GoalAgentPill.tsxnew file mode 100644index 00000000000..e9288867a8f--- /dev/null+++ b/src/features/AgentGoals/GoalAgentPill.tsx@@ -0,0 +1,156 @@+import {+ ActionIcon,+ Block,+ cssVar,+ Flexbox,+ Popover,+ Text,+ Tooltip,+ useThemeMode,+} from '@lobehub/ui';+import { Settings2Icon } from 'lucide-react';++import AssigneeAgentSelector from '@/features/AgentTasks/features/AssigneeAgentSelector';+import AssigneeAvatar from '@/features/AgentTasks/features/AssigneeAvatar';+import { useAgentDisplayMeta } from '@/features/AgentTasks/shared/useAgentDisplayMeta';+import HeterogeneousTag from '@/features/HeterogeneousTag';+import ModelSelect from '@/features/ModelSelect';+import { useHomeStore } from '@/store/home';+import { homeAgentListSelectors } from '@/store/home/selectors';++type ModelConfig = { model: string; provider: string };++export interface GoalAgentPillProps {+ agentId?: string;+ disabled?: boolean;+ /** Why the pill is read-only, shown on hover instead of a generic reason. */+ disabledReason?: string;+ /**+ * Hide the viewer's private Agents: the goal belongs to someone else, whose+ * background runs could never reach them.+ */+ hidePrivateAgents?: boolean;+ /** Names the role, since the planner and executor pills sit side by side. */+ label: string;+ /** The model this role runs on, behind the pill's settings button. */+ model?: {+ /** Why the model cannot be changed here, when it cannot. */+ lockedReason?: string;+ onChange: (next: ModelConfig) => void;+ /** Restrict the choice to these providers. */+ providerIds?: string[];+ /** False while the agent's own model is still loading. */+ ready: boolean;+ title: string;+ value: ModelConfig;+ };+ onChange: (agentId: string | null) => void;+ /** Shown instead of an agent when the slot falls back to another one. */+ placeholder?: string;+ tooltip: string;+}++/**+ * One role on a goal — who plans it or who does its Tasks — as a labelled agent+ * picker, with the role's model behind a settings button when there is one.+ * Shared by the goal page and the create-goal form.+ */+const GoalAgentPill = ({+ agentId,+ disabled,+ disabledReason,+ hidePrivateAgents,+ label,+ model,+ onChange,+ placeholder,+ tooltip,+}: GoalAgentPillProps) => {+ const { isDarkMode } = useThemeMode();+ const meta = useAgentDisplayMeta(agentId);+ const heterogeneousType = useHomeStore(+ (s) => homeAgentListSelectors.getAgentById(agentId ?? '')(s)?.heterogeneousType,+ );++ return (+ <Block+ horizontal+ align={'center'}+ gap={2}+ padding={2}+ style={{ flex: 'none', maxWidth: '100%', minHeight: 32 }}+ variant={isDarkMode ? 'filled' : 'outlined'}+ >+ <AssigneeAgentSelector+ allowUnassigned={false}+ currentAgentId={agentId}+ disabled={disabled}+ disabledReason={disabledReason}+ taskVisibility={hidePrivateAgents ? 'public' : undefined}+ onChange={onChange}+ >+ <Tooltip title={tooltip}>+ <Block+ clickable+ horizontal+ align={'center'}+ gap={8}+ paddingBlock={2}+ paddingInline={8}+ style={{ minHeight: 26 }}+ variant={'borderless'}+ >+ <Text style={{ color: cssVar.colorTextDescription }}>{label}</Text>+ {agentId ? (+ <>+ <AssigneeAvatar agentId={agentId} size={20} />+ <Text ellipsis weight={500}>+ {meta?.title}+ </Text>+ <HeterogeneousTag type={heterogeneousType} />+ </>+ ) : (+ <Text style={{ color: cssVar.colorTextDescription }} weight={500}>+ {placeholder}+ </Text>+ )}+ </Block>+ </Tooltip>+ </AssigneeAgentSelector>+ {model &&+ (disabled || model.lockedReason || !model.ready ? (+ <ActionIcon+ disabled+ icon={Settings2Icon}+ loading={!disabled && !model.lockedReason && !model.ready}+ size={'small'}+ title={(disabled ? disabledReason : model.lockedReason) ?? model.title}+ />+ ) : (+ <Popover+ placement={'bottomLeft'}+ trigger={'click'}+ content={+ <Flexbox gap={8}>+ <Text fontSize={12} type={'secondary'}>+ {model.title}+ </Text>+ <ModelSelect+ initialWidth+ disabled={disabled}+ popupWidth={400}+ providerIds={model.providerIds}+ value={model.value}+ onChange={model.onChange}+ />+ </Flexbox>+ }+ >+ <ActionIcon icon={Settings2Icon} size={'small'} title={model.title} />+ </Popover>+ ))}+ </Block>+ );+};++export default GoalAgentPill;diff --git a/src/features/AgentGoals/GoalDetailPage.test.tsx b/src/features/AgentGoals/GoalDetailPage.test.tsxindex dfbeaa6d74c..3f540ad6dad 100644--- a/src/features/AgentGoals/GoalDetailPage.test.tsx+++ b/src/features/AgentGoals/GoalDetailPage.test.tsx@@ -38,6 +38,10 @@ vi.mock('@/store/goal', () => ({}),}));+vi.mock('@/store/serverConfig', () => ({+ useServerConfigStore: (selector: (s: any) => unknown) => selector({ featureFlags: {} }),+}));+vi.mock('@/store/chat', () => ({useChatStore: (selector: (s: any) => unknown) => selector({ clearPortalStack: vi.fn() }),}));@@ -57,6 +61,11 @@ vi.mock('@/store/global/selectors', () => ({systemStatusSelectors: { showLeftPanel: () => false },}));+// The main-agent picker follows a handover to the new agent's route.+vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({+ useWorkspaceAwareNavigate: () => vi.fn(),+}));+vi.mock('@/hooks/usePermission', () => ({ usePermission: () => ({ allowed: mocks.canEdit }) }));vi.mock('@/features/Portal/usePortalPanelWidth', () => ({diff --git a/src/features/AgentGoals/GoalDetailPage.tsx b/src/features/AgentGoals/GoalDetailPage.tsxindex 20758c00cda..f7658cde996 100644--- a/src/features/AgentGoals/GoalDetailPage.tsx+++ b/src/features/AgentGoals/GoalDetailPage.tsx@@ -26,6 +26,7 @@ import { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';import { goalSelectors, useGoalStore } from '@/store/goal';+import GoalAgentModelConfig from './GoalAgentModelConfig';import GoalChat from './GoalChat';import { GoalConversationContext } from './goalConversation';import GoalDetailActions from './GoalDetailActions';@@ -65,7 +66,7 @@ const AWAIT_RECORD_TIMEOUT = 10_000;const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {const { t } = useTranslation('chat');- const { allowed: canEdit } = usePermission('create_content');+ const { allowed: canEdit, reason: editBlockedReason } = usePermission('create_content');const useFetchGoalGraph = useGoalStore((s) => s.useFetchGoalGraph);const { error, isLoading, mutate } = useFetchGoalGraph(goalId);const snapshot = useGoalStore(goalSelectors.goalGraph(goalId));@@ -287,9 +288,12 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {button is only the control. */}{/* A draft is still being arranged: nothing has been dispatched,and starting it is the one explicit move into running. */}- {goal.status === 'draft' && (- <Flexbox horizontal align={'center'} gap={10} paddingBlock={'8px 0'}>- {canEdit && canStart && (+ <Flexbox horizontal align={'center'} gap={10} paddingBlock={'8px 0'} wrap={'wrap'}>+ {/* One control at a time: a draft is started, a moving goal is+ paused or resumed — the two states never overlap. */}+ {goal.status === 'draft' ? (+ canEdit &&+ canStart && (<Buttonicon={PlayIcon}loading={starting}@@ -307,14 +311,8 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {>{t('goalProcess.start')}</Button>- )}- <Text fontSize={12} type={'secondary'}>- {t('goalProcess.draft')}- </Text>- </Flexbox>- )}- {canPause && (- <Flexbox horizontal align={'center'} gap={10} paddingBlock={'8px 0'}>+ )+ ) : canPause ? (<Buttonicon={paused ? PlayIcon : PauseIcon}type={paused ? 'primary' : 'default'}@@ -322,13 +320,24 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {>{paused ? t('goalProcess.resume') : t('goalProcess.pause')}</Button>- {paused && (- <Text fontSize={12} type={'secondary'}>- {t('goalProcess.paused')}- </Text>- )}- </Flexbox>- )}+ ) : null}+ {/* Who plans the goal and who does its Tasks, next to the control+ that starts or pauses that work. Also the way to give an+ agent-less goal its main agent. */}+ <GoalAgentModelConfig+ disabled={!canEdit || !canStart}+ goalId={goal.id}+ routeAgentId={agentId}+ disabledReason={+ canEdit ? t('goalDetail.agentManagedByOwner') : editBlockedReason+ }+ />+ {goal.status === 'draft' && (+ <Text fontSize={12} type={'secondary'}>+ {t('goalProcess.draft')}+ </Text>+ )}+ </Flexbox>{goal.requirement && (<GoalRequirement goalId={goal.id} requirement={goal.requirement} />)}diff --git a/src/features/AgentGoals/useGoalAgentModel.test.ts b/src/features/AgentGoals/useGoalAgentModel.test.tsnew file mode 100644index 00000000000..3a8544a20f4--- /dev/null+++ b/src/features/AgentGoals/useGoalAgentModel.test.ts@@ -0,0 +1,308 @@+/**+ * @vitest-environment happy-dom+ */+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useGoalAgentModel } from './useGoalAgentModel';++const mocks = vi.hoisted(() => ({+ config: {} as {+ manager?: object;+ model?: string;+ provider?: string;+ taskAgentId?: string;+ taskModel?: string;+ taskProvider?: string;+ },+ loadedAgents: new Set(['agt_old', 'agt_exec']),+ lockedAgents: new Set<string>(),+ navigate: vi.fn(),+ memberPicks: {} as Record<string, string>,+ ownerId: undefined as string | undefined,+ preferenceLoading: false,+ relayEnabled: false,+ settingsReady: true,+ setGoalAgent: vi.fn(),+ setGoalModel: vi.fn(),+ setGoalTaskAgent: vi.fn(),+ setGoalTaskModel: vi.fn(),+}));++vi.mock('@/store/goal', () => ({+ goalSelectors: {+ goalGraph: () => () => ({+ goal: { agentId: 'agt_old', config: mocks.config, userId: mocks.ownerId },+ }),+ },+ useGoalStore: (selector: (s: any) => unknown) =>+ selector({+ setGoalAgent: mocks.setGoalAgent,+ setGoalModel: mocks.setGoalModel,+ setGoalTaskAgent: mocks.setGoalTaskAgent,+ setGoalTaskModel: mocks.setGoalTaskModel,+ }),+}));++vi.mock('@/store/agent', () => ({+ useAgentStore: (selector: (s: any) => unknown) =>+ selector({+ agentMap: Object.fromEntries([...mocks.loadedAgents].map((id) => [id, {}])),+ useHydrateAgentConfig: () => {},+ }),+}));++// The Agent row's own model, which a Task created for it is pinned to.+vi.mock('@/store/agent/selectors', () => ({+ agentByIdSelectors: {+ getAgentModelById: (id: string) => () => (id === 'agt_exec' ? 'deepseek-chat' : 'gpt-4o-mini'),+ getAgentModelProviderById: (id: string) => () => (id === 'agt_exec' ? 'deepseek' : 'openai'),+ },+}));++// The caller's effective model for an agent, as the chat model trigger reads it:+// a member's own pick (`memberPicks`) wins over the Agent row.+vi.mock('@/features/ChatInput/hooks/useAgentModelSelection', () => ({+ useAgentModelSelection: (id: string) => ({+ isPreferenceLoading: mocks.preferenceLoading,+ model: mocks.memberPicks[id] ?? (id === 'agt_exec' ? 'deepseek-chat' : 'gpt-4o-mini'),+ provider: mocks.memberPicks[id] ? 'google' : id === 'agt_exec' ? 'deepseek' : 'openai',+ selectionPolicy: mocks.lockedAgents.has(id) ? 'fixed' : 'member',+ usesWorkspaceMemberSelection: mocks.lockedAgents.has(id),+ }),+}));++// `ollama` is reached from this device; the others from the server.+vi.mock('@/store/aiInfra', () => ({+ aiProviderSelectors: { isProviderFetchOnClient: (id: string) => () => id === 'ollama' },+ useAiInfraStore: (selector: (s: any) => unknown) =>+ selector({ enabledChatModelList: [{ id: 'openai' }, { id: 'ollama' }, { id: 'google' }] }),+}));+vi.mock('@/store/serverConfig', () => ({+ useServerConfigStore: (selector: (s: any) => unknown) =>+ selector({ featureFlags: { enableLlmRelay: mocks.relayEnabled } }),+}));+vi.mock('@/store/home', () => ({ useHomeStore: (selector: (s: any) => unknown) => selector({}) }));+vi.mock('@/store/home/selectors', () => ({+ homeAgentListSelectors: { getAgentById: () => () => undefined },+}));+vi.mock('@/store/user', () => ({+ useUserStore: (selector: (s: any) => unknown) =>+ selector({ isUserStateInit: mocks.settingsReady }),+}));+vi.mock('@/store/user/selectors', () => ({+ authSelectors: { isLogin: () => true },+ systemAgentSelectors: { goal: () => ({ model: 'system-goal', provider: 'system-provider' }) },+ userProfileSelectors: { userId: () => 'user-viewer' },+}));+vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({+ useWorkspaceAwareNavigate: () => mocks.navigate,+}));++beforeEach(() => {+ vi.clearAllMocks();+ // Main-agent planning turns, so the planner falls back to the agent's model.+ mocks.config = { manager: {} };+ mocks.memberPicks = {};+ mocks.ownerId = undefined;+ mocks.settingsReady = true;+ mocks.loadedAgents = new Set(['agt_old', 'agt_exec']);+ mocks.lockedAgents = new Set();+ mocks.preferenceLoading = false;+ mocks.relayEnabled = false;+});++describe('useGoalAgentModel', () => {+ it('follows the goal to the new agent route after a handover', async () => {+ const { result } = renderHook(() =>+ useGoalAgentModel({ goalId: 'goal_1', routeAgentId: 'agt_old' }),+ );++ await act(() => result.current.planner.changeAgent('agt_new'));++ expect(mocks.setGoalAgent).toHaveBeenCalledWith('goal_1', 'agt_new');+ expect(mocks.navigate).toHaveBeenCalledWith('/agent/agt_new/goal/goal_1', { replace: true });+ });++ it('stays on an agent-less route after a handover', async () => {+ const { result } = renderHook(() => useGoalAgentModel({ goalId: 'goal_1' }));++ await act(() => result.current.planner.changeAgent('agt_new'));++ expect(mocks.setGoalAgent).toHaveBeenCalledWith('goal_1', 'agt_new');+ expect(mocks.navigate).not.toHaveBeenCalled();+ });++ it("shows the agent's own model until the goal overrides it", () => {+ const { result, rerender } = renderHook(() => useGoalAgentModel({ goalId: 'goal_1' }));+ expect(result.current.planner.model).toEqual({ model: 'gpt-4o-mini', provider: 'openai' });++ mocks.config = { manager: {}, model: 'gemini-3.8-flash', provider: 'google' };+ rerender();+ expect(result.current.planner.model).toEqual({ model: 'gemini-3.8-flash', provider: 'google' });+ });++ it("stores an override, and clears it when the agent's own model is picked", async () => {+ const { result } = renderHook(() => useGoalAgentModel({ goalId: 'goal_1' }));++ await act(() =>+ result.current.planner.changeModel({ model: 'gemini-3.8-flash', provider: 'google' }),+ );+ expect(mocks.setGoalModel).toHaveBeenLastCalledWith('goal_1', {+ model: 'gemini-3.8-flash',+ provider: 'google',+ });++ await act(() =>+ result.current.planner.changeModel({ model: 'gpt-4o-mini', provider: 'openai' }),+ );+ expect(mocks.setGoalModel).toHaveBeenLastCalledWith('goal_1', null);+ });++ it('routes Tasks to a dedicated executor, and back when the main agent is picked', async () => {+ const { result, rerender } = renderHook(() => useGoalAgentModel({ goalId: 'goal_1' }));++ await act(() => result.current.executor.changeAgent('agt_exec'));+ expect(mocks.setGoalTaskAgent).toHaveBeenLastCalledWith('goal_1', 'agt_exec');++ mocks.config = { taskAgentId: 'agt_exec' };+ rerender();+ expect(result.current.executor.agentId).toBe('agt_exec');++ await act(() => result.current.executor.changeAgent('agt_old'));+ expect(mocks.setGoalTaskAgent).toHaveBeenLastCalledWith('goal_1', null);+ });++ it('skips the write when the executor does not change', async () => {+ const { result } = renderHook(() => useGoalAgentModel({ goalId: 'goal_1' }));++ // No dedicated executor yet, so picking the main agent changes nothing.+ await act(() => result.current.executor.changeAgent('agt_old'));+ expect(mocks.setGoalTaskAgent).not.toHaveBeenCalled();+ });++ it("shows the executor's own model, falling back to the main agent's", () => {+ const { result, rerender } = renderHook(() => useGoalAgentModel({ goalId: 'goal_1' }));+ expect(result.current.executor.model).toEqual({ model: 'gpt-4o-mini', provider: 'openai' });++ mocks.config = { taskAgentId: 'agt_exec' };+ rerender();+ expect(result.current.executor.model).toEqual({ model: 'deepseek-chat', provider: 'deepseek' });++ mocks.config = {+ taskAgentId: 'agt_exec',+ taskModel: 'gemini-3.8-flash',+ taskProvider: 'google',+ };+ rerender();+ expect(result.current.executor.model).toEqual({+ model: 'gemini-3.8-flash',+ provider: 'google',+ });+ });++ it("stores a Task model, and clears it when the executor's own model is picked", async () => {+ mocks.config = { taskAgentId: 'agt_exec' };+ const { result } = renderHook(() => useGoalAgentModel({ goalId: 'goal_1' }));++ await act(() =>+ result.current.executor.changeModel({ model: 'gemini-3.8-flash', provider: 'google' }),+ );+ expect(mocks.setGoalTaskModel).toHaveBeenLastCalledWith('goal_1', {+ model: 'gemini-3.8-flash',+ provider: 'google',+ });++ await act(() =>+ result.current.executor.changeModel({ model: 'deepseek-chat', provider: 'deepseek' }),+ );+ expect(mocks.setGoalTaskModel).toHaveBeenLastCalledWith('goal_1', null);+ });++ it("does not store a pick before the agent's own model has loaded", async () => {+ mocks.loadedAgents = new Set();+ const { result } = renderHook(() => useGoalAgentModel({ goalId: 'goal_1' }));+ expect(result.current.planner.modelReady).toBe(false);++ await act(() =>+ result.current.planner.changeModel({ model: 'gpt-4o-mini', provider: 'openai' }),+ );+ expect(mocks.setGoalModel).not.toHaveBeenCalled();+ });++ it('locks the model of an Agent whose author fixed it', async () => {+ mocks.lockedAgents = new Set(['agt_old']);+ const { result } = renderHook(() => useGoalAgentModel({ goalId: 'goal_1' }));+ expect(result.current.planner.modelLocked).toBe(true);++ await act(() =>+ result.current.planner.changeModel({ model: 'gemini-3.8-flash', provider: 'google' }),+ );+ expect(mocks.setGoalModel).not.toHaveBeenCalled();+ });++ it('falls back to the system goal model when the coordinator plans the goal', async () => {+ mocks.config = {};+ const { result } = renderHook(() => useGoalAgentModel({ goalId: 'goal_1' }));+ expect(result.current.planner.model).toEqual({+ model: 'system-goal',+ provider: 'system-provider',+ });++ // The agent's own model is a real choice here, not the fallback.+ await act(() =>+ result.current.planner.changeModel({ model: 'gpt-4o-mini', provider: 'openai' }),+ );+ expect(mocks.setGoalModel).toHaveBeenLastCalledWith('goal_1', {+ model: 'gpt-4o-mini',+ provider: 'openai',+ });++ await act(() =>+ result.current.planner.changeModel({ model: 'system-goal', provider: 'system-provider' }),+ );+ expect(mocks.setGoalModel).toHaveBeenLastCalledWith('goal_1', null);+ });++ it('waits for user settings before accepting a coordinator planning model', async () => {+ mocks.config = {};+ mocks.settingsReady = false;+ const { result } = renderHook(() => useGoalAgentModel({ goalId: 'goal_1' }));+ expect(result.current.planner.modelReady).toBe(false);+ });++ it("plans on the member's own pick but pins Tasks to the Agent row's model", () => {+ mocks.memberPicks = { agt_old: 'gemini-member' };+ const { result } = renderHook(() => useGoalAgentModel({ goalId: 'goal_1' }));++ expect(result.current.planner.model).toEqual({ model: 'gemini-member', provider: 'google' });+ expect(result.current.executor.model).toEqual({ model: 'gpt-4o-mini', provider: 'openai' });+ });++ it("keeps an admin's pick on someone else's goal instead of clearing it", async () => {+ // The owner's own fallback is not visible to the admin viewing the goal.+ mocks.ownerId = 'user-owner';+ const { result } = renderHook(() => useGoalAgentModel({ goalId: 'goal_1' }));+ expect(result.current.viewerIsOwner).toBe(false);++ await act(() =>+ result.current.planner.changeModel({ model: 'gpt-4o-mini', provider: 'openai' }),+ );+ expect(mocks.setGoalModel).toHaveBeenLastCalledWith('goal_1', {+ model: 'gpt-4o-mini',+ provider: 'openai',+ });+ });++ it('offers the planner no device-only provider while calls are relayed', () => {+ const { result, rerender } = renderHook(() => useGoalAgentModel({ goalId: 'goal_1' }));+ // Without the relay, every provider runs on the server.+ expect(result.current.planner.providerIds).toBeUndefined();++ mocks.relayEnabled = true;+ rerender();+ expect(result.current.planner.providerIds).toEqual(['openai', 'google']);+ // Only planning is restricted.+ expect(result.current.executor).not.toHaveProperty('providerIds');+ });+});diff --git a/src/features/AgentGoals/useGoalAgentModel.ts b/src/features/AgentGoals/useGoalAgentModel.tsnew file mode 100644index 00000000000..e6ffe578553--- /dev/null+++ b/src/features/AgentGoals/useGoalAgentModel.ts@@ -0,0 +1,179 @@+import { toast } from '@lobehub/ui';+import { useShallow } from 'zustand/react/shallow';++import { useAgentModelSelection } from '@/features/ChatInput/hooks/useAgentModelSelection';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { useAgentStore } from '@/store/agent';+import { agentByIdSelectors } from '@/store/agent/selectors';+import { aiProviderSelectors, useAiInfraStore } from '@/store/aiInfra';+import { goalSelectors, useGoalStore } from '@/store/goal';+import { useHomeStore } from '@/store/home';+import { homeAgentListSelectors } from '@/store/home/selectors';+import { useServerConfigStore } from '@/store/serverConfig';+import { useUserStore } from '@/store/user';+import { authSelectors, systemAgentSelectors, userProfileSelectors } from '@/store/user/selectors';++type ModelConfig = { model: string; provider: string };++interface UseGoalAgentModelParams {+ goalId: string;+ /**+ * The agent the page route is scoped to. The goal leaves that agent's list when+ * handed over, so the page follows it to the new agent's route.+ */+ routeAgentId?: string;+}++/**+ * An agent's models as the goal's two slots fall back to them: `effective` is+ * what an agent run uses for the current caller (a Workspace member's own pick+ * on a shared Agent included); `shared` is the Agent row's own model, which is+ * what a Task created for it is pinned to. Hydrates the agent's config, since+ * the surrounding page may be about another agent.+ */+const useAgentOwnModel = (agentId?: string) => {+ const isLogin = useUserStore(authSelectors.isLogin);+ const useHydrateAgentConfig = useAgentStore((s) => s.useHydrateAgentConfig);+ useHydrateAgentConfig(isLogin, agentId ?? '');+ const loaded = useAgentStore((s) => !!agentId && !!s.agentMap[agentId]);+ const selection = useAgentModelSelection(agentId ?? '');+ const sharedModel = useAgentStore((s) => agentByIdSelectors.getAgentModelById(agentId ?? '')(s));+ const sharedProvider = useAgentStore((s) =>+ agentByIdSelectors.getAgentModelProviderById(agentId ?? '')(s),+ );+ const heterogeneousType = useHomeStore(+ (s) => homeAgentListSelectors.getAgentById(agentId ?? '')(s)?.heterogeneousType,+ );+ return {+ effective: { model: selection.model, provider: selection.provider },+ heterogeneousType,+ // The author pinned this shared Agent's model, so only they or an admin+ // may override it — the server refuses everyone else.+ locked: selection.usesWorkspaceMemberSelection && selection.selectionPolicy === 'fixed',+ // Until the agent and the caller's preference load, the fallback is a+ // repository default, and a pick compared against it would be misread.+ ready: loaded && !selection.isPreferenceLoading,+ shared: { model: sharedModel, provider: sharedProvider },+ };+};++/**+ * Who plans the goal and who does its Tasks, each with the model it runs on:+ * what the pickers show and what a pick writes. Each model falls back to what+ * that role would run on anyway until the goal overrides it.+ */+export const useGoalAgentModel = ({ goalId, routeAgentId }: UseGoalAgentModelParams) => {+ const navigate = useWorkspaceAwareNavigate();+ const graph = goalSelectors.goalGraph(goalId);+ const agentId = useGoalStore((s) => graph(s)?.goal.agentId) ?? undefined;+ // Unset means the main agent does the goal's Tasks itself.+ const taskAgentId = useGoalStore((s) => graph(s)?.goal.config?.taskAgentId);+ const planningModel = useGoalStore((s) => graph(s)?.goal.config?.model);+ const planningProvider = useGoalStore((s) => graph(s)?.goal.config?.provider);+ const taskModel = useGoalStore((s) => graph(s)?.goal.config?.taskModel);+ const taskProvider = useGoalStore((s) => graph(s)?.goal.config?.taskProvider);+ const setGoalAgent = useGoalStore((s) => s.setGoalAgent);+ const setGoalModel = useGoalStore((s) => s.setGoalModel);+ const setGoalTaskAgent = useGoalStore((s) => s.setGoalTaskAgent);+ const setGoalTaskModel = useGoalStore((s) => s.setGoalTaskModel);+ const managed = useGoalStore((s) => !!graph(s)?.goal.config?.manager);+ const ownerId = useGoalStore((s) => graph(s)?.goal.userId);+ const viewerId = useUserStore(userProfileSelectors.userId);+ // Background advances run as the goal's owner, with the owner's model+ // preference and system goal model — which an admin viewing someone else's+ // goal cannot see. Their planner fallback here is their own, so a pick that+ // matches it must be kept, not cleared into the owner's unknown default.+ const viewerIsOwner = !ownerId || ownerId === viewerId;+ const systemGoalModel = useUserStore(systemAgentSelectors.goal);+ // The system goal model lives in user settings; before they load it reads as+ // the built-in default.+ const settingsReady = useUserStore((s) => s.isUserStateInit);++ const planner = useAgentOwnModel(agentId);+ const executor = useAgentOwnModel(taskAgentId ?? agentId);+ // What each slot runs on without a goal override — the same fallback the+ // server applies, so picking it clears the override instead of pinning it.+ // Main-agent turns run the agent with no explicit model; the coordinator's+ // own planning uses the system goal model; a Task is pinned to the Agent row.+ const plannerFallback = managed ? planner.effective : systemGoalModel;+ const executorFallback = executor.shared;+ const plannerReady = planner.ready && (managed || settingsReady);+ // Planning advances in the background with no device attached, so a provider+ // relayed to this device could not serve it; the server refuses it as well.+ const relayEnabled = useServerConfigStore((s) => !!s.featureFlags.enableLlmRelay);+ const plannerProviderIds = useAiInfraStore(+ useShallow((s) =>+ relayEnabled+ ? (s.enabledChatModelList ?? [])+ .filter((provider) => !aiProviderSelectors.isProviderFetchOnClient(provider.id)(s))+ .map((provider) => provider.id)+ : undefined,+ ),+ );++ const run = async (write: () => Promise<void>) => {+ try {+ await write();+ } catch (error) {+ toast.error((error as Error).message);+ }+ };++ // Picking the agent's own model is the same as not overriding it, and keeps+ // the slot following that agent when its model changes later.+ const overrideOf = (next: ModelConfig, own: { model?: string; provider?: string }) =>+ next.model === own.model && next.provider === own.provider ? null : next;++ const changeAgent = (next: string | null) =>+ run(async () => {+ if (!next) return;+ await setGoalAgent(goalId, next);+ if (routeAgentId && routeAgentId !== next)+ navigate(`/agent/${next}/goal/${goalId}`, { replace: true });+ });++ const changeTaskAgent = (next: string | null) =>+ run(async () => {+ // Naming the main agent is the same as clearing: it does its own Tasks.+ const nextExecutor = next && next !== agentId ? next : null;+ if (nextExecutor === (taskAgentId ?? null)) return;+ await setGoalTaskAgent(goalId, nextExecutor);+ });++ return {+ viewerIsOwner,+ executor: {+ agentId: taskAgentId,+ changeAgent: changeTaskAgent,+ changeModel: (next: ModelConfig) =>+ run(async () => {+ if (!executor.ready || executor.locked) return;+ await setGoalTaskModel(goalId, overrideOf(next, executorFallback));+ }),+ heterogeneousType: executor.heterogeneousType,+ modelLocked: executor.locked,+ modelReady: executor.ready,+ model: {+ model: taskModel || executorFallback.model || '',+ provider: taskProvider || executorFallback.provider || '',+ },+ },+ planner: {+ agentId,+ changeAgent,+ changeModel: (next: ModelConfig) =>+ run(async () => {+ if (!plannerReady || planner.locked) return;+ await setGoalModel(goalId, viewerIsOwner ? overrideOf(next, plannerFallback) : next);+ }),+ heterogeneousType: planner.heterogeneousType,+ modelLocked: planner.locked,+ modelReady: plannerReady,+ providerIds: plannerProviderIds,+ model: {+ model: planningModel || plannerFallback.model || '',+ provider: planningProvider || plannerFallback.provider || '',+ },+ },+ };+};diff --git a/src/features/AgentTasks/features/AssigneeAgentSelector.tsx b/src/features/AgentTasks/features/AssigneeAgentSelector.tsxindex f29228a7abd..905cd3335a9 100644--- a/src/features/AgentTasks/features/AssigneeAgentSelector.tsx+++ b/src/features/AgentTasks/features/AssigneeAgentSelector.tsx@@ -20,9 +20,13 @@ import { homeAgentListSelectors } from '@/store/home/selectors';import { useTaskStore } from '@/store/task';interface AssigneeAgentSelectorProps {+ /** Offer the "unassigned" option; off where an owner is required. */+ allowUnassigned?: boolean;children: ReactNode;currentAgentId?: string | null;disabled?: boolean;+ /** Why `disabled` holds; defaults to the running-Task explanation. */+ disabledReason?: string;onChange?: (agentId: string | null) => void;taskIdentifier?: string;taskVisibility?: 'private' | 'public' | null;@@ -81,7 +85,16 @@ const triggerStyle: CSSProperties = {const blockedContentStyle: CSSProperties = { display: 'contents', pointerEvents: 'none' };const AssigneeAgentSelector = memo<AssigneeAgentSelectorProps>(- ({ children, currentAgentId, disabled, onChange, taskIdentifier, taskVisibility }) => {+ ({+ allowUnassigned = true,+ children,+ currentAgentId,+ disabled,+ disabledReason,+ onChange,+ taskIdentifier,+ taskVisibility,+ }) => {const { t } = useTranslation(['chat', 'common', 'topic']);const { allowed: canEditTask, reason } = usePermission('create_content');const [key, setKey] = useState(0);@@ -154,7 +167,8 @@ const AssigneeAgentSelector = memo<AssigneeAgentSelectorProps>();const unassignedLabel = t('taskList.unassigned', { ns: 'chat' });- const showUnassigned = !query || unassignedLabel.toLowerCase().includes(query);+ const showUnassigned =+ allowUnassigned && (!query || unassignedLabel.toLowerCase().includes(query));const flatOptions = useMemo<AgentOption[]>(() => [...(showUnassigned ? [{ key: 'unassigned', kind: 'unassigned' } as const] : []),@@ -281,7 +295,11 @@ const AssigneeAgentSelector = memo<AssigneeAgentSelectorProps>(const blocked = disabled || !canEditTask;const trigger = blocked ? (- <Tooltip title={disabled ? t('taskDetail.reassignDisabled', { ns: 'chat' }) : reason}>+ <Tooltip+ title={+ disabled ? (disabledReason ?? t('taskDetail.reassignDisabled', { ns: 'chat' })) : reason+ }+ ><divstyle={{ ...triggerStyle, cursor: 'not-allowed', opacity: 0.5 }}onClick={(event) => event.stopPropagation()}diff --git a/src/services/goal.ts b/src/services/goal.tsindex af7e30e9f0c..9d2edff6b24 100644--- a/src/services/goal.ts+++ b/src/services/goal.ts@@ -12,8 +12,13 @@ import { oneShotRelay } from '@/services/llmRelay';import { useUserStore } from '@/store/user';import { systemAgentSelectors } from '@/store/user/selectors';-/** The `goal` system agent's provider: advancing a goal decomposes and explores on it. */-const goalModelProvider = () => systemAgentSelectors.goal(useUserStore.getState()).provider;+/**+ * The provider a goal's planning runs on: the goal's own planning-model pick+ * when it has one, else the `goal` system agent's — the same choice the server+ * makes, so a device-only provider is relayed back to this tab either way.+ */+const goalModelProvider = (planningProvider?: string) =>+ planningProvider || systemAgentSelectors.goal(useUserStore.getState()).provider;export interface GoalListParams {agentId?: string;@@ -94,16 +99,19 @@ class GoalService {* on the `goal` model inside this request; a model only this device reaches* is relayed back to this tab (one-shot relay).*/- advance = async (id: string): Promise<GoalTickResult & { ticks: number }> => {- const { data } = await oneShotRelay.run(goalModelProvider(), (relay) =>+ advance = async (+ id: string,+ planningProvider?: string,+ ): Promise<GoalTickResult & { ticks: number }> => {+ const { data } = await oneShotRelay.run(goalModelProvider(planningProvider), (relay) =>lambdaClient.goal.advance.mutate({ id }, withLlmRelay(relay)),);return data;};/** Advance the graph by exactly one coordinator step. Relayed like `advance`. */- tick = async (id: string): Promise<GoalTickResult> => {- const { data } = await oneShotRelay.run(goalModelProvider(), (relay) =>+ tick = async (id: string, planningProvider?: string): Promise<GoalTickResult> => {+ const { data } = await oneShotRelay.run(goalModelProvider(planningProvider), (relay) =>lambdaClient.goal.tick.mutate({ id }, withLlmRelay(relay)),);return data;@@ -147,6 +155,22 @@ class GoalService {resolution?: string;}) => lambdaClient.goal.decide.mutate(params);+ /** Hand the goal to another agent; with no executor, its unfinished Tasks follow. */+ setAgent = async (id: string, agentId: string) =>+ lambdaClient.goal.setAgent.mutate({ agentId, id });++ /** Route the goal's Tasks to a dedicated executor; `null` hands them back to the goal agent. */+ setTaskAgent = async (id: string, agentId: string | null) =>+ lambdaClient.goal.setTaskAgent.mutate({ agentId, id });++ /** The model the goal agent plans with; `null` falls back to the agent's own. */+ setModel = async (id: string, modelConfig: { model: string; provider: string } | null) =>+ lambdaClient.goal.setModel.mutate({ id, modelConfig });++ /** The model the goal's Tasks run on; `null` falls back to their executor's own. */+ setTaskModel = async (id: string, modelConfig: { model: string; provider: string } | null) =>+ lambdaClient.goal.setTaskModel.mutate({ id, modelConfig });+setBudget = async (params: {deadline?: string | null;id: string;diff --git a/src/store/goal/action.test.ts b/src/store/goal/action.test.tsindex 37844a77fcc..78e2ed929cc 100644--- a/src/store/goal/action.test.ts+++ b/src/store/goal/action.test.ts@@ -20,7 +20,13 @@ vi.mock('@/libs/swr/useCacheScope', () => ({}));vi.mock('@/services/goal', () => ({- goalService: { delete: vi.fn(), getGraph: vi.fn(), list: vi.fn() },+ goalService: {+ advance: vi.fn(),+ delete: vi.fn(),+ getGraph: vi.fn(),+ list: vi.fn(),+ tick: vi.fn(),+ },}));const SCOPE = 'user-1:personal';@@ -356,4 +362,27 @@ describe('GoalAction', () => {expect(list?.goals.map((item) => item.goal.id)).toEqual(['goal-2']);expect(list?.total).toBe(1);});++ it('relays the provider the goal actually plans on when advancing it', async () => {+ vi.mocked(goalService.advance).mockResolvedValue({ ticks: 1 } as never);+ vi.mocked(goalService.tick).mockResolvedValue({} as never);+ useGoalStore.setState({+ goalGraphById: {+ 'goal-1': graphWith('running', {+ goal: {+ config: { model: 'local-llm', provider: 'ollama' },+ id: 'goal-1',+ status: 'running',+ title: 'Goal',+ },+ }),+ },+ });++ await useGoalStore.getState().advanceGoal('goal-1');+ await useGoalStore.getState().tickGoal('goal-1');++ expect(goalService.advance).toHaveBeenCalledWith('goal-1', 'ollama');+ expect(goalService.tick).toHaveBeenCalledWith('goal-1', 'ollama');+ });});diff --git a/src/store/goal/action.ts b/src/store/goal/action.tsindex 92bc506d73d..bdb0cbe843b 100644--- a/src/store/goal/action.ts+++ b/src/store/goal/action.ts@@ -331,6 +331,42 @@ export class GoalActionImpl {await this.refreshGoalGraph(goalId);};+ /**+ * The goal moves to the new agent's goal list, so both agents' lists re-read+ * along with the page.+ */+ setGoalAgent = async (goalId: string, agentId: string): Promise<void> => {+ await goalService.setAgent(goalId, agentId);+ await Promise.all([+ this.refreshGoalGraph(goalId),+ revalidateReplica(goalListResource),+ revalidateReplica(homeGoalListResource),+ ]);+ };++ /** Unfinished Tasks move with the executor, so their rows on the page re-read too. */+ setGoalTaskAgent = async (goalId: string, agentId: string | null): Promise<void> => {+ await goalService.setTaskAgent(goalId, agentId);+ await this.refreshGoalGraph(goalId);+ };++ setGoalModel = async (+ goalId: string,+ modelConfig: { model: string; provider: string } | null,+ ): Promise<void> => {+ await goalService.setModel(goalId, modelConfig);+ await this.refreshGoalGraph(goalId);+ };++ /** Unfinished Tasks switch model with it, so their rows re-read too. */+ setGoalTaskModel = async (+ goalId: string,+ modelConfig: { model: string; provider: string } | null,+ ): Promise<void> => {+ await goalService.setTaskModel(goalId, modelConfig);+ await this.refreshGoalGraph(goalId);+ };+updateGoalRequirement = async (goalId: string, requirement: string): Promise<void> => {await goalService.updateRequirement(goalId, requirement);await this.refreshGoalGraph(goalId);@@ -341,15 +377,19 @@ export class GoalActionImpl {* own afterwards as its Work Tasks settle, so this is a nudge rather than the* loop the surface used to hold open.*/+ /** The goal's own planning-model provider, so the relay covers the model it plans on. */+ #planningProvider = (goalId: string) =>+ this.#get().goalGraphById[goalId]?.goal.config?.provider ?? undefined;+advanceGoal = async (goalId: string): Promise<GoalTickResult> => {- const result = await goalService.advance(goalId);+ const result = await goalService.advance(goalId, this.#planningProvider(goalId));await this.refreshGoalGraph(goalId);return result;};/** Exactly one coordinator step, for a caller that wants to inspect a single move. */tickGoal = async (goalId: string): Promise<GoalTickResult> => {- const result = await goalService.tick(goalId);+ const result = await goalService.tick(goalId, this.#planningProvider(goalId));await this.refreshGoalGraph(goalId);return result;};