🤯 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
♻️ refactor(task): snapshot agent model into task.config at create time (#14670)
Arvin Xue51c38c182c7
diff --git a/packages/database/src/models/__tests__/agent.test.ts b/packages/database/src/models/__tests__/agent.test.tsindex 09c10f0ae16..4bff53e3df8 100644--- a/packages/database/src/models/__tests__/agent.test.ts+++ b/packages/database/src/models/__tests__/agent.test.ts@@ -186,6 +186,51 @@ describe('AgentModel', () => {});});+ describe('getAgentModelConfig', () => {+ it('returns model + provider when both are configured', async () => {+ const agentId = 'snap-agent-1';+ await serverDB+ .insert(agents)+ .values({ id: agentId, model: 'claude-sonnet-4-6', provider: 'anthropic', userId });++ const result = await agentModel.getAgentModelConfig(agentId);++ expect(result).toEqual({ model: 'claude-sonnet-4-6', provider: 'anthropic' });+ });++ it('resolves by slug when id does not match', async () => {+ const agentId = 'snap-agent-by-slug';+ const slug = 'snap-slug';+ await serverDB+ .insert(agents)+ .values({ id: agentId, model: 'gpt-4o', provider: 'openai', slug, userId });++ const result = await agentModel.getAgentModelConfig(slug);++ expect(result).toEqual({ model: 'gpt-4o', provider: 'openai' });+ });++ it('returns null when model or provider is missing', async () => {+ const agentId = 'snap-agent-incomplete';+ await serverDB.insert(agents).values({ id: agentId, model: 'gpt-4o', userId });++ const result = await agentModel.getAgentModelConfig(agentId);++ expect(result).toBeNull();+ });++ it('does not leak across users', async () => {+ const agentId = 'snap-agent-other-user';+ await serverDB+ .insert(agents)+ .values({ id: agentId, model: 'gpt-4o', provider: 'openai', userId: userId2 });++ const result = await agentModel.getAgentModelConfig(agentId);++ expect(result).toBeNull();+ });+ });+describe('getAgentConfig', () => {it('should find agent by ID', async () => {const agentId = 'test-agent-by-id';diff --git a/packages/database/src/models/agent.ts b/packages/database/src/models/agent.tsindex 0e417b15482..f745784137b 100644--- a/packages/database/src/models/agent.ts+++ b/packages/database/src/models/agent.ts@@ -47,6 +47,29 @@ export class AgentModel {return rows.length > 0;};+ /**+ * Lightweight lookup of an agent's currently-configured model + provider,+ * used to snapshot the model into a task config so later changes to the+ * agent's default model don't silently affect already-created tasks.+ * Returns null when the agent has no model/provider set, or the agent+ * cannot be found for this user.+ */+ getAgentModelConfig = async (+ idOrSlug: string,+ ): Promise<{ model: string; provider: string } | null> => {+ const rows = await this.db+ .select({ model: agents.model, provider: agents.provider })+ .from(agents)+ .where(+ and(eq(agents.userId, this.userId), or(eq(agents.id, idOrSlug), eq(agents.slug, idOrSlug))),+ )+ .limit(1);++ const row = rows[0];+ if (!row || !row.model || !row.provider) return null;+ return { model: row.model, provider: row.provider };+ };+/*** Query non-virtual agents with optional keyword filter.* Returns minimal agent info (id, title, description, avatar, backgroundColor).diff --git a/src/server/routers/lambda/__tests__/integration/task.integration.test.ts b/src/server/routers/lambda/__tests__/integration/task.integration.test.tsindex ec8d67214a8..d30e7a68c37 100644--- a/src/server/routers/lambda/__tests__/integration/task.integration.test.ts+++ b/src/server/routers/lambda/__tests__/integration/task.integration.test.ts@@ -800,4 +800,86 @@ describe('Task Router Integration', () => {expect(mockExecAgent).toHaveBeenCalled();});});++ describe('agent model snapshot', () => {+ const setAgentModel = async (model: string | null, provider: string | null) => {+ const { agents } = await import('@/database/schemas');+ const { eq } = await import('drizzle-orm');+ await serverDB.update(agents).set({ model, provider }).where(eq(agents.id, testAgentId));+ };++ it('snapshots the agent model into task.config at create time', async () => {+ await setAgentModel('claude-sonnet-4-6', 'anthropic');++ const task = await caller.create({+ assigneeAgentId: testAgentId,+ instruction: 'Snapshot at create',+ });++ expect(task.data.config).toMatchObject({+ model: 'claude-sonnet-4-6',+ provider: 'anthropic',+ });+ });++ it('skips snapshot when the agent has no model configured', async () => {+ await setAgentModel(null, null);++ const task = await caller.create({+ assigneeAgentId: testAgentId,+ instruction: 'No snapshot when agent has none',+ });++ expect(task.data.config).toEqual({});+ });++ it('skips snapshot when the task has no assignee', async () => {+ await setAgentModel('claude-sonnet-4-6', 'anthropic');++ const task = await caller.create({ instruction: 'Unassigned task' });++ expect(task.data.config).toEqual({});+ });++ it('preserves the snapshotted model when the agent default changes later', async () => {+ await setAgentModel('claude-sonnet-4-6', 'anthropic');+ const task = await caller.create({+ assigneeAgentId: testAgentId,+ instruction: 'Snapshot then drift',+ });++ // User flips the agent to an expensive chat model.+ await setAgentModel('gpt-5.4-pro', 'openai');++ await caller.run({ id: task.data.id });++ expect(mockExecAgent).toHaveBeenCalledWith(+ expect.objectContaining({ model: 'claude-sonnet-4-6', provider: 'anthropic' }),+ );+ });++ it('backfills the snapshot on first run for tasks without config.model', async () => {+ // Simulate a task that pre-dates this fix: no snapshot yet.+ await setAgentModel(null, null);+ const task = await caller.create({+ assigneeAgentId: testAgentId,+ instruction: 'Pre-fix task',+ });+ expect(task.data.config).toEqual({});++ // User later configures the agent model.+ await setAgentModel('claude-sonnet-4-6', 'anthropic');++ await caller.run({ id: task.data.id });++ const after = await caller.find({ id: task.data.id });+ expect(after.data.config).toMatchObject({+ model: 'claude-sonnet-4-6',+ provider: 'anthropic',+ });+ expect(mockExecAgent).toHaveBeenCalledWith(+ expect.objectContaining({ model: 'claude-sonnet-4-6', provider: 'anthropic' }),+ );+ });+ });});diff --git a/src/server/routers/lambda/task.ts b/src/server/routers/lambda/task.tsindex 5f2eb858a80..d87fec8861d 100644--- a/src/server/routers/lambda/task.ts+++ b/src/server/routers/lambda/task.ts@@ -7,14 +7,9 @@ import { AgentModel } from '@/database/models/agent';import { BriefModel } from '@/database/models/brief';import { TaskModel } from '@/database/models/task';import { TaskTopicModel } from '@/database/models/taskTopic';-import { TopicModel } from '@/database/models/topic';import { authedProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';-import { AiAgentService } from '@/server/services/aiAgent';import { TaskService } from '@/server/services/task';-import { TaskGraphService } from '@/server/services/taskGraph';-import { TaskLifecycleService } from '@/server/services/taskLifecycle';-import { TaskReviewService } from '@/server/services/taskReview';import { TaskRunnerService } from '@/server/services/taskRunner';const taskProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {@@ -22,12 +17,9 @@ const taskProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {return opts.next({ctx: {agentModel: new AgentModel(ctx.serverDB, ctx.userId),- briefModel: new BriefModel(ctx.serverDB, ctx.userId),- taskLifecycle: new TaskLifecycleService(ctx.serverDB, ctx.userId),taskModel: new TaskModel(ctx.serverDB, ctx.userId),taskService: new TaskService(ctx.serverDB, ctx.userId),taskTopicModel: new TaskTopicModel(ctx.serverDB, ctx.userId),- topicModel: new TopicModel(ctx.serverDB, ctx.userId),},});});@@ -306,26 +298,7 @@ export const taskRouter = router({.input(z.object({ topicId: z.string() })).mutation(async ({ input, ctx }) => {try {- const target = await ctx.taskTopicModel.findByTopicId(input.topicId);- if (!target) {- throw new TRPCError({ code: 'NOT_FOUND', message: 'Topic not found.' });- }-- if (target.status !== 'running') {- throw new TRPCError({- code: 'BAD_REQUEST',- message: `Topic is not running (current status: ${target.status}).`,- });- }-- if (target.operationId) {- const aiAgentService = new AiAgentService(ctx.serverDB, ctx.userId);- await aiAgentService.interruptTask({ operationId: target.operationId });- }-- await ctx.taskTopicModel.updateStatus(target.taskId, input.topicId, 'canceled');- await ctx.taskModel.updateStatus(target.taskId, 'paused');-+ await ctx.taskService.cancelTopic(input.topicId);return { message: 'Topic canceled', success: true };} catch (error) {if (error instanceof TRPCError) throw error;@@ -342,19 +315,7 @@ export const taskRouter = router({.input(z.object({ topicId: z.string() })).mutation(async ({ input, ctx }) => {try {- const target = await ctx.taskTopicModel.findByTopicId(input.topicId);- if (!target) {- throw new TRPCError({ code: 'NOT_FOUND', message: 'Topic not found.' });- }-- if (target.status === 'running' && target.operationId) {- const aiAgentService = new AiAgentService(ctx.serverDB, ctx.userId);- await aiAgentService.interruptTask({ operationId: target.operationId });- }-- await ctx.taskTopicModel.remove(target.taskId, input.topicId);- await ctx.topicModel.delete(input.topicId);-+ await ctx.taskService.deleteTopic(input.topicId);return { message: 'Topic deleted', success: true };} catch (error) {if (error instanceof TRPCError) throw error;@@ -369,17 +330,7 @@ export const taskRouter = router({create: taskProcedure.input(createSchema).mutation(async ({ input, ctx }) => {try {- const model = ctx.taskModel;- await assertAssigneeAgentBelongsToUser(ctx.agentModel, input.assigneeAgentId);-- // Resolve parentTaskId if it's an identifier- const createData = { ...input };- if (createData.parentTaskId) {- const parent = await resolveOrThrow(model, createData.parentTaskId);- createData.parentTaskId = parent.id;- }-- const task = await model.create(createData);+ const task = await ctx.taskService.createTask(input);return { data: task, message: 'Task created', success: true };} catch (error) {if (error instanceof TRPCError) throw error;@@ -915,59 +866,7 @@ export const taskRouter = router({).mutation(async ({ input, ctx }) => {try {- const model = ctx.taskModel;- const task = await resolveOrThrow(model, input.id);-- const reviewConfig = model.getReviewConfig(task);- if (!reviewConfig?.enabled) {- throw new TRPCError({- code: 'BAD_REQUEST',- message: 'Review is not enabled for this task',- });- }-- // Use provided content or try to get from latest topic- const content = input.content;- if (!content) {- throw new TRPCError({- code: 'BAD_REQUEST',- message:- 'Content is required for review. Pass --content or run after a topic completes.',- });- }-- // Determine which topic to attach the review to- const topicId = input.topicId || task.currentTopicId;-- // Get current iteration count for this topic- let iteration = 1;- if (topicId) {- const topics = await ctx.taskTopicModel.findByTaskId(task.id);- const target = topics.find((t) => t.topicId === topicId);- if (target?.reviewIteration) {- iteration = target.reviewIteration + 1;- }- }-- const reviewService = new TaskReviewService(ctx.serverDB, ctx.userId);- const result = await reviewService.review({- content,- iteration,- judge: reviewConfig.judge,- rubrics: reviewConfig.rubrics,- taskName: task.name || task.identifier,- });-- // Save review result to task_topics- if (topicId) {- await ctx.taskTopicModel.updateReview(task.id, topicId, {- iteration,- passed: result.passed,- score: result.overallScore,- scores: result.rubricResults,- });- }-+ const result = await ctx.taskService.runReview(input);return { data: result, success: true };} catch (error) {if (error instanceof TRPCError) throw error;@@ -1029,9 +928,7 @@ export const taskRouter = router({previewSubtaskLayers: taskProcedure.input(idInput).query(async ({ input, ctx }) => {try {- const parent = await resolveOrThrow(ctx.taskModel, input.id);- const graph = new TaskGraphService(ctx.serverDB, ctx.userId);- const { plan } = await graph.planForParent(parent.id);+ const plan = await ctx.taskService.previewSubtaskLayers(input.id);return { data: plan, success: true };} catch (error) {if (error instanceof TRPCError) throw error;@@ -1046,55 +943,8 @@ export const taskRouter = router({runReadySubtasks: taskProcedure.input(idInput).mutation(async ({ input, ctx }) => {try {- const parent = await resolveOrThrow(ctx.taskModel, input.id);- const graph = new TaskGraphService(ctx.serverDB, ctx.userId);- const { descendants, plan } = await graph.planForParent(parent.id);-- if (plan.layers.length === 0) {- return {- data: {- kickedOff: [],- plan,- skipped: { reason: 'nothing-runnable' as const },- },- success: true,- };- }-- // Layer 0 is the only wave we kick off here. Subsequent layers fire- // automatically through `TaskRunnerService.cascadeOnCompletion` as- // each upstream finishes.- const firstLayer = plan.layers[0];- const identifierToId = new Map(descendants.map((d) => [d.identifier, d.id]));- const runner = new TaskRunnerService(ctx.serverDB, ctx.userId);-- const kickedOff: string[] = [];- const failed: { error: string; identifier: string }[] = [];-- const settled = await Promise.allSettled(- firstLayer.map(async (identifier) => {- const id = identifierToId.get(identifier);- if (!id) throw new Error(`Subtask ${identifier} not found`);- await runner.runTask({ taskId: id });- return identifier;- }),- );-- for (const [index, result] of settled.entries()) {- const identifier = firstLayer[index];- if (result.status === 'fulfilled') {- kickedOff.push(identifier);- } else {- const message =- result.reason instanceof Error ? result.reason.message : 'Failed to start task';- failed.push({ error: message, identifier });- }- }-- return {- data: { failed, kickedOff, plan },- success: failed.length === 0,- };+ const result = await ctx.taskService.runReadySubtasks(input.id);+ return { data: result, success: result.failed.length === 0 };} catch (error) {if (error instanceof TRPCError) throw error;console.error('[task:runReadySubtasks]', error);@@ -1115,89 +965,18 @@ export const taskRouter = router({}),).mutation(async ({ input, ctx }) => {- const { id, status, error: errorMsg } = input;try {- if (errorMsg && status !== 'failed') {- throw new TRPCError({- code: 'BAD_REQUEST',- message: 'Task error can only be provided when status is failed.',- });- }-- const model = ctx.taskModel;- const resolved = await resolveOrThrow(model, id);-- // Cascade: when leaving `running`, cancel all running topics- if (resolved.status === 'running' && status !== 'running') {- const topics = await ctx.taskTopicModel.findByTaskId(resolved.id);- const aiAgentService = new AiAgentService(ctx.serverDB, ctx.userId);-- for (const t of topics) {- if (t.status !== 'running' || !t.topicId) continue;-- // Interrupt the remote operation first; if it fails, skip cancellation- // to avoid desynchronizing DB state from a still-running operation.- if (t.operationId) {- try {- await aiAgentService.interruptTask({ operationId: t.operationId });- } catch (err) {- console.error('[task:updateStatus] failed to interrupt topic %s:', t.topicId, err);- continue;- }- }-- // Conditionally cancel only if the topic is still running,- // avoiding overwrite of a concurrent completed/timeout transition.- await ctx.taskTopicModel.cancelIfRunning(resolved.id, t.topicId);- }- }-- const extra: Record<string, unknown> = {};- if (status === 'running') extra.startedAt = new Date();- if (status === 'completed' || status === 'failed' || status === 'canceled')- extra.completedAt = new Date();- if (errorMsg) extra.error = errorMsg;-- const task = await model.updateStatus(resolved.id, status, extra);- if (!task) throw new TRPCError({ code: 'NOT_FOUND', message: 'Task not found' });-- // On completion: check dependency unlocking + parent notification + checkpoints- const unlocked: string[] = [];- const paused: string[] = [];- let allSubtasksDone = false;- let checkpointTriggered = false;-- if (status === 'completed') {- // 1. Check afterIds checkpoint on parent- if (task.parentTaskId) {- const parentTask = await model.findById(task.parentTaskId);- if (parentTask && model.shouldPauseAfterComplete(parentTask, task.identifier)) {- // Pause the parent task for review- await model.updateStatus(parentTask.id, 'paused');- checkpointTriggered = true;- }-- // 2. Check if all sibling subtasks are done- allSubtasksDone = await model.areAllSubtasksCompleted(task.parentTaskId);- }-- // 3. Unlock tasks blocked by this one and actually kick them off.- // The runner creates a topic + enqueues to QStash; status transitions- // happen inside `runTask`, so callers don't need to flip it manually.- const runner = new TaskRunnerService(ctx.serverDB, ctx.userId);- const cascade = await runner.cascadeOnCompletion(task.id);- unlocked.push(...cascade.started);- paused.push(...cascade.paused);- }-+ const result = await ctx.taskService.updateStatus(input);+ const { task, unlocked, paused, checkpointTriggered, allSubtasksDone, parentTaskId } =+ result;return {data: task,- message: `Task ${status}`,+ message: `Task ${input.status}`,success: true,...(unlocked.length > 0 && { unlocked }),...(paused.length > 0 && { paused }),...(checkpointTriggered && { checkpointTriggered: true }),- ...(allSubtasksDone && { allSubtasksDone: true, parentTaskId: task.parentTaskId }),+ ...(allSubtasksDone && { allSubtasksDone: true, parentTaskId }),};} catch (error) {if (error instanceof TRPCError) throw error;diff --git a/src/server/services/task/index.ts b/src/server/services/task/index.tsindex 3d5df37443c..6a22895adc4 100644--- a/src/server/services/task/index.ts+++ b/src/server/services/task/index.ts@@ -4,22 +4,62 @@ import type {TaskDetailData,TaskDetailSubtask,TaskDetailWorkspaceNode,+ TaskItem,+ TaskStatus,TaskTopicHandoff,WorkspaceData,} from '@lobechat/types';+import { TRPCError } from '@trpc/server';import { AgentModel } from '@/database/models/agent';import { BriefModel } from '@/database/models/brief';import { TaskModel } from '@/database/models/task';import { TaskTopicModel } from '@/database/models/taskTopic';+import { TopicModel } from '@/database/models/topic';import { UserModel } from '@/database/models/user';import type { LobeChatDatabase } from '@/database/type';+import { AiAgentService } from '../aiAgent';import { BriefService } from '../brief';+import { type SubtaskGraphPlan, TaskGraphService } from '../taskGraph';+import { type ReviewResult, TaskReviewService } from '../taskReview';+import { TaskRunnerService } from '../taskRunner';const emptyWorkspace: WorkspaceData = { nodeMap: {}, tree: [] };const UNTITLED_TOPIC_TITLE = 'Untitled';+export interface CreateTaskInput {+ assigneeAgentId?: string;+ assigneeUserId?: string;+ automationMode?: 'heartbeat' | 'schedule';+ createdByAgentId?: string;+ description?: string;+ identifierPrefix?: string;+ instruction: string;+ name?: string;+ parentTaskId?: string;+ priority?: number;+ schedulePattern?: string;+ scheduleTimezone?: string;+ sortOrder?: number;+}++export interface UpdateStatusResult {+ allSubtasksDone?: boolean;+ checkpointTriggered?: boolean;+ parentTaskId?: string | null;+ paused: string[];+ task: TaskItem;+ unlocked: string[];+}++export interface RunReadySubtasksResult {+ failed: { error: string; identifier: string }[];+ kickedOff: string[];+ plan: SubtaskGraphPlan;+ skipped?: { reason: 'nothing-runnable' };+}+export class TaskService {private agentModel: AgentModel;private briefModel: BriefModel;@@ -27,16 +67,304 @@ export class TaskService {private db: LobeChatDatabase;private taskModel: TaskModel;private taskTopicModel: TaskTopicModel;+ private topicModel: TopicModel;+ private userId: string;constructor(db: LobeChatDatabase, userId: string) {this.db = db;+ this.userId = userId;this.agentModel = new AgentModel(db, userId);this.taskModel = new TaskModel(db, userId);this.taskTopicModel = new TaskTopicModel(db, userId);+ this.topicModel = new TopicModel(db, userId);this.briefModel = new BriefModel(db, userId);this.briefService = new BriefService(db, userId);}+ /**+ * Create a task. Validates the assignee belongs to the user, resolves+ * `parentTaskId` if it's an identifier, and snapshots the assignee agent's+ * current model/provider into `task.config` so later changes to the agent's+ * default model don't silently affect this task.+ */+ async createTask(input: CreateTaskInput): Promise<TaskItem> {+ await this.assertAssigneeAgentBelongsToUser(input.assigneeAgentId);++ const createData: CreateTaskInput & { config?: Record<string, unknown> } = { ...input };++ if (createData.parentTaskId) {+ const parent = await this.resolveOrThrow(createData.parentTaskId);+ createData.parentTaskId = parent.id;+ }++ if (input.assigneeAgentId) {+ const snapshot = await this.agentModel.getAgentModelConfig(input.assigneeAgentId);+ if (snapshot) createData.config = snapshot;+ }++ return this.taskModel.create(createData);+ }++ /**+ * Cancel a running topic: interrupt the remote operation (if any), then+ * mark the topic as `canceled` and pause its parent task.+ */+ async cancelTopic(topicId: string): Promise<void> {+ const target = await this.taskTopicModel.findByTopicId(topicId);+ if (!target) throw new TRPCError({ code: 'NOT_FOUND', message: 'Topic not found.' });++ if (target.status !== 'running') {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: `Topic is not running (current status: ${target.status}).`,+ });+ }++ if (target.operationId) {+ const aiAgentService = new AiAgentService(this.db, this.userId);+ await aiAgentService.interruptTask({ operationId: target.operationId });+ }++ await this.taskTopicModel.updateStatus(target.taskId, topicId, 'canceled');+ await this.taskModel.updateStatus(target.taskId, 'paused');+ }++ /**+ * Delete a topic: interrupt if still running, then remove the task-topic+ * link and delete the underlying topic.+ */+ async deleteTopic(topicId: string): Promise<void> {+ const target = await this.taskTopicModel.findByTopicId(topicId);+ if (!target) throw new TRPCError({ code: 'NOT_FOUND', message: 'Topic not found.' });++ if (target.status === 'running' && target.operationId) {+ const aiAgentService = new AiAgentService(this.db, this.userId);+ await aiAgentService.interruptTask({ operationId: target.operationId });+ }++ await this.taskTopicModel.remove(target.taskId, topicId);+ await this.topicModel.delete(topicId);+ }++ /**+ * Run the configured review on `content`, persist the result onto the+ * target topic, and return the review outcome.+ */+ async runReview(input: {+ content?: string;+ id: string;+ topicId?: string;+ }): Promise<ReviewResult> {+ const task = await this.resolveOrThrow(input.id);++ const reviewConfig = this.taskModel.getReviewConfig(task);+ if (!reviewConfig?.enabled) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'Review is not enabled for this task',+ });+ }++ const content = input.content;+ if (!content) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'Content is required for review. Pass --content or run after a topic completes.',+ });+ }++ const topicId = input.topicId || task.currentTopicId;++ let iteration = 1;+ if (topicId) {+ const topics = await this.taskTopicModel.findByTaskId(task.id);+ const target = topics.find((t) => t.topicId === topicId);+ if (target?.reviewIteration) iteration = target.reviewIteration + 1;+ }++ const reviewService = new TaskReviewService(this.db, this.userId);+ const result = await reviewService.review({+ content,+ iteration,+ judge: reviewConfig.judge,+ rubrics: reviewConfig.rubrics,+ taskName: task.name || task.identifier,+ });++ if (topicId) {+ await this.taskTopicModel.updateReview(task.id, topicId, {+ iteration,+ passed: result.passed,+ score: result.overallScore,+ scores: result.rubricResults,+ });+ }++ return result;+ }++ /**+ * Transition a task to a new status, cascading the side effects:+ * - leaving `running`: interrupt + cancel still-running topics+ * - entering `completed`: check parent checkpoint, count sibling+ * completions, kick off any newly-unlocked downstream tasks.+ */+ async updateStatus(input: {+ error?: string;+ id: string;+ status: TaskStatus;+ }): Promise<UpdateStatusResult> {+ const { id, status, error: errorMsg } = input;++ if (errorMsg && status !== 'failed') {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'Task error can only be provided when status is failed.',+ });+ }++ const resolved = await this.resolveOrThrow(id);++ if (resolved.status === 'running' && status !== 'running') {+ const topics = await this.taskTopicModel.findByTaskId(resolved.id);+ const aiAgentService = new AiAgentService(this.db, this.userId);++ for (const t of topics) {+ if (t.status !== 'running' || !t.topicId) continue;++ // Interrupt the remote operation first; if it fails, skip cancellation+ // to avoid desynchronizing DB state from a still-running operation.+ if (t.operationId) {+ try {+ await aiAgentService.interruptTask({ operationId: t.operationId });+ } catch (err) {+ console.error(+ '[TaskService.updateStatus] failed to interrupt topic %s:',+ t.topicId,+ err,+ );+ continue;+ }+ }++ await this.taskTopicModel.cancelIfRunning(resolved.id, t.topicId);+ }+ }++ const extra: Record<string, unknown> = {};+ if (status === 'running') extra.startedAt = new Date();+ if (status === 'completed' || status === 'failed' || status === 'canceled')+ extra.completedAt = new Date();+ if (errorMsg) extra.error = errorMsg;++ const task = await this.taskModel.updateStatus(resolved.id, status, extra);+ if (!task) throw new TRPCError({ code: 'NOT_FOUND', message: 'Task not found' });++ const unlocked: string[] = [];+ const paused: string[] = [];+ let allSubtasksDone = false;+ let checkpointTriggered = false;++ if (status === 'completed') {+ if (task.parentTaskId) {+ const parentTask = await this.taskModel.findById(task.parentTaskId);+ if (parentTask && this.taskModel.shouldPauseAfterComplete(parentTask, task.identifier)) {+ await this.taskModel.updateStatus(parentTask.id, 'paused');+ checkpointTriggered = true;+ }+ allSubtasksDone = await this.taskModel.areAllSubtasksCompleted(task.parentTaskId);+ }++ // Unlock blocked tasks and actually kick them off via the runner.+ const runner = new TaskRunnerService(this.db, this.userId);+ const cascade = await runner.cascadeOnCompletion(task.id);+ unlocked.push(...cascade.started);+ paused.push(...cascade.paused);+ }++ return {+ paused,+ task,+ unlocked,+ ...(checkpointTriggered && { checkpointTriggered: true }),+ ...(allSubtasksDone && { allSubtasksDone: true, parentTaskId: task.parentTaskId }),+ };+ }++ /**+ * Compute the subtask execution plan for `idOrIdentifier` without+ * actually kicking anything off.+ */+ async previewSubtaskLayers(idOrIdentifier: string): Promise<SubtaskGraphPlan> {+ const parent = await this.resolveOrThrow(idOrIdentifier);+ const graph = new TaskGraphService(this.db, this.userId);+ const { plan } = await graph.planForParent(parent.id);+ return plan;+ }++ /**+ * Kick off the first runnable layer of subtasks under `idOrIdentifier`.+ * Subsequent layers fire automatically through+ * `TaskRunnerService.cascadeOnCompletion` as each upstream finishes.+ */+ async runReadySubtasks(idOrIdentifier: string): Promise<RunReadySubtasksResult> {+ const parent = await this.resolveOrThrow(idOrIdentifier);+ const graph = new TaskGraphService(this.db, this.userId);+ const { descendants, plan } = await graph.planForParent(parent.id);++ if (plan.layers.length === 0) {+ return {+ failed: [],+ kickedOff: [],+ plan,+ skipped: { reason: 'nothing-runnable' as const },+ };+ }++ const firstLayer = plan.layers[0];+ const identifierToId = new Map(descendants.map((d) => [d.identifier, d.id]));+ const runner = new TaskRunnerService(this.db, this.userId);++ const kickedOff: string[] = [];+ const failed: { error: string; identifier: string }[] = [];++ const settled = await Promise.allSettled(+ firstLayer.map(async (identifier) => {+ const id = identifierToId.get(identifier);+ if (!id) throw new Error(`Subtask ${identifier} not found`);+ await runner.runTask({ taskId: id });+ return identifier;+ }),+ );++ for (const [index, result] of settled.entries()) {+ const identifier = firstLayer[index];+ if (result.status === 'fulfilled') {+ kickedOff.push(identifier);+ } else {+ const message =+ result.reason instanceof Error ? result.reason.message : 'Failed to start task';+ failed.push({ error: message, identifier });+ }+ }++ return { failed, kickedOff, plan };+ }++ private async assertAssigneeAgentBelongsToUser(assigneeAgentId?: string | null): Promise<void> {+ if (!assigneeAgentId) return;+ const exists = await this.agentModel.existsById(assigneeAgentId);+ if (!exists) {+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Assignee agent not found' });+ }+ }++ private async resolveOrThrow(idOrIdentifier: string): Promise<TaskItem> {+ const task = await this.taskModel.resolve(idOrIdentifier);+ if (!task) throw new TRPCError({ code: 'NOT_FOUND', message: 'Task not found' });+ return task;+ }+async getTaskDetail(taskIdOrIdentifier: string): Promise<TaskDetailData | null> {let task = await this.taskModel.resolve(taskIdOrIdentifier);if (!task) return null;diff --git a/src/server/services/taskRunner/index.ts b/src/server/services/taskRunner/index.tsindex e2660574f04..0604ba593e3 100644--- a/src/server/services/taskRunner/index.ts+++ b/src/server/services/taskRunner/index.ts@@ -1,10 +1,12 @@import { TaskIdentifier as TaskSkillIdentifier } from '@lobechat/builtin-skills';import { BriefIdentifier } from '@lobechat/builtin-tool-brief';+import { INBOX_SESSION_ID } from '@lobechat/const';import type { ExecAgentResult, TaskItem } from '@lobechat/types';import { TRPCError } from '@trpc/server';import debug from 'debug';import { TopicTrigger } from '@/const/topic';+import { AgentModel } from '@/database/models/agent';import { BriefModel } from '@/database/models/brief';import { TaskModel } from '@/database/models/task';import { TaskTopicModel } from '@/database/models/taskTopic';@@ -35,6 +37,7 @@ export interface RunTaskResult extends ExecAgentResult {* - `heartbeat-tick` workflow handler (QStash self-rescheduling)*/export class TaskRunnerService {+ private agentModel: AgentModel;private briefModel: BriefModel;private db: LobeChatDatabase;private taskLifecycle: TaskLifecycleService;@@ -45,6 +48,7 @@ export class TaskRunnerService {constructor(db: LobeChatDatabase, userId: string) {this.db = db;this.userId = userId;+ this.agentModel = new AgentModel(db, userId);this.taskModel = new TaskModel(db, userId);this.taskTopicModel = new TaskTopicModel(db, userId);this.briefModel = new BriefModel(db, userId);@@ -67,10 +71,15 @@ export class TaskRunnerService {try {if (!task.assigneeAgentId) {- throw new TRPCError({- code: 'BAD_REQUEST',- message: 'Task has no assigned agent. Use --agent when creating or edit the task.',- });+ const inboxAgent = await this.agentModel.getBuiltinAgent(INBOX_SESSION_ID);+ if (!inboxAgent) {+ throw new TRPCError({+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to resolve fallback inbox agent for task',+ });+ }+ await this.taskModel.update(task.id, { assigneeAgentId: inboxAgent.id });+ task.assigneeAgentId = inboxAgent.id;}const existingTopics = await this.taskTopicModel.findByTaskId(task.id);@@ -150,6 +159,18 @@ export class TaskRunnerService {const taskConfig = (task.config ?? {}) as Record<string, unknown>;+ // Backfill model snapshot for tasks created before the snapshot logic+ // landed, or whose assignee was set after creation. Once written, the+ // task is pinned to this model regardless of later agent default changes.+ if (typeof taskConfig.model !== 'string' || typeof taskConfig.provider !== 'string') {+ const snapshot = await this.agentModel.getAgentModelConfig(agentRef);+ if (snapshot) {+ await this.taskModel.updateTaskConfig(task.id, snapshot);+ taskConfig.model = snapshot.model;+ taskConfig.provider = snapshot.provider;+ }+ }+log('runTask: %s (continue=%s)', taskIdentifier, continueTopicId);const result = await aiAgentService.execAgent({diff --git a/src/server/services/toolExecution/serverRuntimes/__tests__/task.test.ts b/src/server/services/toolExecution/serverRuntimes/__tests__/task.test.tsindex 070c73175fe..44503909482 100644--- a/src/server/services/toolExecution/serverRuntimes/__tests__/task.test.ts+++ b/src/server/services/toolExecution/serverRuntimes/__tests__/task.test.ts@@ -7,6 +7,13 @@ vi.mock('@/server/routers/lambda/task', () => ({taskRouter: { createCaller: () => ({}) },}));+// TaskService's transitive deps (taskReview → ModelRuntime) call getLLMConfig+// at module load, which fails in unit-test env. The runtime is passed a+// taskService instance per test, so a stubbed class is all we need here.+vi.mock('@/server/services/task', () => ({+ TaskService: vi.fn(),+}));+describe('createTaskRuntime', () => {describe('task comments', () => {it('adds a comment to the current task with agent attribution', async () => {@@ -123,10 +130,11 @@ describe('createTaskRuntime', () => {existsById: vi.fn().mockResolvedValue(true),};const taskModel = {- create: vi.fn().mockResolvedValue(fakeTask),resolve: vi.fn(),};- const taskService = {} as any;+ const taskService = {+ createTask: vi.fn().mockResolvedValue(fakeTask),+ };const taskCaller = {} as any;return { agentModel, taskCaller, taskModel, taskService };};@@ -139,7 +147,7 @@ describe('createTaskRuntime', () => {agentId: 'agt-xyz',taskCaller: deps.taskCaller,taskModel: deps.taskModel as any,- taskService: deps.taskService,+ taskService: deps.taskService as any,});const result = await runtime.createTask({@@ -148,7 +156,7 @@ describe('createTaskRuntime', () => {});expect(result.success).toBe(true);- expect(deps.taskModel.create).toHaveBeenCalledWith(+ expect(deps.taskService.createTask).toHaveBeenCalledWith(expect.objectContaining({assigneeAgentId: 'agt-xyz',createdByAgentId: 'agt-xyz',@@ -163,7 +171,7 @@ describe('createTaskRuntime', () => {agentModel: deps.agentModel as any,taskCaller: deps.taskCaller,taskModel: deps.taskModel as any,- taskService: deps.taskService,+ taskService: deps.taskService as any,});await runtime.createTask({@@ -171,7 +179,7 @@ describe('createTaskRuntime', () => {name: 'Test',});- expect(deps.taskModel.create).toHaveBeenCalledWith(+ expect(deps.taskService.createTask).toHaveBeenCalledWith(expect.objectContaining({assigneeAgentId: undefined,createdByAgentId: undefined,@@ -188,7 +196,7 @@ describe('createTaskRuntime', () => {scope: 'task',taskCaller: deps.taskCaller,taskModel: deps.taskModel as any,- taskService: deps.taskService,+ taskService: deps.taskService as any,});await runtime.createTask({@@ -196,7 +204,7 @@ describe('createTaskRuntime', () => {name: 'Test',});- expect(deps.taskModel.create).toHaveBeenCalledWith(+ expect(deps.taskService.createTask).toHaveBeenCalledWith(expect.objectContaining({assigneeAgentId: undefined,createdByAgentId: 'agt-xyz',@@ -213,7 +221,7 @@ describe('createTaskRuntime', () => {scope: 'task',taskCaller: deps.taskCaller,taskModel: deps.taskModel as any,- taskService: deps.taskService,+ taskService: deps.taskService as any,});await runtime.createTask({@@ -222,7 +230,7 @@ describe('createTaskRuntime', () => {name: 'Test',});- expect(deps.taskModel.create).toHaveBeenCalledWith(+ expect(deps.taskService.createTask).toHaveBeenCalledWith(expect.objectContaining({assigneeAgentId: 'agt-worker',createdByAgentId: 'agt-manager',@@ -241,7 +249,7 @@ describe('createTaskRuntime', () => {scope: 'task',taskCaller: deps.taskCaller,taskModel: deps.taskModel as any,- taskService: deps.taskService,+ taskService: deps.taskService as any,});const result = await runtime.createTask({@@ -252,7 +260,7 @@ describe('createTaskRuntime', () => {expect(result.success).toBe(false);expect(result.content).toBe('Assignee agent not found: agt-other-user');- expect(deps.taskModel.create).not.toHaveBeenCalled();+ expect(deps.taskService.createTask).not.toHaveBeenCalled();});it('resolves and uses parentTaskId when parentIdentifier is provided', async () => {@@ -264,7 +272,7 @@ describe('createTaskRuntime', () => {agentId: 'agt-xyz',taskCaller: deps.taskCaller,taskModel: deps.taskModel as any,- taskService: deps.taskService,+ taskService: deps.taskService as any,});await runtime.createTask({@@ -273,7 +281,7 @@ describe('createTaskRuntime', () => {parentIdentifier: 'T-99',});- expect(deps.taskModel.create).toHaveBeenCalledWith(+ expect(deps.taskService.createTask).toHaveBeenCalledWith(expect.objectContaining({createdByAgentId: 'agt-xyz',parentTaskId: 'parent-id',@@ -290,7 +298,7 @@ describe('createTaskRuntime', () => {agentId: 'agt-xyz',taskCaller: deps.taskCaller,taskModel: deps.taskModel as any,- taskService: deps.taskService,+ taskService: deps.taskService as any,});const result = await runtime.createTask({@@ -300,7 +308,7 @@ describe('createTaskRuntime', () => {});expect(result.success).toBe(false);- expect(deps.taskModel.create).not.toHaveBeenCalled();+ expect(deps.taskService.createTask).not.toHaveBeenCalled();});});@@ -327,7 +335,7 @@ describe('createTaskRuntime', () => {agentId: 'agt-manager',taskCaller: deps.taskCaller,taskModel: deps.taskModel as any,- taskService: deps.taskService,+ taskService: deps.taskService as any,});const result = await runtime.editTask({@@ -349,7 +357,7 @@ describe('createTaskRuntime', () => {agentId: 'agt-manager',taskCaller: deps.taskCaller,taskModel: deps.taskModel as any,- taskService: deps.taskService,+ taskService: deps.taskService as any,});const result = await runtime.editTask({@@ -374,7 +382,7 @@ describe('createTaskRuntime', () => {agentId: 'agt-manager',taskCaller: deps.taskCaller,taskModel: deps.taskModel as any,- taskService: deps.taskService,+ taskService: deps.taskService as any,});const result = await runtime.editTask({@@ -396,7 +404,7 @@ describe('createTaskRuntime', () => {agentId: 'agt-manager',taskCaller: deps.taskCaller,taskModel: deps.taskModel as any,- taskService: deps.taskService,+ taskService: deps.taskService as any,});const result = await runtime.editTask({@@ -438,20 +446,22 @@ describe('createTaskRuntime', () => {const makeDeps = () => {const agentModel = { existsById: vi.fn().mockResolvedValue(true) };const taskModel = {- create: vi.fn().mockImplementation(async ({ name }) => ({+ resolve: vi.fn(),+ };+ const taskService = {+ createTask: vi.fn().mockImplementation(async ({ name }) => ({id: `db-${name}`,identifier: `T-${name}`,name,priority: 0,status: 'backlog',})),- resolve: vi.fn(),};return {agentModel,taskCaller: {} as any,taskModel,- taskService: {} as any,+ taskService,};};@@ -462,7 +472,7 @@ describe('createTaskRuntime', () => {agentId: 'agt-x',taskCaller: deps.taskCaller,taskModel: deps.taskModel as any,- taskService: deps.taskService,+ taskService: deps.taskService as any,});const result = await runtime.createTasks({@@ -473,7 +483,7 @@ describe('createTaskRuntime', () => {});expect(result.success).toBe(true);- expect(deps.taskModel.create).toHaveBeenCalledTimes(2);+ expect(deps.taskService.createTask).toHaveBeenCalledTimes(2);expect(result.content).toContain('Created 2 tasks');expect(result.content).toContain('T-A');expect(result.content).toContain('T-B');@@ -482,7 +492,7 @@ describe('createTaskRuntime', () => {it('continues past per-item failures and reports them in the summary', async () => {const deps = makeDeps();// make the second create throw- deps.taskModel.create+ deps.taskService.createTask.mockResolvedValueOnce({id: 'db-A',identifier: 'T-A',@@ -497,7 +507,7 @@ describe('createTaskRuntime', () => {agentId: 'agt-x',taskCaller: deps.taskCaller,taskModel: deps.taskModel as any,- taskService: deps.taskService,+ taskService: deps.taskService as any,});const result = await runtime.createTasks({@@ -518,13 +528,13 @@ describe('createTaskRuntime', () => {agentModel: deps.agentModel as any,taskCaller: deps.taskCaller,taskModel: deps.taskModel as any,- taskService: deps.taskService,+ taskService: deps.taskService as any,});const result = await runtime.createTasks({ tasks: [] });expect(result.success).toBe(false);- expect(deps.taskModel.create).not.toHaveBeenCalled();+ expect(deps.taskService.createTask).not.toHaveBeenCalled();});});diff --git a/src/server/services/toolExecution/serverRuntimes/task.ts b/src/server/services/toolExecution/serverRuntimes/task.tsindex 5a02d27f58e..cca26fb6cfd 100644--- a/src/server/services/toolExecution/serverRuntimes/task.ts+++ b/src/server/services/toolExecution/serverRuntimes/task.ts@@ -59,9 +59,11 @@ export const createTaskRuntime = ({const createTaskImpl = async (args: CreateTaskArgs,): Promise<{ content: string; identifier?: string; success: boolean }> => {- let parentTaskId: string | undefined;let parentLabel: string | undefined;+ // Pre-resolve parent identifier so we can surface a tool-friendly error+ // and label, and pass the resolved id straight through to the service.+ let parentTaskId: string | undefined;if (args.parentIdentifier) {const parent = await taskModel.resolve(args.parentIdentifier);if (!parent)@@ -73,7 +75,7 @@ export const createTaskRuntime = ({const assigneeResult = await resolveAssigneeAgent(args.assigneeAgentId);if (!assigneeResult.success) return { content: assigneeResult.content, success: false };- const task = await taskModel.create({+ const task = await taskService.createTask({assigneeAgentId: args.assigneeAgentId ?? (scope === 'task' ? undefined : agentId),createdByAgentId: agentId,instruction: args.instruction,