π€― 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(server): split the 1770-line task router into sub-domain modules (#21090)
Arvin Xu7b11e08cda93
diff --git a/.agents/skills/ux-audit/references/example/tasks.md b/.agents/skills/ux-audit/references/example/tasks.mdindex c87e98fd831..01f29fa8664 100644--- a/.agents/skills/ux-audit/references/example/tasks.md+++ b/.agents/skills/ux-audit/references/example/tasks.md@@ -28,7 +28,7 @@ branch** (user-supplied screenshot of the populated list), see the **Β§6 addenduKanbanColumn,EmptyState,CreateTaskInlineEntry}`, `features/AgentTasks/features/AgentTaskItem.tsx`,`features/AgentTasks/hooks/useTaskItemContextMenu.tsx`, `CreateTaskModal/*`,`store/task/slices/{list,detail,lifecycle}/action.ts`, `store/task/selectors/listSelectors.ts`,-`apps/server/src/routers/lambda/task.ts`.+`apps/server/src/routers/lambda/task/`.## 1 β Patterns in use@@ -90,7 +90,7 @@ onboarding hero into the permanent skeleton β a failed load reads as neither e_Remedy:_ add `onError` β an error state + Reload; read the hook's `error` at the call site.**Lβ‘ List sort / group / filter run client-side over a 50-row cap; no virtualization β Read Β§1.2** π-The server caps the list at `limit` default **50** (`apps/server/src/routers/lambda/task.ts`), and+The server caps the list at `limit` default **50** (`apps/server/src/routers/lambda/task/queries.ts` `list`, schema in `_helpers/taskListSchemas.ts`), and`fetchTaskList` passes no limit/offset, so 50 rows load while `tasksTotal` can be larger.`TaskList.tsx:135-201` then filters, sorts, and groups **entirely in-memory over those 50** β nopagination, no load-more, no windowing (plain `.map`, `TaskList.tsx:43-48`; kanban maps all,diff --git a/apps/server/src/routers/lambda/task.ts b/apps/server/src/routers/lambda/task.tsdeleted file mode 100644index 0b38408575d..00000000000--- a/apps/server/src/routers/lambda/task.ts+++ /dev/null@@ -1,1770 +0,0 @@-import { TASK_STATUSES } from '@lobechat/builtin-tool-task';-import { AgentRuntimeErrorType } from '@lobechat/model-runtime';-import type { TaskListItem, TaskParticipant, TaskVerifyConfig } from '@lobechat/types';-import { TRPCError } from '@trpc/server';-import { z } from 'zod';--import type { TaskCommentActivityRecipient } from '@/business/server/task/notifyTaskCommentActivity';-import { notifyTaskCommentActivity } from '@/business/server/task/notifyTaskCommentActivity';-import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';-import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';-import { AgentModel } from '@/database/models/agent';-import { BriefModel } from '@/database/models/brief';-import { TaskModel } from '@/database/models/task';-import { TaskArchiveModel } from '@/database/models/taskArchive';-import { TaskTopicModel } from '@/database/models/taskTopic';-import { TopicModel } from '@/database/models/topic';-import { UserModel } from '@/database/models/user';-import { TaskSubtreeRepository } from '@/database/repositories/taskSubtree';-import type { LobeChatDatabase } from '@/database/type';-import { assertAgentUsableBy } from '@/database/utils/agent-access';-import { router } from '@/libs/trpc/lambda';-import { serverDatabase } from '@/libs/trpc/lambda/middleware';-import { markSilentTRPCErrorLog } from '@/libs/trpc/utils/errorLogger';-import { EditLockService } from '@/server/services/editLock';-import { publishResourceEvent } from '@/server/services/resourceEvents';-import { TaskService } from '@/server/services/task';-import { assertNotInOpenGoal } from '@/server/services/task/archiveGuard';-import { notifyAssignedBestEffort } from '@/server/services/task/assignmentNotification';-import { TaskIntentService } from '@/server/services/task/intent';-import {- assertAssigneeAgentBelongsToUser,- resolveTaskPatchInvariants,-} from '@/server/services/task/patchValidation';-import {- assertResultingScheduleValid,- schedulePatternSchema,- scheduleTimezoneSchema,-} from '@/server/services/task/scheduleValidation';-import { TaskLifecycleService } from '@/server/services/taskLifecycle';-import { failStuckTasks } from '@/server/services/taskLifecycle/failStuckTasks';-import { TaskRunnerService } from '@/server/services/taskRunner';-import { AcceptanceService } from '@/server/services/verify/acceptanceService';-import { resolveTaskAcceptance } from '@/server/services/verify/taskAcceptance';-import { hasWorkspaceScopedPermission } from '@/server/services/workspacePermission';-import {- extractMentionedUserIds,- filterActiveWorkspaceMemberIds,- validateMentionedUserIds,-} from '@/server/utils/commentMentions';-import { after } from '@/server/utils/scheduleAfterResponse';-import { TransferErrorCode } from '@/types/transferError';--import { assertWorkspaceRowManageable } from './_helpers/assertWorkspaceRowManageable';-import { groupListSchema, listSchema } from './_helpers/taskListSchemas';--const taskProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {- const { ctx } = opts;- const wsId = ctx.workspaceId ?? undefined;- return opts.next({- ctx: {- agentModel: new AgentModel(ctx.serverDB, ctx.userId, wsId),- briefModel: new BriefModel(ctx.serverDB, ctx.userId, wsId),- editLockService: new EditLockService(ctx.userId),- taskLifecycle: new TaskLifecycleService(ctx.serverDB, ctx.userId, wsId),- taskModel: new TaskModel(ctx.serverDB, ctx.userId, wsId),- taskIntentService: new TaskIntentService(ctx.serverDB, ctx.userId, wsId),- taskService: new TaskService(ctx.serverDB, ctx.userId, wsId),- taskSubtree: new TaskSubtreeRepository(ctx.serverDB, ctx.userId, wsId),- taskTopicModel: new TaskTopicModel(ctx.serverDB, ctx.userId, wsId),- topicModel: new TopicModel(ctx.serverDB, ctx.userId, wsId),- },- });-});--// Write variant gates viewers out of every task mutation (create/update/delete/-// run). Reads keep using `taskProcedure` so viewers can still inspect tasks-// and their status.-const taskProcedureWrite = taskProcedure.use(withScopedPermission('agent:update'));--// All procedures that take an id accept either raw id (task_xxx) or identifier (TASK-1)-// Resolution happens in the model layer via model.resolve()-const idInput = z.object({ id: z.string() });--const taskVerifyConfigPatchSchema = z.object({- enabled: z.boolean().nullish(),- maxIterations: z.number().min(1).max(10).nullish(),- requirement: z.string().nullish(),- verifierAgentId: z.string().nullish(),- verifyCriteriaIds: z.array(z.string()).nullish(),- verifyRubricId: z.string().nullish(),-});--// Priority: 0=None, 1=Urgent, 2=High, 3=Normal, 4=Low-// Unknown fields are stripped, including the removed identifierPrefix. Released-// CLI clients send 'T' by default; ignore it so project subtasks use their project-// identifier without breaking ordinary creates from those clients.-const createSchema = z.object({- assigneeAgentId: z.string().optional(),- assigneeUserId: z.string().optional(),- // Optional schedule wiring at create time. When `automationMode` is- // 'schedule', `schedulePattern` (cron) is required for the central- // schedule-dispatch sweep to pick the task up.- automationMode: z.enum(['heartbeat', 'schedule']).optional(),- config: z.record(z.string(), z.unknown()).optional(),- createdByAgentId: z.string().optional(),- description: z.string().optional(),- editorData: z.unknown().optional(),- instruction: z.string().min(1),- name: z.string().optional(),- parentTaskId: z.string().optional(),- priority: z.number().min(0).max(4).optional(),- projectId: z.string().optional(),- schedulePattern: schedulePatternSchema.optional(),- scheduleTimezone: scheduleTimezoneSchema.optional(),- // When omitted, the server derives visibility from the parent task or the- // assignee agent's visibility (private agent β private task). UI surfaces- // such as the top-level "Tasks" create form pass it explicitly.- visibility: z.enum(['private', 'public']).optional(),- // Removed contract, kept so the server can recognise it. A task no longer- // carries a goal β the Goal Graph owns execution and dispatches its own Work- // Tasks β and silently dropping this field would let a released client report- // that a goal started when only an ordinary task exists.- goal: z.unknown().optional(),-});--const updateSchema = z.object({- assigneeAgentId: z.string().nullish(),- assigneeUserId: z.string().nullish(),- automationMode: z.enum(['heartbeat', 'schedule']).nullish(),- config: z.record(z.string(), z.unknown()).optional(),- // Deep-merged into `config` under the update's row lock rather than- // replacing it β for a client editing one config key alongside columns.- configPatch: z.record(z.string(), z.unknown()).optional(),- context: z.record(z.string(), z.unknown()).optional(),- description: z.string().optional(),- editorData: z.unknown().optional(),- // 0 clears the interval (disables heartbeat); any positive value must be- // β₯600s (10 min) to match the UI minimum and prevent sub-minute ticks if an- // LLM calls setTaskSchedule with a tiny number.- heartbeatInterval: z- .number()- .int()- .refine((v) => v === 0 || v >= 600, {- message: 'heartbeatInterval must be 0 (disabled) or at least 600 seconds (10 minutes)',- })- .optional(),- heartbeatTimeout: z.number().min(1).nullish(),- instruction: z.string().optional(),- name: z.string().optional(),- parentTaskId: z.string().nullish(),- priority: z.number().min(0).max(4).optional(),- schedulePattern: schedulePatternSchema.nullish(),- scheduleTimezone: scheduleTimezoneSchema.nullish(),- status: z.enum(TASK_STATUSES).optional(),-});--// Helper: resolve id/identifier and throw if not found-async function resolveOrThrow(model: TaskModel, id: string) {- const task = await model.resolve(id);- if (!task) throw new TRPCError({ code: 'NOT_FOUND', message: 'Task not found' });- return task;-}--/**- * Recipients of a new member comment on a task: the creator and the member- * assignee as ambient `commented` pings, upgraded to `mentioned` when the- * comment @mentions them. The actor never appears in the result.- */-function collectTaskCommentRecipients(params: {- actorUserId: string;- mentionedUserIds: string[];- task: { assigneeUserId: string | null; createdByUserId: string };-}): TaskCommentActivityRecipient[] {- const { actorUserId, mentionedUserIds, task } = params;- const byUserId = new Map<string, TaskCommentActivityRecipient['kind']>();- for (const userId of [task.createdByUserId, task.assigneeUserId]) {- if (userId) byUserId.set(userId, 'commented');- }- for (const userId of mentionedUserIds) byUserId.set(userId, 'mentioned');- byUserId.delete(actorUserId);- return [...byUserId].map(([userId, kind]) => ({ kind, userId }));-}--/**- * Whether a notification deep-linking to `task` would land on a page `userId`- * cannot open. Mirrors `TaskModel.ownership()`: public tasks are visible to- * every member, private ones only to their creator. Membership is a separate- * check (`filterActiveWorkspaceMemberIds`).- */-function isTaskHiddenFrom(- task: { createdByUserId: string; visibility: 'private' | 'public' },- userId: string,-): boolean {- return task.visibility === 'private' && task.createdByUserId !== userId;-}--interface TaskNotificationCtx {- serverDB: LobeChatDatabase;- taskModel: TaskModel;- workspaceId: string;-}--/**- * Re-authorize every recipient against the task before any id reaches the- * delivery slot (same contract as topic and document comments): a member- * @mentioned on a private task they cannot see must not receive its title and- * link, and the creator / assignee rows can outlive workspace membership.- */-async function filterRecipientsByTaskAccess(- ctx: TaskNotificationCtx,- taskId: string,- recipients: TaskCommentActivityRecipient[],-): Promise<TaskCommentActivityRecipient[]> {- if (recipients.length === 0) return [];- const task = await ctx.taskModel.findById(taskId);- if (!task) return [];-- const visible = recipients.filter(({ userId }) => !isTaskHiddenFrom(task, userId));- const activeUserIds = new Set(- await filterActiveWorkspaceMemberIds(- ctx.serverDB,- ctx.workspaceId,- visible.map(({ userId }) => userId),- ),- );- return visible.filter(({ userId }) => activeUserIds.has(userId));-}--/**- * Member comment ping (Linear-style), delivered after the response as- * best-effort work: the `@/business` slot defaults to a no-op, and a rejecting- * implementation must neither fail the mutation nor surface as an unhandled- * rejection. `after()` keeps the work alive past the response on serverless.- */-function notifyCommentActivityBestEffort(- ctx: TaskNotificationCtx,- params: Parameters<typeof notifyTaskCommentActivity>[0],-) {- after(async () => {- try {- const recipients = await filterRecipientsByTaskAccess(ctx, params.taskId, params.recipients);- if (recipients.length === 0) return;- await notifyTaskCommentActivity({ ...params, recipients });- } catch (error) {- console.error('[task-comment] Failed to send activity notification', error);- }- });-}--/**- * Who an activity row is attributed to.- *- * A server-side caller (the gateway task runtime) carries the agent in- * `ctx.actingAgentId`, which no HTTP request can set β that is the trusted- * path and always wins. The client-first runtime (gateway off, self-hosted)- * has no such channel: its task tools are ordinary TRPC calls from the- * browser, so it names the agent in the payload β the same contract- * `addComment.authorAgentId` already uses β and the claim is honoured only- * for an agent the caller can use. That bounds any misattribution to the- * caller's own agents rather than letting a request pin a change on anyone.- */-async function resolveActivityActor(- ctx: {- actingAgentId?: string | null;- serverDB: LobeChatDatabase;- userId: string;- workspaceId?: string | null;- },- claimedAgentId?: string,-): Promise<{ agentId?: string | null; userId: string }> {- if (ctx.actingAgentId) return { agentId: ctx.actingAgentId, userId: ctx.userId };- if (claimedAgentId) {- await assertAgentUsableBy(ctx.serverDB, claimedAgentId, {- userId: ctx.userId,- workspaceId: ctx.workspaceId ?? undefined,- });- }- return { agentId: claimedAgentId ?? null, userId: ctx.userId };-}--export const taskRouter = router({- /**- * Read a composer draft and report what it means β a name, the outcome as- * understood, the questions that would change the deliverable, and whether- * it is really a standing goal. Returns a reading only; nothing is created.- */- analyzeIntent: taskProcedureWrite- .input(- z.object({- context: z.string().optional(),- instruction: z.string().min(1).max(20_000),- }),- )- .mutation(async ({ ctx, input }) => {- try {- return await ctx.taskIntentService.analyze(input);- } catch (error) {- const errorType = (error as { errorType?: unknown } | null)?.errorType;- if (errorType === AgentRuntimeErrorType.InvalidProviderAPIKey) {- const trpcError = new TRPCError({- cause: error,- code: 'PRECONDITION_FAILED',- message: AgentRuntimeErrorType.InvalidProviderAPIKey,- });- // Runtime errors are plain payloads, so tRPC normalizes them into an- // Error cause; mark the cause the shared handler actually receives.- markSilentTRPCErrorLog(trpcError.cause);- throw trpcError;- }-- throw error;- }- }),-- /**- * Rewrite a confirmed draft into the brief that gets executed, folding in the- * answers the user just gave. Returns a brief only; nothing is created.- */- synthesizeInstruction: taskProcedureWrite- .input(- z.object({- answers: z- .array(z.object({ answer: z.string().min(1), question: z.string().min(1) }))- .max(3),- context: z.string().optional(),- instruction: z.string().min(1).max(20_000),- }),- )- .mutation(async ({ ctx, input }) => {- try {- return await ctx.taskIntentService.synthesize(input);- } catch (error) {- const errorType = (error as { errorType?: unknown } | null)?.errorType;- if (errorType === AgentRuntimeErrorType.InvalidProviderAPIKey) {- const trpcError = new TRPCError({- cause: error,- code: 'PRECONDITION_FAILED',- message: AgentRuntimeErrorType.InvalidProviderAPIKey,- });- markSilentTRPCErrorLog(trpcError.cause);- throw trpcError;- }-- throw error;- }- }),-- reorderSubtasks: taskProcedureWrite- .input(- z.object({- id: z.string(),- // Ordered list of subtask identifiers (e.g. ['TASK-2', 'TASK-4', 'TASK-3'])- order: z.array(z.string()),- }),- )- .mutation(async ({ input, ctx }) => {- try {- const model = ctx.taskModel;- const task = await resolveOrThrow(model, input.id);- const subtasks = await model.findSubtasks(task.id);-- // Build identifier β id map- const idMap = new Map<string, string>();- for (const s of subtasks) idMap.set(s.identifier, s.id);-- // Validate all identifiers exist- const reorderItems: Array<{ id: string; sortOrder: number }> = [];- for (let i = 0; i < input.order.length; i++) {- const identifier = input.order[i].toUpperCase();- const taskId = idMap.get(identifier);- if (!taskId) {- throw new TRPCError({- code: 'BAD_REQUEST',- message: `Subtask not found: ${identifier}`,- });- }- reorderItems.push({ id: taskId, sortOrder: i });- }-- await model.reorder(reorderItems);-- return {- data: reorderItems.map((item, i) => ({- identifier: input.order[i],- sortOrder: item.sortOrder,- })),- message: 'Subtasks reordered',- success: true,- };- } catch (error) {- if (error instanceof TRPCError) throw error;- console.error('[task:reorderSubtasks]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to reorder subtasks',- });- }- }),-- addComment: taskProcedureWrite- .input(- z.object({- authorAgentId: z.string().optional(),- briefId: z.string().optional(),- content: z.string().min(1),- editorData: z.unknown().optional(),- id: z.string(),- topicId: z.string().optional(),- }),- )- .mutation(async ({ input, ctx }) => {- try {- const model = ctx.taskModel;- const task = await resolveOrThrow(model, input.id);- await assertAssigneeAgentBelongsToUser(- ctx.serverDB,- { userId: ctx.userId, workspaceId: ctx.workspaceId ?? undefined },- input.authorAgentId,- );- // Resolve @mentions before the insert so an invalid editorData never- // leaves a comment behind that nobody was told about.- const mentionedUserIds =- ctx.workspaceId && !input.authorAgentId- ? await validateMentionedUserIds(- ctx.serverDB,- { actorUserId: ctx.userId, workspaceId: ctx.workspaceId },- input.editorData,- )- : [];- const comment = await model.addComment({- authorAgentId: input.authorAgentId,- authorUserId: input.authorAgentId ? undefined : ctx.userId,- briefId: input.briefId,- content: input.content,- editorData: input.editorData as never,- taskId: task.id,- topicId: input.topicId,- userId: ctx.userId,- });- // Member comment ping (Linear-style): the task creator and the member- // assignee learn about new discussion; @mentioned members get the- // stronger "mentioned" notification instead. Agent-authored progress- // notes stay silent β they are not a conversation between members.- if (ctx.workspaceId && !input.authorAgentId) {- const recipients = collectTaskCommentRecipients({- actorUserId: ctx.userId,- mentionedUserIds,- task,- });- if (recipients.length > 0) {- notifyCommentActivityBestEffort(- { serverDB: ctx.serverDB, taskModel: model, workspaceId: ctx.workspaceId },- {- actorUserId: ctx.userId,- commentId: comment.id,- recipients,- taskId: task.id,- workspaceId: ctx.workspaceId,- },- );- }- }- return { data: comment, message: 'Comment added', success: true };- } catch (error) {- if (error instanceof TRPCError) throw error;- console.error('[task:addComment]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to add comment',- });- }- }),-- deleteComment: taskProcedureWrite- .input(z.object({ commentId: z.string() }))- .mutation(async ({ input, ctx }) => {- try {- const deleted = await ctx.taskModel.deleteComment(input.commentId);- if (!deleted) {- throw new TRPCError({ code: 'NOT_FOUND', message: 'Comment not found' });- }- return { message: 'Comment deleted', success: true };- } catch (error) {- if (error instanceof TRPCError) throw error;- console.error('[task:deleteComment]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to delete comment',- });- }- }),-- updateComment: taskProcedureWrite- .input(- z.object({- commentId: z.string(),- content: z.string().min(1),- editorData: z.unknown().optional(),- }),- )- .mutation(async ({ input, ctx }) => {- try {- const workspaceId = ctx.workspaceId ?? undefined;- const previous = await ctx.taskModel.findCommentById(input.commentId);- if (!previous) {- throw new TRPCError({ code: 'NOT_FOUND', message: 'Comment not found' });- }- // Only members @mentioned for the first time by this edit are pinged;- // mentions kept from the previous revision were already notified.- let addedMentionUserIds: string[] = [];- if (workspaceId && !previous.authorAgentId && input.editorData !== undefined) {- const previousMentions = new Set(extractMentionedUserIds(previous.editorData));- const nextMentions = await validateMentionedUserIds(- ctx.serverDB,- { actorUserId: ctx.userId, workspaceId },- input.editorData,- );- addedMentionUserIds = nextMentions.filter((id) => !previousMentions.has(id));- }- const comment = await ctx.taskModel.updateComment(input.commentId, input.content, {- editorData: input.editorData === undefined ? null : input.editorData,- });- if (!comment) {- throw new TRPCError({ code: 'NOT_FOUND', message: 'Comment not found' });- }- if (workspaceId && addedMentionUserIds.length > 0) {- notifyCommentActivityBestEffort(- { serverDB: ctx.serverDB, taskModel: ctx.taskModel, workspaceId },- {- actorUserId: ctx.userId,- commentId: comment.id,- recipients: addedMentionUserIds.map((userId) => ({ kind: 'mentioned', userId })),- taskId: comment.taskId,- workspaceId,- },- );- }- return { data: comment, message: 'Comment updated', success: true };- } catch (error) {- if (error instanceof TRPCError) throw error;- console.error('[task:updateComment]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to update comment',- });- }- }),-- addDependency: taskProcedureWrite- .input(- z.object({- dependsOnId: z.string(),- taskId: z.string(),- type: z.enum(['blocks', 'relates']).default('blocks'),- }),- )- .mutation(async ({ input, ctx }) => {- try {- const model = ctx.taskModel;- const task = await resolveOrThrow(model, input.taskId);- const dep = await resolveOrThrow(model, input.dependsOnId);- await model.addDependency(task.id, dep.id, input.type);- return { message: 'Dependency added', success: true };- } catch (error) {- if (error instanceof TRPCError) throw error;- console.error('[task:addDependency]', error);- if (error instanceof Error && error.message.includes('project boundaries')) {- throw new TRPCError({ cause: error, code: 'BAD_REQUEST', message: error.message });- }- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to add dependency',- });- }- }),-- cancelTopic: taskProcedureWrite- .input(z.object({ topicId: z.string() }))- .mutation(async ({ input, ctx }) => {- try {- await ctx.taskService.cancelTopic(input.topicId);- return { message: 'Topic canceled', success: true };- } catch (error) {- if (error instanceof TRPCError) throw error;- console.error('[task:cancelTopic]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to cancel topic',- });- }- }),-- deleteTopic: taskProcedureWrite- .input(z.object({ topicId: z.string() }))- .mutation(async ({ input, ctx }) => {- try {- await ctx.taskService.deleteTopic(input.topicId);- return { message: 'Topic deleted', success: true };- } catch (error) {- if (error instanceof TRPCError) throw error;- console.error('[task:deleteTopic]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to delete topic',- });- }- }),-- create: taskProcedureWrite.input(createSchema).mutation(async ({ input, ctx }) => {- const { goal: legacyGoal, ...createInput } = input;- if (legacyGoal !== undefined) {- throw new TRPCError({- code: 'BAD_REQUEST',- message:- 'Creating a goal through task.create is no longer supported. Reload the app, then create the goal again.',- });- }- assertResultingScheduleValid(null, createInput);- try {- const parsedVerify = taskVerifyConfigPatchSchema.safeParse(createInput.config?.verify);- const { verify: _legacyVerify, ...taskConfig } = createInput.config ?? {};- const task = await ctx.taskService.createTask({- ...createInput,- config: parsedVerify.success ? taskConfig : createInput.config,- });- try {- if (parsedVerify.success) {- const { requirement, ...rawConfig } = parsedVerify.data;- const config = Object.fromEntries(- Object.entries(rawConfig).filter(([, value]) => value != null),- );- await new AcceptanceService(- ctx.serverDB,- ctx.userId,- ctx.workspaceId ?? undefined,- ).ensureForSubject('task', task.id, {- config,- requirement: requirement ?? undefined,- });- }- } catch (error) {- await ctx.taskModel.delete(task.id).catch(() => {});- throw error;- }- // Creating a task already assigned to another member notifies them.- notifyAssignedBestEffort(ctx, task);- return { data: task, message: 'Task created', success: true };- } catch (error) {- if (error instanceof TRPCError) throw error;- console.error('[task:create]', error);- const causeMessage = error instanceof Error ? error.message : String(error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: causeMessage ? `Failed to create task: ${causeMessage}` : 'Failed to create task',- });- }- }),-- clearAll: taskProcedureWrite.mutation(async ({ ctx }) => {- try {- const model = ctx.taskModel;- // Workspace clear-all is caller-scoped for every role β owners included- // (per docs/usage/workspace-permissions: bulk actions only affect- // caller-created content).- const restrictToCreator = !!ctx.workspaceId;- const count = await model.deleteAll({ restrictToCreator });- return { count, message: `${count} tasks deleted`, success: true };- } catch (error) {- console.error('[task:clearAll]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to clear tasks',- });- }- }),-- delete: taskProcedureWrite.input(idInput).mutation(async ({ input, ctx }) => {- try {- const task = await resolveOrThrow(ctx.taskModel, input.id);- assertWorkspaceRowManageable(ctx, task.createdByUserId, 'task');- await ctx.taskService.deleteTask(task.id);- return { data: task, message: 'Task deleted', success: true };- } catch (error) {- if (error instanceof TRPCError) throw error;- console.error('[task:delete]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to delete task',- });- }- }),-- // User-only close-out: no builtin agent tool exposes it, so an agent never- // archives a task on its own. `status` is left untouched.- archive: taskProcedureWrite- .input(idInput.extend({ archived: z.boolean() }))- .mutation(async ({ input, ctx }) => {- try {- const task = await resolveOrThrow(ctx.taskModel, input.id);- // Archiving hides a shared task from every member's lists: same- // creator-or-owner scope as delete.- assertWorkspaceRowManageable(ctx, task.createdByUserId, 'task');- if (input.archived) {- await assertNotInOpenGoal(- ctx.serverDB,- { userId: ctx.userId, workspaceId: ctx.workspaceId ?? undefined },- task,- );- }- const archiveModel = new TaskArchiveModel(- ctx.serverDB,- ctx.userId,- ctx.workspaceId ?? undefined,- );- // Archived rows leave every list, so live work would run out of sight.- // The guard is part of the UPDATE, so a run starting concurrently can't slip past.- const updated = input.archived- ? await archiveModel.archive(task.id)- : await archiveModel.unarchive(task.id);- if (!updated) {- throw new TRPCError({- code: 'BAD_REQUEST',- message: 'Stop the running task or its schedule/heartbeat before archiving it',- });- }- return { data: updated, success: true };- } catch (error) {- if (error instanceof TRPCError) throw error;- console.error('[task:archive]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to archive task',- });- }- }),-- detail: taskProcedure.input(idInput).query(async ({ input, ctx }) => {- try {- const detail = await ctx.taskService.getTaskDetail(input.id);- if (!detail) {- throw new TRPCError({ code: 'NOT_FOUND', message: 'Task not found' });- }-- return { data: detail, success: true };- } catch (error) {- if (error instanceof TRPCError) throw error;- console.error('[task:detail]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to get task detail',- });- }- }),-- find: taskProcedure.input(idInput).query(async ({ input, ctx }) => {- try {- const model = ctx.taskModel;- const task = await resolveOrThrow(model, input.id);- return { data: task, success: true };- } catch (error) {- if (error instanceof TRPCError) throw error;- console.error('[task:find]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to find task',- });- }- }),-- getDependencies: taskProcedure.input(idInput).query(async ({ input, ctx }) => {- try {- const model = ctx.taskModel;- const task = await resolveOrThrow(model, input.id);- const deps = await model.getDependencies(task.id);- return { data: deps, success: true };- } catch (error) {- if (error instanceof TRPCError) throw error;- console.error('[task:getDependencies]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to get dependencies',- });- }- }),-- getPinnedDocuments: taskProcedure.input(idInput).query(async ({ input, ctx }) => {- try {- const model = ctx.taskModel;- const task = await resolveOrThrow(model, input.id);- const docs = await model.getPinnedDocuments(task.id);- return { data: docs, success: true };- } catch (error) {- if (error instanceof TRPCError) throw error;- console.error('[task:getPinnedDocuments]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to get documents',- });- }- }),-- getTopics: taskProcedure.input(idInput).query(async ({ input, ctx }) => {- try {- const model = ctx.taskModel;- const task = await resolveOrThrow(model, input.id);- const results = await ctx.taskTopicModel.findWithDetails(task.id);- return { data: results, success: true };- } catch (error) {- if (error instanceof TRPCError) throw error;- console.error('[task:getTopics]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to get task topics',- });- }- }),-- getSubtasks: taskProcedure.input(idInput).query(async ({ input, ctx }) => {- try {- const model = ctx.taskModel;- const task = await resolveOrThrow(model, input.id);- const subtasks = await model.findSubtasks(task.id);- return { data: subtasks, success: true };- } catch (error) {- if (error instanceof TRPCError) throw error;- console.error('[task:getSubtasks]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to get subtasks',- });- }- }),-- getTaskTree: taskProcedure.input(idInput).query(async ({ input, ctx }) => {- try {- const model = ctx.taskModel;- const task = await resolveOrThrow(model, input.id);- const tree = await model.getTaskTree(task.id);- return { data: tree, success: true };- } catch (error) {- if (error instanceof TRPCError) throw error;- console.error('[task:getTaskTree]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to get task tree',- });- }- }),-- heartbeat: taskProcedureWrite.input(idInput).mutation(async ({ input, ctx }) => {- try {- const model = ctx.taskModel;- const task = await resolveOrThrow(model, input.id);- await model.updateHeartbeat(task.id);- return { message: 'Heartbeat updated', success: true };- } catch (error) {- if (error instanceof TRPCError) throw error;- console.error('[task:heartbeat]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to update heartbeat',- });- }- }),-- watchdog: taskProcedureWrite.mutation(async ({ ctx }) => {- try {- const { checked, failed } = await failStuckTasks(ctx.serverDB);-- return {- checked,- failed,- message:- failed.length > 0- ? `${failed.length} stuck tasks marked as failed`- : 'No stuck tasks found',- success: true,- };- } catch (error) {- console.error('[task:watchdog]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Watchdog check failed',- });- }- }),-- groupList: taskProcedure.input(groupListSchema).query(async ({ input, ctx }) => {- try {- const model = ctx.taskModel;- const { scope, ...query } = input;- const groups = await model.groupList({- ...query,- ...(scope === 'assigned' ? { assigneeUserId: ctx.userId } : {}),- ...(scope === 'created' ? { createdByUserId: ctx.userId } : {}),- });- return { data: groups, success: true };- } catch (error) {- console.error('[task:groupList]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to fetch grouped tasks',- });- }- }),-- list: taskProcedure.input(listSchema).query(async ({ input, ctx }) => {- try {- const model = ctx.taskModel;- const { parentIdentifier, scope, ...query } = input;- let parentTaskId = query.parentTaskId;-- if (parentIdentifier) {- const parent = await model.resolve(parentIdentifier);- if (!parent) {- throw new TRPCError({- code: 'NOT_FOUND',- message: `Parent task not found: ${parentIdentifier}`,- });- }-- parentTaskId = parent.id;- }-- const result = await model.list({- ...query,- ...(scope === 'assigned' ? { assigneeUserId: ctx.userId } : {}),- ...(scope === 'created' ? { createdByUserId: ctx.userId } : {}),- parentTaskId,- });-- const assigneeIds = [- ...new Set(result.tasks.map((t) => t.assigneeAgentId).filter((id): id is string => !!id)),- ];- const assigneeUserIds = [- ...new Set(result.tasks.map((t) => t.assigneeUserId).filter((id): id is string => !!id)),- ];- const [agents, users] = await Promise.all([- assigneeIds.length > 0 ? ctx.agentModel.getAgentAvatarsByIds(assigneeIds) : [],- assigneeUserIds.length > 0- ? UserModel.getDisplayInfoByIds(ctx.serverDB, assigneeUserIds)- : [],- ]);- const agentMap = new Map(agents.map((a) => [a.id, a]));- const userMap = new Map(users.map((u) => [u.id, u]));-- const data: TaskListItem[] = result.tasks.map((task) => {- const participants: TaskParticipant[] = [];- if (task.assigneeAgentId) {- const agent = agentMap.get(task.assigneeAgentId);- if (agent) {- participants.push({- avatar: agent.avatar,- backgroundColor: agent.backgroundColor,- id: agent.id,- title: agent.title ?? '',- type: 'agent',- });- }- }- if (task.assigneeUserId) {- const user = userMap.get(task.assigneeUserId);- if (user) {- participants.push({- avatar: user.avatar,- backgroundColor: null,- id: user.id,- title: user.fullName ?? user.username ?? '',- type: 'user',- });- }- }- return { ...task, participants };- });-- return { data, success: true, total: result.total };- } catch (error) {- if (error instanceof TRPCError) throw error;- console.error('[task:list]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to list tasks',- });- }- }),-- run: taskProcedureWrite- .input(- idInput.merge(- z.object({- continueTopicId: z.string().optional(),- deviceId: z.string().optional(),- prompt: z.string().optional(),- }),- ),- )- .mutation(async ({ input, ctx }) => {- try {- const task = await resolveOrThrow(ctx.taskModel, input.id);-- const runner = new TaskRunnerService(- ctx.serverDB,- ctx.userId,- ctx.workspaceId ?? undefined,- );- return await runner.runTask({- continueTopicId: input.continueTopicId,- deviceId: input.deviceId,- extraPrompt: input.prompt,- taskId: task.id,- });- } catch (error) {- if (error instanceof TRPCError) throw error;- console.error('[task:run]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to run task',- });- }- }),-- pinDocument: taskProcedureWrite- .input(- z.object({- documentId: z.string(),- pinnedBy: z.string().default('user'),- taskId: z.string(),- }),- )- .mutation(async ({ input, ctx }) => {- try {- const model = ctx.taskModel;- const task = await resolveOrThrow(model, input.taskId);- await model.pinDocument(task.id, input.documentId, input.pinnedBy);- return { message: 'Document pinned', success: true };- } catch (error) {- if (error instanceof TRPCError) throw error;- console.error('[task:pinDocument]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to pin document',- });- }- }),-- removeDependency: taskProcedureWrite- .input(z.object({ dependsOnId: z.string(), taskId: z.string() }))- .mutation(async ({ input, ctx }) => {- try {- const model = ctx.taskModel;- const task = await resolveOrThrow(model, input.taskId);- const dep = await resolveOrThrow(model, input.dependsOnId);- await model.removeDependency(task.id, dep.id);- return { message: 'Dependency removed', success: true };- } catch (error) {- if (error instanceof TRPCError) throw error;- console.error('[task:removeDependency]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to remove dependency',- });- }- }),-- unpinDocument: taskProcedureWrite- .input(z.object({ documentId: z.string(), taskId: z.string() }))- .mutation(async ({ input, ctx }) => {- try {- const model = ctx.taskModel;- const task = await resolveOrThrow(model, input.taskId);- await model.unpinDocument(task.id, input.documentId);- return { message: 'Document unpinned', success: true };- } catch (error) {- if (error instanceof TRPCError) throw error;- console.error('[task:unpinDocument]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to unpin document',- });- }- }),-- getCheckpoint: taskProcedure.input(idInput).query(async ({ input, ctx }) => {- try {- const model = ctx.taskModel;- const task = await resolveOrThrow(model, input.id);- const checkpoint = model.getCheckpointConfig(task);- return { data: checkpoint, success: true };- } catch (error) {- if (error instanceof TRPCError) throw error;- console.error('[task:getCheckpoint]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to get checkpoint',- });- }- }),-- updateCheckpoint: taskProcedureWrite- .input(- idInput.merge(- z.object({- checkpoint: z.object({- onAgentRequest: z.boolean().optional(),- tasks: z- .object({- afterIds: z.array(z.string()).optional(),- beforeIds: z.array(z.string()).optional(),- })- .optional(),- topic: z- .object({- after: z.boolean().optional(),- before: z.boolean().optional(),- })- .optional(),- }),- }),- ),- )- .mutation(async ({ input, ctx }) => {- const { id, checkpoint } = input;- try {- const model = ctx.taskModel;- const resolved = await resolveOrThrow(model, id);- const task = await model.updateCheckpointConfig(resolved.id, checkpoint);- if (!task) throw new TRPCError({ code: 'NOT_FOUND', message: 'Task not found' });- return {- data: model.getCheckpointConfig(task),- message: 'Checkpoint updated',- success: true,- };- } catch (error) {- if (error instanceof TRPCError) throw error;- console.error('[task:updateCheckpoint]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to update checkpoint',- });- }- }),-- getReview: taskProcedure.input(idInput).query(async ({ input, ctx }) => {- try {- const model = ctx.taskModel;- const task = await resolveOrThrow(model, input.id);- return { data: model.getReviewConfig(task) || null, success: true };- } catch (error) {- if (error instanceof TRPCError) throw error;- console.error('[task:getReview]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to get review config',- });- }- }),-- updateReview: taskProcedureWrite- .input(- idInput.merge(- z.object({- review: z.object({- autoRetry: z.boolean().default(true),- enabled: z.boolean(),- judge: z- .object({- model: z.string().optional(),- provider: z.string().optional(),- })- .default({}),- maxIterations: z.number().min(1).max(10).default(3),- rubrics: z.array(- z.object({- config: z.record(z.string(), z.unknown()),- extractor: z.record(z.string(), z.unknown()).optional(),- id: z.string(),- name: z.string(),- threshold: z.number().min(0).max(1).optional(),- type: z.string(),- weight: z.number().default(1),- }),- ),- }),- }),- ),- )- .mutation(async ({ input, ctx }) => {- const { id, review } = input;- try {- const model = ctx.taskModel;- const resolved = await resolveOrThrow(model, id);- const task = await model.updateReviewConfig(resolved.id, review);- if (!task) throw new TRPCError({ code: 'NOT_FOUND', message: 'Task not found' });- return {- data: model.getReviewConfig(task),- message: 'Review config updated',- success: true,- };- } catch (error) {- if (error instanceof TRPCError) throw error;- console.error('[task:updateReview]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to update review config',- });- }- }),-- getVerifyConfig: taskProcedure.input(idInput).query(async ({ input, ctx }) => {- try {- const model = ctx.taskModel;- const task = await resolveOrThrow(model, input.id);- const resolved = await resolveTaskAcceptance(- ctx.serverDB,- ctx.userId,- task.id,- ctx.workspaceId ?? undefined,- );- return {- data: resolved ? { ...resolved.config, requirement: resolved.requirement } : null,- success: true,- };- } catch (error) {- if (error instanceof TRPCError) throw error;- console.error('[task:getVerifyConfig]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to get verify config',- });- }- }),-- updateVerifyConfig: taskProcedureWrite- .input(- idInput.merge(- z.object({- // `.nullish()` lets callers clear a saved field: `null` removes it- // (JSON can't send `undefined`), omission leaves it untouched.- verify: taskVerifyConfigPatchSchema,- }),- ),- )- .mutation(async ({ input, ctx }) => {- const { id, verify } = input;- try {- const model = ctx.taskModel;- const task = await resolveOrThrow(model, id);- const acceptanceService = new AcceptanceService(- ctx.serverDB,- ctx.userId,- ctx.workspaceId ?? undefined,- );- const resolvedAcceptance = await resolveTaskAcceptance(- ctx.serverDB,- ctx.userId,- task.id,- ctx.workspaceId ?? undefined,- );- const acceptance =- resolvedAcceptance?.acceptance ??- (await acceptanceService.ensureForSubject('task', task.id));- const nextConfig = { ...acceptance.config } as Record<string, unknown>;- for (const [key, value] of Object.entries(verify)) {- if (key === 'requirement') continue;- if (value === null) delete nextConfig[key];- else if (value !== undefined) nextConfig[key] = value;- }- const requirement =- verify.requirement === undefined ? acceptance.requirement : verify.requirement;- const updated = await acceptanceService.acceptanceModel.updatePolicy(acceptance.id, {- config: nextConfig,- requirement,- });- if (!updated) {- throw new TRPCError({ code: 'NOT_FOUND', message: 'Acceptance policy not found' });- }- const data: TaskVerifyConfig = {- ...(nextConfig as TaskVerifyConfig),- requirement: requirement ?? undefined,- };- return {- data,- message: 'Verify config updated',- success: true,- };- } catch (error) {- if (error instanceof TRPCError) throw error;- console.error('[task:updateVerifyConfig]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to update verify config',- });- }- }),-- runReview: taskProcedureWrite- .input(- idInput.merge(- z.object({- content: z.string().optional(),- topicId: z.string().optional(),- }),- ),- )- .mutation(async ({ input, ctx }) => {- try {- const result = await ctx.taskService.runReview(input);- return { data: result, success: true };- } catch (error) {- if (error instanceof TRPCError) throw error;- console.error('[task:runReview]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to run review',- });- }- }),-- update: taskProcedureWrite- .input(idInput.merge(updateSchema).extend({ actorAgentId: z.string().optional() }))- .mutation(async ({ input, ctx }) => {- const { actorAgentId, configPatch, id, parentTaskId, status, ...data } = input;- try {- const model = ctx.taskModel;- const actor = await resolveActivityActor(ctx, actorAgentId);- // Hierarchy, visibility and assignment invariants β shared with the- // REST patch boundary so the two cannot drift.- const { data: normalizedUpdateData, resolved } = await resolveTaskPatchInvariants(- {- agentModel: ctx.agentModel,- editLockService: ctx.editLockService,- serverDB: ctx.serverDB,- taskModel: model,- taskService: ctx.taskService,- userId: ctx.userId,- workspaceId: ctx.workspaceId ?? undefined,- },- { data, id, parentTaskId },- );- // Agent attribution comes from `resolveActivityActor` above. The- // assignment activity is written inside this update's own transaction- // (see `TaskModel.updateWithLog`), so a concurrent reassignment cannot- // interleave between reading the old assignee and recording it.- const task = status- ? await ctx.serverDB.transaction(async (tx) => {- const taskService = new TaskService(tx, ctx.userId, ctx.workspaceId ?? undefined);- const updated = await taskService.updateTaskWithAssigneeLock(- resolved.id,- normalizedUpdateData,- actor,- { configPatch },- );- if (!updated) return null;-- const result = await taskService.updateStatus({ id: resolved.id, status }, actor);- return result.task;- })- : await ctx.taskService.updateTaskWithAssigneeLock(- resolved.id,- normalizedUpdateData,- actor,- { configPatch },- );- if (!task) throw new TRPCError({ code: 'NOT_FOUND', message: 'Task not found' });- // Only an actual assignee change notifies β re-saving the same assignee- // stays silent (self-assignment is filtered inside the helper).- if (task.assigneeUserId !== resolved.assigneeUserId) {- notifyAssignedBestEffort(ctx, task);- }- return { data: task, message: 'Task updated', success: true };- } catch (error) {- if (error instanceof TRPCError) throw error;- console.error('[task:update]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to update task',- });- }- }),-- updateVisibility: taskProcedureWrite- .input(idInput.merge(z.object({ visibility: z.enum(['private', 'public']) })))- .mutation(async ({ input, ctx }) => {- try {- const resolved = await resolveOrThrow(ctx.taskModel, input.id);-- // Mirror the edit-lock contract from `update`: reject visibility flips- // while another workspace member is actively editing this task. Without- // this check a collaborator could silently retitle a private task to- // public (or vice versa) while you're mid-edit.- if (ctx.workspaceId) {- const blockedBy = await ctx.editLockService.getBlockingHolder('task', resolved.id);- if (blockedBy) {- throw new TRPCError({- cause: { data: { code: 'DocumentLocked' } },- code: 'CONFLICT',- message: 'Task is being edited by another user',- });- }- }-- // The creator can always change visibility on their own tasks. In- // workspace mode, workspace owners may still promote other members'- // tasks (mirrors the transferTask policy at line ~1166), but demoting- // to private stays creator-only: the task would land in- // the creator's private list, so an owner-initiated demotion just- // appropriates another member's data.- if (ctx.workspaceId && resolved.createdByUserId !== ctx.userId) {- if (input.visibility === 'private') {- throw new TRPCError({- code: 'FORBIDDEN',- message: 'Only the task creator can make this task private',- });- }- const canOverride = await hasWorkspaceScopedPermission({- action: 'AGENT_UPDATE',- db: ctx.serverDB,- scopes: ['ALL'],- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });- if (!canOverride) {- throw new TRPCError({- code: 'FORBIDDEN',- message: 'Only the task creator or workspace owner can change visibility',- });- }- }-- // Demoting a mixed-creator subtree would fracture it: each descendant- // stays owned by its creator, so the root creator loses other- // members' subtasks while those members keep orphaned children whose- // parent is hidden. Reject early β the subtree must be single-creator- // to go private.- if (input.visibility === 'private') {- const hasOtherCreators = await ctx.taskModel.subtreeHasOtherCreators(- resolved.id,- resolved.createdByUserId,- );- if (hasOtherCreators) {- throw new TRPCError({- code: 'BAD_REQUEST',- message:- 'Cannot make this task private while it has subtasks created by other members. Reassign or remove those subtasks first.',- });- }- }-- // Demoting a member-assigned task to private would strand the- // assignee: the task disappears from their view while still carrying- // their name. Reject early β unassign first, then demote.- if (input.visibility === 'private') {- ctx.taskService.assertAssigneeUserVisibilityCompat(- input.visibility,- resolved.assigneeUserId,- resolved.createdByUserId,- );- }-- // A private assignee agent on a public task breaks the visibility- // invariant. Reject early β reassign first, then promote.- if (input.visibility === 'public' && resolved.assigneeAgentId) {- const agentVisibility = await ctx.agentModel.getAgentVisibility(resolved.assigneeAgentId);- ctx.taskService.assertAgentVisibilityCompat(input.visibility, agentVisibility);- }-- // A public subtask under a private parent would be orphaned in the- // workspace view β a subtask cannot be more public than its parent.- // The user must promote the parent chain first, or keep it private.- if (input.visibility === 'public' && resolved.parentTaskId) {- const parent = await ctx.taskModel.findById(resolved.parentTaskId);- ctx.taskService.assertParentVisibilityCompat(input.visibility, parent?.visibility);- }-- const updated = await ctx.taskSubtree.updateVisibility(resolved.id, input.visibility);- if (!updated) throw new TRPCError({ code: 'NOT_FOUND', message: 'Task not found' });- return { data: updated, message: 'Task visibility updated', success: true };- } catch (error) {- if (error instanceof TRPCError) throw error;- console.error('[task:updateVisibility]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to update task visibility',- });- }- }),-- acquireTaskLock: taskProcedureWrite.input(idInput).mutation(async ({ ctx, input }) => {- if (!ctx.workspaceId) return { expiresAt: null, holderId: null, lockedByOther: false };- const resolved = await resolveOrThrow(ctx.taskModel, input.id);- const prev = await ctx.editLockService.getActiveHolder('task', resolved.id);- const result = await ctx.editLockService.acquire('task', resolved.id);- if ((result.holderId ?? null) !== (prev ?? null)) {- void publishResourceEvent(- { id: resolved.id, type: 'task' },- { actorId: ctx.userId, data: { holderId: result.holderId }, type: 'lock.changed' },- );- }- return result;- }),-- getTaskLock: taskProcedureWrite.input(idInput).query(async ({ ctx, input }) => {- if (!ctx.workspaceId) return { expiresAt: null, holderId: null, lockedByOther: false };- const resolved = await resolveOrThrow(ctx.taskModel, input.id);- const holder = await ctx.editLockService.getActiveHolder('task', resolved.id);- return {- expiresAt: null,- holderId: holder ?? null,- lockedByOther: Boolean(holder) && holder !== ctx.userId,- };- }),-- releaseTaskLock: taskProcedureWrite.input(idInput).mutation(async ({ ctx, input }) => {- if (!ctx.workspaceId) return;- const resolved = await resolveOrThrow(ctx.taskModel, input.id);- // Only broadcast "unlocked" when we actually released our own lock β if the- // lease expired and another member took over, the lock is still held.- const released = await ctx.editLockService.release('task', resolved.id);- if (!released) return;- void publishResourceEvent(- { id: resolved.id, type: 'task' },- { actorId: ctx.userId, data: { holderId: null }, type: 'lock.changed' },- );- }),-- updateConfig: taskProcedureWrite- .input(idInput.merge(z.object({ config: z.record(z.string(), z.unknown()) })))- .mutation(async ({ input, ctx }) => {- const { id, config } = input;- try {- const model = ctx.taskModel;- const resolved = await resolveOrThrow(model, id);- const task = await model.updateTaskConfig(resolved.id, config);- if (!task) throw new TRPCError({ code: 'NOT_FOUND', message: 'Task not found' });- return { data: task, message: 'Config updated', success: true };- } catch (error) {- if (error instanceof TRPCError) throw error;- console.error('[task:updateConfig]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to update task config',- });- }- }),-- previewSubtaskLayers: taskProcedure.input(idInput).query(async ({ input, ctx }) => {- try {- const plan = await ctx.taskService.previewSubtaskLayers(input.id);- return { data: plan, success: true };- } catch (error) {- if (error instanceof TRPCError) throw error;- console.error('[task:previewSubtaskLayers]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to plan subtask layers',- });- }- }),-- runReadySubtasks: taskProcedureWrite.input(idInput).mutation(async ({ input, ctx }) => {- try {- 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);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to run subtasks',- });- }- }),-- updateStatus: taskProcedureWrite- .input(- z.object({- actorAgentId: z.string().optional(),- error: z.string().optional(),- id: z.string(),- operationId: z.string().optional(),- status: z.enum(TASK_STATUSES),- }),- )- .mutation(async ({ input, ctx }) => {- const { actorAgentId, ...statusInput } = input;- try {- // A person (or their agent) changed it: record who. System- // transitions call the service without an actor and stay silent.- const actor = await resolveActivityActor(ctx, actorAgentId);- const result = await ctx.taskService.updateStatus(statusInput, actor);- const {- task,- unlocked,- paused,- checkpointTriggered,- allSubtasksDone,- parentTaskId,- completionDeferred,- } = result;- return {- data: task,- message: `Task ${input.status}`,- success: true,- ...(completionDeferred && { completionDeferred: true }),- ...(unlocked.length > 0 && { unlocked }),- ...(paused.length > 0 && { paused }),- ...(checkpointTriggered && { checkpointTriggered: true }),- ...(allSubtasksDone && { allSubtasksDone: true, parentTaskId }),- };- } catch (error) {- if (error instanceof TRPCError) throw error;- console.error('[task:updateStatus]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to update status',- });- }- }),-- updateStatusCascade: taskProcedureWrite- .input(- z.object({- id: z.string(),- status: z.enum(['canceled', 'completed']),- }),- )- .mutation(async ({ input, ctx }) => {- try {- const result = await ctx.taskService.updateStatusCascade(- input,- await resolveActivityActor(ctx),- );- return { data: result, message: `Task family ${input.status}`, success: true };- } catch (error) {- if (error instanceof TRPCError) throw error;- console.error('[task:updateStatusCascade]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to update task family status',- });- }- }),-- usage: taskProcedure.input(idInput).query(async ({ input, ctx }) => {- try {- const task = await resolveOrThrow(ctx.taskModel, input.id);- const usage = await ctx.taskTopicModel.sumRunCostByTaskIds([task.id]);-- return {- data: { ...usage, taskId: task.id, taskIdentifier: task.identifier },- success: true,- };- } catch (error) {- if (error instanceof TRPCError) throw error;- console.error('[task:usage]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to get task usage',- });- }- }),-- // Cross-workspace task *transfer* is intentionally not supported anymore:- // moving a task drags its whole subtree plus history (dependencies,- // documents, comments) out of the workspace. Use `copyTaskToWorkspace`,- // which clones the task definition only. The procedure is kept as a- // compatibility stub so already-released clients get a stable business- // error instead of a procedure-not-found failure.- transferTask: taskProcedureWrite- .input(- z.object({- targetVisibility: z.enum(['private', 'public']).optional(),- targetWorkspaceId: z.string().nullable(),- taskId: z.string(),- }),- )- .mutation(async () => {- throw new TRPCError({- cause: { data: { code: TransferErrorCode.TransferNotSupported } },- code: 'PRECONDITION_FAILED',- message: 'Task transfer is no longer supported; use copyTaskToWorkspace instead',- });- }),-- copyTaskToWorkspace: taskProcedureWrite- .input(- z.object({- targetVisibility: z.enum(['private', 'public']).optional(),- targetWorkspaceId: z.string().nullable(),- taskId: z.string(),- }),- )- .mutation(async ({ ctx, input }) => {- const task = await ctx.taskModel.resolve(input.taskId);- if (!task)- throw new TRPCError({- cause: { data: { code: TransferErrorCode.ResourceNotFound } },- code: 'NOT_FOUND',- message: 'Task not found',- });-- // No source-side creator gate: copy is non-destructive and clones the- // task definition only, so any member who can resolve the task (the- // visibility-aware `resolve` above already hides others' private tasks)- // may copy it.- if (input.targetWorkspaceId) {- const canWriteTarget = await hasWorkspaceScopedPermission({- action: 'AGENT_UPDATE',- db: ctx.serverDB,- userId: ctx.userId,- workspaceId: input.targetWorkspaceId,- });- if (!canWriteTarget) {- throw new TRPCError({- cause: { data: { code: TransferErrorCode.TargetNoWriteAccess } },- code: 'FORBIDDEN',- message: 'No write access to target workspace',- });- }- }-- return ctx.taskModel.copyToWorkspace(- task.id,- input.targetWorkspaceId,- ctx.userId,- input.targetVisibility,- );- }),-});diff --git a/apps/server/src/routers/lambda/task/comments.ts b/apps/server/src/routers/lambda/task/comments.tsnew file mode 100644index 00000000000..56388677ada--- /dev/null+++ b/apps/server/src/routers/lambda/task/comments.ts@@ -0,0 +1,255 @@+import { TRPCError } from '@trpc/server';+import { z } from 'zod';++import type { TaskCommentActivityRecipient } from '@/business/server/task/notifyTaskCommentActivity';+import { notifyTaskCommentActivity } from '@/business/server/task/notifyTaskCommentActivity';+import type { TaskModel } from '@/database/models/task';+import type { LobeChatDatabase } from '@/database/type';+import { router } from '@/libs/trpc/lambda';+import { assertAssigneeAgentBelongsToUser } from '@/server/services/task/patchValidation';+import {+ extractMentionedUserIds,+ filterActiveWorkspaceMemberIds,+ validateMentionedUserIds,+} from '@/server/utils/commentMentions';+import { after } from '@/server/utils/scheduleAfterResponse';++import { resolveOrThrow, taskProcedureWrite } from './procedures';++/**+ * Recipients of a new member comment on a task: the creator and the member+ * assignee as ambient `commented` pings, upgraded to `mentioned` when the+ * comment @mentions them. The actor never appears in the result.+ */+function collectTaskCommentRecipients(params: {+ actorUserId: string;+ mentionedUserIds: string[];+ task: { assigneeUserId: string | null; createdByUserId: string };+}): TaskCommentActivityRecipient[] {+ const { actorUserId, mentionedUserIds, task } = params;+ const byUserId = new Map<string, TaskCommentActivityRecipient['kind']>();+ for (const userId of [task.createdByUserId, task.assigneeUserId]) {+ if (userId) byUserId.set(userId, 'commented');+ }+ for (const userId of mentionedUserIds) byUserId.set(userId, 'mentioned');+ byUserId.delete(actorUserId);+ return [...byUserId].map(([userId, kind]) => ({ kind, userId }));+}++/**+ * Whether a notification deep-linking to `task` would land on a page `userId`+ * cannot open. Mirrors `TaskModel.ownership()`: public tasks are visible to+ * every member, private ones only to their creator. Membership is a separate+ * check (`filterActiveWorkspaceMemberIds`).+ */+function isTaskHiddenFrom(+ task: { createdByUserId: string; visibility: 'private' | 'public' },+ userId: string,+): boolean {+ return task.visibility === 'private' && task.createdByUserId !== userId;+}++interface TaskNotificationCtx {+ serverDB: LobeChatDatabase;+ taskModel: TaskModel;+ workspaceId: string;+}++/**+ * Re-authorize every recipient against the task before any id reaches the+ * delivery slot (same contract as topic and document comments): a member+ * @mentioned on a private task they cannot see must not receive its title and+ * link, and the creator / assignee rows can outlive workspace membership.+ */+async function filterRecipientsByTaskAccess(+ ctx: TaskNotificationCtx,+ taskId: string,+ recipients: TaskCommentActivityRecipient[],+): Promise<TaskCommentActivityRecipient[]> {+ if (recipients.length === 0) return [];+ const task = await ctx.taskModel.findById(taskId);+ if (!task) return [];++ const visible = recipients.filter(({ userId }) => !isTaskHiddenFrom(task, userId));+ const activeUserIds = new Set(+ await filterActiveWorkspaceMemberIds(+ ctx.serverDB,+ ctx.workspaceId,+ visible.map(({ userId }) => userId),+ ),+ );+ return visible.filter(({ userId }) => activeUserIds.has(userId));+}++/**+ * Member comment ping (Linear-style), delivered after the response as+ * best-effort work: the `@/business` slot defaults to a no-op, and a rejecting+ * implementation must neither fail the mutation nor surface as an unhandled+ * rejection. `after()` keeps the work alive past the response on serverless.+ */+function notifyCommentActivityBestEffort(+ ctx: TaskNotificationCtx,+ params: Parameters<typeof notifyTaskCommentActivity>[0],+) {+ after(async () => {+ try {+ const recipients = await filterRecipientsByTaskAccess(ctx, params.taskId, params.recipients);+ if (recipients.length === 0) return;+ await notifyTaskCommentActivity({ ...params, recipients });+ } catch (error) {+ console.error('[task-comment] Failed to send activity notification', error);+ }+ });+}++export const commentsRouter = router({+ addComment: taskProcedureWrite+ .input(+ z.object({+ authorAgentId: z.string().optional(),+ briefId: z.string().optional(),+ content: z.string().min(1),+ editorData: z.unknown().optional(),+ id: z.string(),+ topicId: z.string().optional(),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ try {+ const model = ctx.taskModel;+ const task = await resolveOrThrow(model, input.id);+ await assertAssigneeAgentBelongsToUser(+ ctx.serverDB,+ { userId: ctx.userId, workspaceId: ctx.workspaceId ?? undefined },+ input.authorAgentId,+ );+ // Resolve @mentions before the insert so an invalid editorData never+ // leaves a comment behind that nobody was told about.+ const mentionedUserIds =+ ctx.workspaceId && !input.authorAgentId+ ? await validateMentionedUserIds(+ ctx.serverDB,+ { actorUserId: ctx.userId, workspaceId: ctx.workspaceId },+ input.editorData,+ )+ : [];+ const comment = await model.addComment({+ authorAgentId: input.authorAgentId,+ authorUserId: input.authorAgentId ? undefined : ctx.userId,+ briefId: input.briefId,+ content: input.content,+ editorData: input.editorData as never,+ taskId: task.id,+ topicId: input.topicId,+ userId: ctx.userId,+ });+ // Member comment ping (Linear-style): the task creator and the member+ // assignee learn about new discussion; @mentioned members get the+ // stronger "mentioned" notification instead. Agent-authored progress+ // notes stay silent β they are not a conversation between members.+ if (ctx.workspaceId && !input.authorAgentId) {+ const recipients = collectTaskCommentRecipients({+ actorUserId: ctx.userId,+ mentionedUserIds,+ task,+ });+ if (recipients.length > 0) {+ notifyCommentActivityBestEffort(+ { serverDB: ctx.serverDB, taskModel: model, workspaceId: ctx.workspaceId },+ {+ actorUserId: ctx.userId,+ commentId: comment.id,+ recipients,+ taskId: task.id,+ workspaceId: ctx.workspaceId,+ },+ );+ }+ }+ return { data: comment, message: 'Comment added', success: true };+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ console.error('[task:addComment]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to add comment',+ });+ }+ }),+ deleteComment: taskProcedureWrite+ .input(z.object({ commentId: z.string() }))+ .mutation(async ({ input, ctx }) => {+ try {+ const deleted = await ctx.taskModel.deleteComment(input.commentId);+ if (!deleted) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Comment not found' });+ }+ return { message: 'Comment deleted', success: true };+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ console.error('[task:deleteComment]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to delete comment',+ });+ }+ }),+ updateComment: taskProcedureWrite+ .input(+ z.object({+ commentId: z.string(),+ content: z.string().min(1),+ editorData: z.unknown().optional(),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ try {+ const workspaceId = ctx.workspaceId ?? undefined;+ const previous = await ctx.taskModel.findCommentById(input.commentId);+ if (!previous) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Comment not found' });+ }+ // Only members @mentioned for the first time by this edit are pinged;+ // mentions kept from the previous revision were already notified.+ let addedMentionUserIds: string[] = [];+ if (workspaceId && !previous.authorAgentId && input.editorData !== undefined) {+ const previousMentions = new Set(extractMentionedUserIds(previous.editorData));+ const nextMentions = await validateMentionedUserIds(+ ctx.serverDB,+ { actorUserId: ctx.userId, workspaceId },+ input.editorData,+ );+ addedMentionUserIds = nextMentions.filter((id) => !previousMentions.has(id));+ }+ const comment = await ctx.taskModel.updateComment(input.commentId, input.content, {+ editorData: input.editorData === undefined ? null : input.editorData,+ });+ if (!comment) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Comment not found' });+ }+ if (workspaceId && addedMentionUserIds.length > 0) {+ notifyCommentActivityBestEffort(+ { serverDB: ctx.serverDB, taskModel: ctx.taskModel, workspaceId },+ {+ actorUserId: ctx.userId,+ commentId: comment.id,+ recipients: addedMentionUserIds.map((userId) => ({ kind: 'mentioned', userId })),+ taskId: comment.taskId,+ workspaceId,+ },+ );+ }+ return { data: comment, message: 'Comment updated', success: true };+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ console.error('[task:updateComment]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to update comment',+ });+ }+ }),+});diff --git a/apps/server/src/routers/lambda/task/execution.ts b/apps/server/src/routers/lambda/task/execution.tsnew file mode 100644index 00000000000..f4841987634--- /dev/null+++ b/apps/server/src/routers/lambda/task/execution.ts@@ -0,0 +1,144 @@+import { TRPCError } from '@trpc/server';+import { z } from 'zod';++import { router } from '@/libs/trpc/lambda';+import { failStuckTasks } from '@/server/services/taskLifecycle/failStuckTasks';+import { TaskRunnerService } from '@/server/services/taskRunner';++import { idInput, resolveOrThrow, taskProcedure, taskProcedureWrite } from './procedures';++export const executionRouter = router({+ run: taskProcedureWrite+ .input(+ idInput.merge(+ z.object({+ continueTopicId: z.string().optional(),+ deviceId: z.string().optional(),+ prompt: z.string().optional(),+ }),+ ),+ )+ .mutation(async ({ input, ctx }) => {+ try {+ const task = await resolveOrThrow(ctx.taskModel, input.id);++ const runner = new TaskRunnerService(+ ctx.serverDB,+ ctx.userId,+ ctx.workspaceId ?? undefined,+ );+ return await runner.runTask({+ continueTopicId: input.continueTopicId,+ deviceId: input.deviceId,+ extraPrompt: input.prompt,+ taskId: task.id,+ });+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ console.error('[task:run]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to run task',+ });+ }+ }),+ heartbeat: taskProcedureWrite.input(idInput).mutation(async ({ input, ctx }) => {+ try {+ const model = ctx.taskModel;+ const task = await resolveOrThrow(model, input.id);+ await model.updateHeartbeat(task.id);+ return { message: 'Heartbeat updated', success: true };+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ console.error('[task:heartbeat]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to update heartbeat',+ });+ }+ }),+ watchdog: taskProcedureWrite.mutation(async ({ ctx }) => {+ try {+ const { checked, failed } = await failStuckTasks(ctx.serverDB);++ return {+ checked,+ failed,+ message:+ failed.length > 0+ ? `${failed.length} stuck tasks marked as failed`+ : 'No stuck tasks found',+ success: true,+ };+ } catch (error) {+ console.error('[task:watchdog]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Watchdog check failed',+ });+ }+ }),+ cancelTopic: taskProcedureWrite+ .input(z.object({ topicId: z.string() }))+ .mutation(async ({ input, ctx }) => {+ try {+ await ctx.taskService.cancelTopic(input.topicId);+ return { message: 'Topic canceled', success: true };+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ console.error('[task:cancelTopic]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to cancel topic',+ });+ }+ }),+ deleteTopic: taskProcedureWrite+ .input(z.object({ topicId: z.string() }))+ .mutation(async ({ input, ctx }) => {+ try {+ await ctx.taskService.deleteTopic(input.topicId);+ return { message: 'Topic deleted', success: true };+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ console.error('[task:deleteTopic]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to delete topic',+ });+ }+ }),+ previewSubtaskLayers: taskProcedure.input(idInput).query(async ({ input, ctx }) => {+ try {+ const plan = await ctx.taskService.previewSubtaskLayers(input.id);+ return { data: plan, success: true };+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ console.error('[task:previewSubtaskLayers]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to plan subtask layers',+ });+ }+ }),+ runReadySubtasks: taskProcedureWrite.input(idInput).mutation(async ({ input, ctx }) => {+ try {+ 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);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to run subtasks',+ });+ }+ }),+});diff --git a/apps/server/src/routers/lambda/task/index.procedures.test.ts b/apps/server/src/routers/lambda/task/index.procedures.test.tsnew file mode 100644index 00000000000..4ad22ac4bcd--- /dev/null+++ b/apps/server/src/routers/lambda/task/index.procedures.test.ts@@ -0,0 +1,77 @@+// @vitest-environment node+import { describe, expect, it } from 'vitest';++import { taskRouter } from '.';++/**+ * Pins the router's public surface: every procedure path, its kind, and its+ * middleware chain length (which encodes the procedure builder and its input+ * parsers). Splitting the router across files must keep all three.+ */+describe('taskRouter procedures', () => {+ const procedures = (taskRouter as any)._def.procedures as Record<string, any>;++ it('exposes exactly the expected procedure paths', () => {+ expect(Object.keys(procedures).sort()).toEqual(expected().map(([name]) => name));+ });++ it.each(expected())('%s is a %s with %i middlewares', (name, type, middlewares) => {+ expect(procedures[name]._def.type).toBe(type);+ expect(procedures[name]._def.middlewares).toHaveLength(middlewares);+ });+});++function expected(): Array<+ [name: string, type: 'mutation' | 'query' | 'subscription', middlewares: number]+> {+ return [+ ['acquireTaskLock', 'mutation', 13],+ ['addComment', 'mutation', 13],+ ['addDependency', 'mutation', 13],+ ['analyzeIntent', 'mutation', 13],+ ['archive', 'mutation', 13],+ ['cancelTopic', 'mutation', 13],+ ['clearAll', 'mutation', 12],+ ['copyTaskToWorkspace', 'mutation', 13],+ ['create', 'mutation', 13],+ ['delete', 'mutation', 13],+ ['deleteComment', 'mutation', 13],+ ['deleteTopic', 'mutation', 13],+ ['detail', 'query', 12],+ ['find', 'query', 12],+ ['getCheckpoint', 'query', 12],+ ['getDependencies', 'query', 12],+ ['getPinnedDocuments', 'query', 12],+ ['getReview', 'query', 12],+ ['getSubtasks', 'query', 12],+ ['getTaskLock', 'query', 13],+ ['getTaskTree', 'query', 12],+ ['getTopics', 'query', 12],+ ['getVerifyConfig', 'query', 12],+ ['groupList', 'query', 12],+ ['heartbeat', 'mutation', 13],+ ['list', 'query', 12],+ ['pinDocument', 'mutation', 13],+ ['previewSubtaskLayers', 'query', 12],+ ['releaseTaskLock', 'mutation', 13],+ ['removeDependency', 'mutation', 13],+ ['reorderSubtasks', 'mutation', 13],+ ['run', 'mutation', 13],+ ['runReadySubtasks', 'mutation', 13],+ ['runReview', 'mutation', 13],+ ['synthesizeInstruction', 'mutation', 13],+ ['transferTask', 'mutation', 13],+ ['unpinDocument', 'mutation', 13],+ ['update', 'mutation', 13],+ ['updateCheckpoint', 'mutation', 13],+ ['updateComment', 'mutation', 13],+ ['updateConfig', 'mutation', 13],+ ['updateReview', 'mutation', 13],+ ['updateStatus', 'mutation', 13],+ ['updateStatusCascade', 'mutation', 13],+ ['updateVerifyConfig', 'mutation', 13],+ ['updateVisibility', 'mutation', 13],+ ['usage', 'query', 12],+ ['watchdog', 'mutation', 12],+ ];+}diff --git a/apps/server/src/routers/lambda/task/index.ts b/apps/server/src/routers/lambda/task/index.tsnew file mode 100644index 00000000000..2c26ae80e09--- /dev/null+++ b/apps/server/src/routers/lambda/task/index.ts@@ -0,0 +1,19 @@+import { mergeRouters } from '@/libs/trpc/lambda';++import { commentsRouter } from './comments';+import { executionRouter } from './execution';+import { lifecycleRouter } from './lifecycle';+import { queriesRouter } from './queries';+import { relationsRouter } from './relations';+import { reviewRouter } from './review';+import { updateRouter } from './update';++export const taskRouter = mergeRouters(+ lifecycleRouter,+ relationsRouter,+ commentsRouter,+ executionRouter,+ queriesRouter,+ reviewRouter,+ updateRouter,+);diff --git a/apps/server/src/routers/lambda/task/lifecycle.ts b/apps/server/src/routers/lambda/task/lifecycle.tsnew file mode 100644index 00000000000..7356dd0b1ee--- /dev/null+++ b/apps/server/src/routers/lambda/task/lifecycle.ts@@ -0,0 +1,318 @@+import { AgentRuntimeErrorType } from '@lobechat/model-runtime';+import { TRPCError } from '@trpc/server';+import { z } from 'zod';++import { TaskArchiveModel } from '@/database/models/taskArchive';+import { router } from '@/libs/trpc/lambda';+import { markSilentTRPCErrorLog } from '@/libs/trpc/utils/errorLogger';+import { assertNotInOpenGoal } from '@/server/services/task/archiveGuard';+import { notifyAssignedBestEffort } from '@/server/services/task/assignmentNotification';+import {+ assertResultingScheduleValid,+ schedulePatternSchema,+ scheduleTimezoneSchema,+} from '@/server/services/task/scheduleValidation';+import { AcceptanceService } from '@/server/services/verify/acceptanceService';+import { hasWorkspaceScopedPermission } from '@/server/services/workspacePermission';+import { TransferErrorCode } from '@/types/transferError';++import { assertWorkspaceRowManageable } from '../_helpers/assertWorkspaceRowManageable';+import {+ idInput,+ resolveOrThrow,+ taskProcedureWrite,+ taskVerifyConfigPatchSchema,+} from './procedures';++// Priority: 0=None, 1=Urgent, 2=High, 3=Normal, 4=Low+// Unknown fields are stripped, including the removed identifierPrefix. Released+// CLI clients send 'T' by default; ignore it so project subtasks use their project+// identifier without breaking ordinary creates from those clients.+const createSchema = z.object({+ assigneeAgentId: z.string().optional(),+ assigneeUserId: z.string().optional(),+ // Optional schedule wiring at create time. When `automationMode` is+ // 'schedule', `schedulePattern` (cron) is required for the central+ // schedule-dispatch sweep to pick the task up.+ automationMode: z.enum(['heartbeat', 'schedule']).optional(),+ config: z.record(z.string(), z.unknown()).optional(),+ createdByAgentId: z.string().optional(),+ description: z.string().optional(),+ editorData: z.unknown().optional(),+ instruction: z.string().min(1),+ name: z.string().optional(),+ parentTaskId: z.string().optional(),+ priority: z.number().min(0).max(4).optional(),+ projectId: z.string().optional(),+ schedulePattern: schedulePatternSchema.optional(),+ scheduleTimezone: scheduleTimezoneSchema.optional(),+ // When omitted, the server derives visibility from the parent task or the+ // assignee agent's visibility (private agent β private task). UI surfaces+ // such as the top-level "Tasks" create form pass it explicitly.+ visibility: z.enum(['private', 'public']).optional(),+ // Removed contract, kept so the server can recognise it. A task no longer+ // carries a goal β the Goal Graph owns execution and dispatches its own Work+ // Tasks β and silently dropping this field would let a released client report+ // that a goal started when only an ordinary task exists.+ goal: z.unknown().optional(),+});++export const lifecycleRouter = router({+ /**+ * Read a composer draft and report what it means β a name, the outcome as+ * understood, the questions that would change the deliverable, and whether+ * it is really a standing goal. Returns a reading only; nothing is created.+ */+ analyzeIntent: taskProcedureWrite+ .input(+ z.object({+ context: z.string().optional(),+ instruction: z.string().min(1).max(20_000),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ try {+ return await ctx.taskIntentService.analyze(input);+ } catch (error) {+ const errorType = (error as { errorType?: unknown } | null)?.errorType;+ if (errorType === AgentRuntimeErrorType.InvalidProviderAPIKey) {+ const trpcError = new TRPCError({+ cause: error,+ code: 'PRECONDITION_FAILED',+ message: AgentRuntimeErrorType.InvalidProviderAPIKey,+ });+ // Runtime errors are plain payloads, so tRPC normalizes them into an+ // Error cause; mark the cause the shared handler actually receives.+ markSilentTRPCErrorLog(trpcError.cause);+ throw trpcError;+ }++ throw error;+ }+ }),+ /**+ * Rewrite a confirmed draft into the brief that gets executed, folding in the+ * answers the user just gave. Returns a brief only; nothing is created.+ */+ synthesizeInstruction: taskProcedureWrite+ .input(+ z.object({+ answers: z+ .array(z.object({ answer: z.string().min(1), question: z.string().min(1) }))+ .max(3),+ context: z.string().optional(),+ instruction: z.string().min(1).max(20_000),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ try {+ return await ctx.taskIntentService.synthesize(input);+ } catch (error) {+ const errorType = (error as { errorType?: unknown } | null)?.errorType;+ if (errorType === AgentRuntimeErrorType.InvalidProviderAPIKey) {+ const trpcError = new TRPCError({+ cause: error,+ code: 'PRECONDITION_FAILED',+ message: AgentRuntimeErrorType.InvalidProviderAPIKey,+ });+ markSilentTRPCErrorLog(trpcError.cause);+ throw trpcError;+ }++ throw error;+ }+ }),+ create: taskProcedureWrite.input(createSchema).mutation(async ({ input, ctx }) => {+ const { goal: legacyGoal, ...createInput } = input;+ if (legacyGoal !== undefined) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message:+ 'Creating a goal through task.create is no longer supported. Reload the app, then create the goal again.',+ });+ }+ assertResultingScheduleValid(null, createInput);+ try {+ const parsedVerify = taskVerifyConfigPatchSchema.safeParse(createInput.config?.verify);+ const { verify: _legacyVerify, ...taskConfig } = createInput.config ?? {};+ const task = await ctx.taskService.createTask({+ ...createInput,+ config: parsedVerify.success ? taskConfig : createInput.config,+ });+ try {+ if (parsedVerify.success) {+ const { requirement, ...rawConfig } = parsedVerify.data;+ const config = Object.fromEntries(+ Object.entries(rawConfig).filter(([, value]) => value != null),+ );+ await new AcceptanceService(+ ctx.serverDB,+ ctx.userId,+ ctx.workspaceId ?? undefined,+ ).ensureForSubject('task', task.id, {+ config,+ requirement: requirement ?? undefined,+ });+ }+ } catch (error) {+ await ctx.taskModel.delete(task.id).catch(() => {});+ throw error;+ }+ // Creating a task already assigned to another member notifies them.+ notifyAssignedBestEffort(ctx, task);+ return { data: task, message: 'Task created', success: true };+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ console.error('[task:create]', error);+ const causeMessage = error instanceof Error ? error.message : String(error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: causeMessage ? `Failed to create task: ${causeMessage}` : 'Failed to create task',+ });+ }+ }),+ clearAll: taskProcedureWrite.mutation(async ({ ctx }) => {+ try {+ const model = ctx.taskModel;+ // Workspace clear-all is caller-scoped for every role β owners included+ // (per docs/usage/workspace-permissions: bulk actions only affect+ // caller-created content).+ const restrictToCreator = !!ctx.workspaceId;+ const count = await model.deleteAll({ restrictToCreator });+ return { count, message: `${count} tasks deleted`, success: true };+ } catch (error) {+ console.error('[task:clearAll]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to clear tasks',+ });+ }+ }),+ delete: taskProcedureWrite.input(idInput).mutation(async ({ input, ctx }) => {+ try {+ const task = await resolveOrThrow(ctx.taskModel, input.id);+ assertWorkspaceRowManageable(ctx, task.createdByUserId, 'task');+ await ctx.taskService.deleteTask(task.id);+ return { data: task, message: 'Task deleted', success: true };+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ console.error('[task:delete]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to delete task',+ });+ }+ }),+ // User-only close-out: no builtin agent tool exposes it, so an agent never+ // archives a task on its own. `status` is left untouched.+ archive: taskProcedureWrite+ .input(idInput.extend({ archived: z.boolean() }))+ .mutation(async ({ input, ctx }) => {+ try {+ const task = await resolveOrThrow(ctx.taskModel, input.id);+ // Archiving hides a shared task from every member's lists: same+ // creator-or-owner scope as delete.+ assertWorkspaceRowManageable(ctx, task.createdByUserId, 'task');+ if (input.archived) {+ await assertNotInOpenGoal(+ ctx.serverDB,+ { userId: ctx.userId, workspaceId: ctx.workspaceId ?? undefined },+ task,+ );+ }+ const archiveModel = new TaskArchiveModel(+ ctx.serverDB,+ ctx.userId,+ ctx.workspaceId ?? undefined,+ );+ // Archived rows leave every list, so live work would run out of sight.+ // The guard is part of the UPDATE, so a run starting concurrently can't slip past.+ const updated = input.archived+ ? await archiveModel.archive(task.id)+ : await archiveModel.unarchive(task.id);+ if (!updated) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'Stop the running task or its schedule/heartbeat before archiving it',+ });+ }+ return { data: updated, success: true };+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ console.error('[task:archive]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to archive task',+ });+ }+ }),+ // Cross-workspace task *transfer* is intentionally not supported anymore:+ // moving a task drags its whole subtree plus history (dependencies,+ // documents, comments) out of the workspace. Use `copyTaskToWorkspace`,+ // which clones the task definition only. The procedure is kept as a+ // compatibility stub so already-released clients get a stable business+ // error instead of a procedure-not-found failure.+ transferTask: taskProcedureWrite+ .input(+ z.object({+ targetVisibility: z.enum(['private', 'public']).optional(),+ targetWorkspaceId: z.string().nullable(),+ taskId: z.string(),+ }),+ )+ .mutation(async () => {+ throw new TRPCError({+ cause: { data: { code: TransferErrorCode.TransferNotSupported } },+ code: 'PRECONDITION_FAILED',+ message: 'Task transfer is no longer supported; use copyTaskToWorkspace instead',+ });+ }),+ copyTaskToWorkspace: taskProcedureWrite+ .input(+ z.object({+ targetVisibility: z.enum(['private', 'public']).optional(),+ targetWorkspaceId: z.string().nullable(),+ taskId: z.string(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ const task = await ctx.taskModel.resolve(input.taskId);+ if (!task)+ throw new TRPCError({+ cause: { data: { code: TransferErrorCode.ResourceNotFound } },+ code: 'NOT_FOUND',+ message: 'Task not found',+ });++ // No source-side creator gate: copy is non-destructive and clones the+ // task definition only, so any member who can resolve the task (the+ // visibility-aware `resolve` above already hides others' private tasks)+ // may copy it.+ if (input.targetWorkspaceId) {+ const canWriteTarget = await hasWorkspaceScopedPermission({+ action: 'AGENT_UPDATE',+ db: ctx.serverDB,+ userId: ctx.userId,+ workspaceId: input.targetWorkspaceId,+ });+ if (!canWriteTarget) {+ throw new TRPCError({+ cause: { data: { code: TransferErrorCode.TargetNoWriteAccess } },+ code: 'FORBIDDEN',+ message: 'No write access to target workspace',+ });+ }+ }++ return ctx.taskModel.copyToWorkspace(+ task.id,+ input.targetWorkspaceId,+ ctx.userId,+ input.targetVisibility,+ );+ }),+});diff --git a/apps/server/src/routers/lambda/task/procedures.ts b/apps/server/src/routers/lambda/task/procedures.tsnew file mode 100644index 00000000000..b94bc56104b--- /dev/null+++ b/apps/server/src/routers/lambda/task/procedures.ts@@ -0,0 +1,60 @@+import { TRPCError } from '@trpc/server';+import { z } from 'zod';++import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';+import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';+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 { TaskSubtreeRepository } from '@/database/repositories/taskSubtree';+import { serverDatabase } from '@/libs/trpc/lambda/middleware';+import { EditLockService } from '@/server/services/editLock';+import { TaskService } from '@/server/services/task';+import { TaskIntentService } from '@/server/services/task/intent';+import { TaskLifecycleService } from '@/server/services/taskLifecycle';++export const taskProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {+ const { ctx } = opts;+ const wsId = ctx.workspaceId ?? undefined;+ return opts.next({+ ctx: {+ agentModel: new AgentModel(ctx.serverDB, ctx.userId, wsId),+ briefModel: new BriefModel(ctx.serverDB, ctx.userId, wsId),+ editLockService: new EditLockService(ctx.userId),+ taskLifecycle: new TaskLifecycleService(ctx.serverDB, ctx.userId, wsId),+ taskModel: new TaskModel(ctx.serverDB, ctx.userId, wsId),+ taskIntentService: new TaskIntentService(ctx.serverDB, ctx.userId, wsId),+ taskService: new TaskService(ctx.serverDB, ctx.userId, wsId),+ taskSubtree: new TaskSubtreeRepository(ctx.serverDB, ctx.userId, wsId),+ taskTopicModel: new TaskTopicModel(ctx.serverDB, ctx.userId, wsId),+ topicModel: new TopicModel(ctx.serverDB, ctx.userId, wsId),+ },+ });+});++// Write variant gates viewers out of every task mutation (create/update/delete/+// run). Reads keep using `taskProcedure` so viewers can still inspect tasks+// and their status.+export const taskProcedureWrite = taskProcedure.use(withScopedPermission('agent:update'));++// All procedures that take an id accept either raw id (task_xxx) or identifier (TASK-1)+// Resolution happens in the model layer via model.resolve()+export const idInput = z.object({ id: z.string() });++export const taskVerifyConfigPatchSchema = z.object({+ enabled: z.boolean().nullish(),+ maxIterations: z.number().min(1).max(10).nullish(),+ requirement: z.string().nullish(),+ verifierAgentId: z.string().nullish(),+ verifyCriteriaIds: z.array(z.string()).nullish(),+ verifyRubricId: z.string().nullish(),+});++// Helper: resolve id/identifier and throw if not found+export async function resolveOrThrow(model: TaskModel, id: string) {+ const task = await model.resolve(id);+ if (!task) throw new TRPCError({ code: 'NOT_FOUND', message: 'Task not found' });+ return task;+}diff --git a/apps/server/src/routers/lambda/task/queries.ts b/apps/server/src/routers/lambda/task/queries.tsnew file mode 100644index 00000000000..c86b095473f--- /dev/null+++ b/apps/server/src/routers/lambda/task/queries.ts@@ -0,0 +1,242 @@+import type { TaskListItem, TaskParticipant } from '@lobechat/types';+import { TRPCError } from '@trpc/server';++import { UserModel } from '@/database/models/user';+import { router } from '@/libs/trpc/lambda';++import { groupListSchema, listSchema } from '../_helpers/taskListSchemas';+import { idInput, resolveOrThrow, taskProcedure } from './procedures';++export const queriesRouter = router({+ detail: taskProcedure.input(idInput).query(async ({ input, ctx }) => {+ try {+ const detail = await ctx.taskService.getTaskDetail(input.id);+ if (!detail) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Task not found' });+ }++ return { data: detail, success: true };+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ console.error('[task:detail]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to get task detail',+ });+ }+ }),+ find: taskProcedure.input(idInput).query(async ({ input, ctx }) => {+ try {+ const model = ctx.taskModel;+ const task = await resolveOrThrow(model, input.id);+ return { data: task, success: true };+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ console.error('[task:find]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to find task',+ });+ }+ }),+ getDependencies: taskProcedure.input(idInput).query(async ({ input, ctx }) => {+ try {+ const model = ctx.taskModel;+ const task = await resolveOrThrow(model, input.id);+ const deps = await model.getDependencies(task.id);+ return { data: deps, success: true };+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ console.error('[task:getDependencies]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to get dependencies',+ });+ }+ }),+ getPinnedDocuments: taskProcedure.input(idInput).query(async ({ input, ctx }) => {+ try {+ const model = ctx.taskModel;+ const task = await resolveOrThrow(model, input.id);+ const docs = await model.getPinnedDocuments(task.id);+ return { data: docs, success: true };+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ console.error('[task:getPinnedDocuments]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to get documents',+ });+ }+ }),+ getTopics: taskProcedure.input(idInput).query(async ({ input, ctx }) => {+ try {+ const model = ctx.taskModel;+ const task = await resolveOrThrow(model, input.id);+ const results = await ctx.taskTopicModel.findWithDetails(task.id);+ return { data: results, success: true };+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ console.error('[task:getTopics]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to get task topics',+ });+ }+ }),+ getSubtasks: taskProcedure.input(idInput).query(async ({ input, ctx }) => {+ try {+ const model = ctx.taskModel;+ const task = await resolveOrThrow(model, input.id);+ const subtasks = await model.findSubtasks(task.id);+ return { data: subtasks, success: true };+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ console.error('[task:getSubtasks]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to get subtasks',+ });+ }+ }),+ getTaskTree: taskProcedure.input(idInput).query(async ({ input, ctx }) => {+ try {+ const model = ctx.taskModel;+ const task = await resolveOrThrow(model, input.id);+ const tree = await model.getTaskTree(task.id);+ return { data: tree, success: true };+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ console.error('[task:getTaskTree]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to get task tree',+ });+ }+ }),+ groupList: taskProcedure.input(groupListSchema).query(async ({ input, ctx }) => {+ try {+ const model = ctx.taskModel;+ const { scope, ...query } = input;+ const groups = await model.groupList({+ ...query,+ ...(scope === 'assigned' ? { assigneeUserId: ctx.userId } : {}),+ ...(scope === 'created' ? { createdByUserId: ctx.userId } : {}),+ });+ return { data: groups, success: true };+ } catch (error) {+ console.error('[task:groupList]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to fetch grouped tasks',+ });+ }+ }),+ list: taskProcedure.input(listSchema).query(async ({ input, ctx }) => {+ try {+ const model = ctx.taskModel;+ const { parentIdentifier, scope, ...query } = input;+ let parentTaskId = query.parentTaskId;++ if (parentIdentifier) {+ const parent = await model.resolve(parentIdentifier);+ if (!parent) {+ throw new TRPCError({+ code: 'NOT_FOUND',+ message: `Parent task not found: ${parentIdentifier}`,+ });+ }++ parentTaskId = parent.id;+ }++ const result = await model.list({+ ...query,+ ...(scope === 'assigned' ? { assigneeUserId: ctx.userId } : {}),+ ...(scope === 'created' ? { createdByUserId: ctx.userId } : {}),+ parentTaskId,+ });++ const assigneeIds = [+ ...new Set(result.tasks.map((t) => t.assigneeAgentId).filter((id): id is string => !!id)),+ ];+ const assigneeUserIds = [+ ...new Set(result.tasks.map((t) => t.assigneeUserId).filter((id): id is string => !!id)),+ ];+ const [agents, users] = await Promise.all([+ assigneeIds.length > 0 ? ctx.agentModel.getAgentAvatarsByIds(assigneeIds) : [],+ assigneeUserIds.length > 0+ ? UserModel.getDisplayInfoByIds(ctx.serverDB, assigneeUserIds)+ : [],+ ]);+ const agentMap = new Map(agents.map((a) => [a.id, a]));+ const userMap = new Map(users.map((u) => [u.id, u]));++ const data: TaskListItem[] = result.tasks.map((task) => {+ const participants: TaskParticipant[] = [];+ if (task.assigneeAgentId) {+ const agent = agentMap.get(task.assigneeAgentId);+ if (agent) {+ participants.push({+ avatar: agent.avatar,+ backgroundColor: agent.backgroundColor,+ id: agent.id,+ title: agent.title ?? '',+ type: 'agent',+ });+ }+ }+ if (task.assigneeUserId) {+ const user = userMap.get(task.assigneeUserId);+ if (user) {+ participants.push({+ avatar: user.avatar,+ backgroundColor: null,+ id: user.id,+ title: user.fullName ?? user.username ?? '',+ type: 'user',+ });+ }+ }+ return { ...task, participants };+ });++ return { data, success: true, total: result.total };+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ console.error('[task:list]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to list tasks',+ });+ }+ }),+ usage: taskProcedure.input(idInput).query(async ({ input, ctx }) => {+ try {+ const task = await resolveOrThrow(ctx.taskModel, input.id);+ const usage = await ctx.taskTopicModel.sumRunCostByTaskIds([task.id]);++ return {+ data: { ...usage, taskId: task.id, taskIdentifier: task.identifier },+ success: true,+ };+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ console.error('[task:usage]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to get task usage',+ });+ }+ }),+});diff --git a/apps/server/src/routers/lambda/task/relations.ts b/apps/server/src/routers/lambda/task/relations.tsnew file mode 100644index 00000000000..694ac2be011--- /dev/null+++ b/apps/server/src/routers/lambda/task/relations.ts@@ -0,0 +1,150 @@+import { TRPCError } from '@trpc/server';+import { z } from 'zod';++import { router } from '@/libs/trpc/lambda';++import { resolveOrThrow, taskProcedureWrite } from './procedures';++export const relationsRouter = router({+ reorderSubtasks: taskProcedureWrite+ .input(+ z.object({+ id: z.string(),+ // Ordered list of subtask identifiers (e.g. ['TASK-2', 'TASK-4', 'TASK-3'])+ order: z.array(z.string()),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ try {+ const model = ctx.taskModel;+ const task = await resolveOrThrow(model, input.id);+ const subtasks = await model.findSubtasks(task.id);++ // Build identifier β id map+ const idMap = new Map<string, string>();+ for (const s of subtasks) idMap.set(s.identifier, s.id);++ // Validate all identifiers exist+ const reorderItems: Array<{ id: string; sortOrder: number }> = [];+ for (let i = 0; i < input.order.length; i++) {+ const identifier = input.order[i].toUpperCase();+ const taskId = idMap.get(identifier);+ if (!taskId) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: `Subtask not found: ${identifier}`,+ });+ }+ reorderItems.push({ id: taskId, sortOrder: i });+ }++ await model.reorder(reorderItems);++ return {+ data: reorderItems.map((item, i) => ({+ identifier: input.order[i],+ sortOrder: item.sortOrder,+ })),+ message: 'Subtasks reordered',+ success: true,+ };+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ console.error('[task:reorderSubtasks]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to reorder subtasks',+ });+ }+ }),+ addDependency: taskProcedureWrite+ .input(+ z.object({+ dependsOnId: z.string(),+ taskId: z.string(),+ type: z.enum(['blocks', 'relates']).default('blocks'),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ try {+ const model = ctx.taskModel;+ const task = await resolveOrThrow(model, input.taskId);+ const dep = await resolveOrThrow(model, input.dependsOnId);+ await model.addDependency(task.id, dep.id, input.type);+ return { message: 'Dependency added', success: true };+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ console.error('[task:addDependency]', error);+ if (error instanceof Error && error.message.includes('project boundaries')) {+ throw new TRPCError({ cause: error, code: 'BAD_REQUEST', message: error.message });+ }+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to add dependency',+ });+ }+ }),+ removeDependency: taskProcedureWrite+ .input(z.object({ dependsOnId: z.string(), taskId: z.string() }))+ .mutation(async ({ input, ctx }) => {+ try {+ const model = ctx.taskModel;+ const task = await resolveOrThrow(model, input.taskId);+ const dep = await resolveOrThrow(model, input.dependsOnId);+ await model.removeDependency(task.id, dep.id);+ return { message: 'Dependency removed', success: true };+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ console.error('[task:removeDependency]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to remove dependency',+ });+ }+ }),+ pinDocument: taskProcedureWrite+ .input(+ z.object({+ documentId: z.string(),+ pinnedBy: z.string().default('user'),+ taskId: z.string(),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ try {+ const model = ctx.taskModel;+ const task = await resolveOrThrow(model, input.taskId);+ await model.pinDocument(task.id, input.documentId, input.pinnedBy);+ return { message: 'Document pinned', success: true };+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ console.error('[task:pinDocument]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to pin document',+ });+ }+ }),+ unpinDocument: taskProcedureWrite+ .input(z.object({ documentId: z.string(), taskId: z.string() }))+ .mutation(async ({ input, ctx }) => {+ try {+ const model = ctx.taskModel;+ const task = await resolveOrThrow(model, input.taskId);+ await model.unpinDocument(task.id, input.documentId);+ return { message: 'Document unpinned', success: true };+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ console.error('[task:unpinDocument]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to unpin document',+ });+ }+ }),+});diff --git a/apps/server/src/routers/lambda/task/review.ts b/apps/server/src/routers/lambda/task/review.tsnew file mode 100644index 00000000000..4bb0962cd8c--- /dev/null+++ b/apps/server/src/routers/lambda/task/review.ts@@ -0,0 +1,254 @@+import type { TaskVerifyConfig } from '@lobechat/types';+import { TRPCError } from '@trpc/server';+import { z } from 'zod';++import { router } from '@/libs/trpc/lambda';+import { AcceptanceService } from '@/server/services/verify/acceptanceService';+import { resolveTaskAcceptance } from '@/server/services/verify/taskAcceptance';++import {+ idInput,+ resolveOrThrow,+ taskProcedure,+ taskProcedureWrite,+ taskVerifyConfigPatchSchema,+} from './procedures';++export const reviewRouter = router({+ getCheckpoint: taskProcedure.input(idInput).query(async ({ input, ctx }) => {+ try {+ const model = ctx.taskModel;+ const task = await resolveOrThrow(model, input.id);+ const checkpoint = model.getCheckpointConfig(task);+ return { data: checkpoint, success: true };+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ console.error('[task:getCheckpoint]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to get checkpoint',+ });+ }+ }),+ updateCheckpoint: taskProcedureWrite+ .input(+ idInput.merge(+ z.object({+ checkpoint: z.object({+ onAgentRequest: z.boolean().optional(),+ tasks: z+ .object({+ afterIds: z.array(z.string()).optional(),+ beforeIds: z.array(z.string()).optional(),+ })+ .optional(),+ topic: z+ .object({+ after: z.boolean().optional(),+ before: z.boolean().optional(),+ })+ .optional(),+ }),+ }),+ ),+ )+ .mutation(async ({ input, ctx }) => {+ const { id, checkpoint } = input;+ try {+ const model = ctx.taskModel;+ const resolved = await resolveOrThrow(model, id);+ const task = await model.updateCheckpointConfig(resolved.id, checkpoint);+ if (!task) throw new TRPCError({ code: 'NOT_FOUND', message: 'Task not found' });+ return {+ data: model.getCheckpointConfig(task),+ message: 'Checkpoint updated',+ success: true,+ };+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ console.error('[task:updateCheckpoint]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to update checkpoint',+ });+ }+ }),+ getReview: taskProcedure.input(idInput).query(async ({ input, ctx }) => {+ try {+ const model = ctx.taskModel;+ const task = await resolveOrThrow(model, input.id);+ return { data: model.getReviewConfig(task) || null, success: true };+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ console.error('[task:getReview]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to get review config',+ });+ }+ }),+ updateReview: taskProcedureWrite+ .input(+ idInput.merge(+ z.object({+ review: z.object({+ autoRetry: z.boolean().default(true),+ enabled: z.boolean(),+ judge: z+ .object({+ model: z.string().optional(),+ provider: z.string().optional(),+ })+ .default({}),+ maxIterations: z.number().min(1).max(10).default(3),+ rubrics: z.array(+ z.object({+ config: z.record(z.string(), z.unknown()),+ extractor: z.record(z.string(), z.unknown()).optional(),+ id: z.string(),+ name: z.string(),+ threshold: z.number().min(0).max(1).optional(),+ type: z.string(),+ weight: z.number().default(1),+ }),+ ),+ }),+ }),+ ),+ )+ .mutation(async ({ input, ctx }) => {+ const { id, review } = input;+ try {+ const model = ctx.taskModel;+ const resolved = await resolveOrThrow(model, id);+ const task = await model.updateReviewConfig(resolved.id, review);+ if (!task) throw new TRPCError({ code: 'NOT_FOUND', message: 'Task not found' });+ return {+ data: model.getReviewConfig(task),+ message: 'Review config updated',+ success: true,+ };+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ console.error('[task:updateReview]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to update review config',+ });+ }+ }),+ getVerifyConfig: taskProcedure.input(idInput).query(async ({ input, ctx }) => {+ try {+ const model = ctx.taskModel;+ const task = await resolveOrThrow(model, input.id);+ const resolved = await resolveTaskAcceptance(+ ctx.serverDB,+ ctx.userId,+ task.id,+ ctx.workspaceId ?? undefined,+ );+ return {+ data: resolved ? { ...resolved.config, requirement: resolved.requirement } : null,+ success: true,+ };+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ console.error('[task:getVerifyConfig]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to get verify config',+ });+ }+ }),+ updateVerifyConfig: taskProcedureWrite+ .input(+ idInput.merge(+ z.object({+ // `.nullish()` lets callers clear a saved field: `null` removes it+ // (JSON can't send `undefined`), omission leaves it untouched.+ verify: taskVerifyConfigPatchSchema,+ }),+ ),+ )+ .mutation(async ({ input, ctx }) => {+ const { id, verify } = input;+ try {+ const model = ctx.taskModel;+ const task = await resolveOrThrow(model, id);+ const acceptanceService = new AcceptanceService(+ ctx.serverDB,+ ctx.userId,+ ctx.workspaceId ?? undefined,+ );+ const resolvedAcceptance = await resolveTaskAcceptance(+ ctx.serverDB,+ ctx.userId,+ task.id,+ ctx.workspaceId ?? undefined,+ );+ const acceptance =+ resolvedAcceptance?.acceptance ??+ (await acceptanceService.ensureForSubject('task', task.id));+ const nextConfig = { ...acceptance.config } as Record<string, unknown>;+ for (const [key, value] of Object.entries(verify)) {+ if (key === 'requirement') continue;+ if (value === null) delete nextConfig[key];+ else if (value !== undefined) nextConfig[key] = value;+ }+ const requirement =+ verify.requirement === undefined ? acceptance.requirement : verify.requirement;+ const updated = await acceptanceService.acceptanceModel.updatePolicy(acceptance.id, {+ config: nextConfig,+ requirement,+ });+ if (!updated) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Acceptance policy not found' });+ }+ const data: TaskVerifyConfig = {+ ...(nextConfig as TaskVerifyConfig),+ requirement: requirement ?? undefined,+ };+ return {+ data,+ message: 'Verify config updated',+ success: true,+ };+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ console.error('[task:updateVerifyConfig]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to update verify config',+ });+ }+ }),+ runReview: taskProcedureWrite+ .input(+ idInput.merge(+ z.object({+ content: z.string().optional(),+ topicId: z.string().optional(),+ }),+ ),+ )+ .mutation(async ({ input, ctx }) => {+ try {+ const result = await ctx.taskService.runReview(input);+ return { data: result, success: true };+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ console.error('[task:runReview]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to run review',+ });+ }+ }),+});diff --git a/apps/server/src/routers/lambda/task/update.ts b/apps/server/src/routers/lambda/task/update.tsnew file mode 100644index 00000000000..1a28fd9ff38--- /dev/null+++ b/apps/server/src/routers/lambda/task/update.ts@@ -0,0 +1,377 @@+import { TASK_STATUSES } from '@lobechat/builtin-tool-task';+import { TRPCError } from '@trpc/server';+import { z } from 'zod';++import type { LobeChatDatabase } from '@/database/type';+import { assertAgentUsableBy } from '@/database/utils/agent-access';+import { router } from '@/libs/trpc/lambda';+import { publishResourceEvent } from '@/server/services/resourceEvents';+import { TaskService } from '@/server/services/task';+import { notifyAssignedBestEffort } from '@/server/services/task/assignmentNotification';+import { resolveTaskPatchInvariants } from '@/server/services/task/patchValidation';+import {+ schedulePatternSchema,+ scheduleTimezoneSchema,+} from '@/server/services/task/scheduleValidation';+import { hasWorkspaceScopedPermission } from '@/server/services/workspacePermission';++import { idInput, resolveOrThrow, taskProcedureWrite } from './procedures';++const updateSchema = z.object({+ assigneeAgentId: z.string().nullish(),+ assigneeUserId: z.string().nullish(),+ automationMode: z.enum(['heartbeat', 'schedule']).nullish(),+ config: z.record(z.string(), z.unknown()).optional(),+ // Deep-merged into `config` under the update's row lock rather than+ // replacing it β for a client editing one config key alongside columns.+ configPatch: z.record(z.string(), z.unknown()).optional(),+ context: z.record(z.string(), z.unknown()).optional(),+ description: z.string().optional(),+ editorData: z.unknown().optional(),+ // 0 clears the interval (disables heartbeat); any positive value must be+ // β₯600s (10 min) to match the UI minimum and prevent sub-minute ticks if an+ // LLM calls setTaskSchedule with a tiny number.+ heartbeatInterval: z+ .number()+ .int()+ .refine((v) => v === 0 || v >= 600, {+ message: 'heartbeatInterval must be 0 (disabled) or at least 600 seconds (10 minutes)',+ })+ .optional(),+ heartbeatTimeout: z.number().min(1).nullish(),+ instruction: z.string().optional(),+ name: z.string().optional(),+ parentTaskId: z.string().nullish(),+ priority: z.number().min(0).max(4).optional(),+ schedulePattern: schedulePatternSchema.nullish(),+ scheduleTimezone: scheduleTimezoneSchema.nullish(),+ status: z.enum(TASK_STATUSES).optional(),+});++/**+ * Who an activity row is attributed to.+ *+ * A server-side caller (the gateway task runtime) carries the agent in+ * `ctx.actingAgentId`, which no HTTP request can set β that is the trusted+ * path and always wins. The client-first runtime (gateway off, self-hosted)+ * has no such channel: its task tools are ordinary TRPC calls from the+ * browser, so it names the agent in the payload β the same contract+ * `addComment.authorAgentId` already uses β and the claim is honoured only+ * for an agent the caller can use. That bounds any misattribution to the+ * caller's own agents rather than letting a request pin a change on anyone.+ */+async function resolveActivityActor(+ ctx: {+ actingAgentId?: string | null;+ serverDB: LobeChatDatabase;+ userId: string;+ workspaceId?: string | null;+ },+ claimedAgentId?: string,+): Promise<{ agentId?: string | null; userId: string }> {+ if (ctx.actingAgentId) return { agentId: ctx.actingAgentId, userId: ctx.userId };+ if (claimedAgentId) {+ await assertAgentUsableBy(ctx.serverDB, claimedAgentId, {+ userId: ctx.userId,+ workspaceId: ctx.workspaceId ?? undefined,+ });+ }+ return { agentId: claimedAgentId ?? null, userId: ctx.userId };+}++export const updateRouter = router({+ update: taskProcedureWrite+ .input(idInput.merge(updateSchema).extend({ actorAgentId: z.string().optional() }))+ .mutation(async ({ input, ctx }) => {+ const { actorAgentId, configPatch, id, parentTaskId, status, ...data } = input;+ try {+ const model = ctx.taskModel;+ const actor = await resolveActivityActor(ctx, actorAgentId);+ // Hierarchy, visibility and assignment invariants β shared with the+ // REST patch boundary so the two cannot drift.+ const { data: normalizedUpdateData, resolved } = await resolveTaskPatchInvariants(+ {+ agentModel: ctx.agentModel,+ editLockService: ctx.editLockService,+ serverDB: ctx.serverDB,+ taskModel: model,+ taskService: ctx.taskService,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId ?? undefined,+ },+ { data, id, parentTaskId },+ );+ // Agent attribution comes from `resolveActivityActor` above. The+ // assignment activity is written inside this update's own transaction+ // (see `TaskModel.updateWithLog`), so a concurrent reassignment cannot+ // interleave between reading the old assignee and recording it.+ const task = status+ ? await ctx.serverDB.transaction(async (tx) => {+ const taskService = new TaskService(tx, ctx.userId, ctx.workspaceId ?? undefined);+ const updated = await taskService.updateTaskWithAssigneeLock(+ resolved.id,+ normalizedUpdateData,+ actor,+ { configPatch },+ );+ if (!updated) return null;++ const result = await taskService.updateStatus({ id: resolved.id, status }, actor);+ return result.task;+ })+ : await ctx.taskService.updateTaskWithAssigneeLock(+ resolved.id,+ normalizedUpdateData,+ actor,+ { configPatch },+ );+ if (!task) throw new TRPCError({ code: 'NOT_FOUND', message: 'Task not found' });+ // Only an actual assignee change notifies β re-saving the same assignee+ // stays silent (self-assignment is filtered inside the helper).+ if (task.assigneeUserId !== resolved.assigneeUserId) {+ notifyAssignedBestEffort(ctx, task);+ }+ return { data: task, message: 'Task updated', success: true };+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ console.error('[task:update]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to update task',+ });+ }+ }),+ updateVisibility: taskProcedureWrite+ .input(idInput.merge(z.object({ visibility: z.enum(['private', 'public']) })))+ .mutation(async ({ input, ctx }) => {+ try {+ const resolved = await resolveOrThrow(ctx.taskModel, input.id);++ // Mirror the edit-lock contract from `update`: reject visibility flips+ // while another workspace member is actively editing this task. Without+ // this check a collaborator could silently retitle a private task to+ // public (or vice versa) while you're mid-edit.+ if (ctx.workspaceId) {+ const blockedBy = await ctx.editLockService.getBlockingHolder('task', resolved.id);+ if (blockedBy) {+ throw new TRPCError({+ cause: { data: { code: 'DocumentLocked' } },+ code: 'CONFLICT',+ message: 'Task is being edited by another user',+ });+ }+ }++ // The creator can always change visibility on their own tasks. In+ // workspace mode, workspace owners may still promote other members'+ // tasks (mirrors the transferTask policy at line ~1166), but demoting+ // to private stays creator-only: the task would land in+ // the creator's private list, so an owner-initiated demotion just+ // appropriates another member's data.+ if (ctx.workspaceId && resolved.createdByUserId !== ctx.userId) {+ if (input.visibility === 'private') {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: 'Only the task creator can make this task private',+ });+ }+ const canOverride = await hasWorkspaceScopedPermission({+ action: 'AGENT_UPDATE',+ db: ctx.serverDB,+ scopes: ['ALL'],+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ if (!canOverride) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: 'Only the task creator or workspace owner can change visibility',+ });+ }+ }++ // Demoting a mixed-creator subtree would fracture it: each descendant+ // stays owned by its creator, so the root creator loses other+ // members' subtasks while those members keep orphaned children whose+ // parent is hidden. Reject early β the subtree must be single-creator+ // to go private.+ if (input.visibility === 'private') {+ const hasOtherCreators = await ctx.taskModel.subtreeHasOtherCreators(+ resolved.id,+ resolved.createdByUserId,+ );+ if (hasOtherCreators) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message:+ 'Cannot make this task private while it has subtasks created by other members. Reassign or remove those subtasks first.',+ });+ }+ }++ // Demoting a member-assigned task to private would strand the+ // assignee: the task disappears from their view while still carrying+ // their name. Reject early β unassign first, then demote.+ if (input.visibility === 'private') {+ ctx.taskService.assertAssigneeUserVisibilityCompat(+ input.visibility,+ resolved.assigneeUserId,+ resolved.createdByUserId,+ );+ }++ // A private assignee agent on a public task breaks the visibility+ // invariant. Reject early β reassign first, then promote.+ if (input.visibility === 'public' && resolved.assigneeAgentId) {+ const agentVisibility = await ctx.agentModel.getAgentVisibility(resolved.assigneeAgentId);+ ctx.taskService.assertAgentVisibilityCompat(input.visibility, agentVisibility);+ }++ // A public subtask under a private parent would be orphaned in the+ // workspace view β a subtask cannot be more public than its parent.+ // The user must promote the parent chain first, or keep it private.+ if (input.visibility === 'public' && resolved.parentTaskId) {+ const parent = await ctx.taskModel.findById(resolved.parentTaskId);+ ctx.taskService.assertParentVisibilityCompat(input.visibility, parent?.visibility);+ }++ const updated = await ctx.taskSubtree.updateVisibility(resolved.id, input.visibility);+ if (!updated) throw new TRPCError({ code: 'NOT_FOUND', message: 'Task not found' });+ return { data: updated, message: 'Task visibility updated', success: true };+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ console.error('[task:updateVisibility]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to update task visibility',+ });+ }+ }),+ updateConfig: taskProcedureWrite+ .input(idInput.merge(z.object({ config: z.record(z.string(), z.unknown()) })))+ .mutation(async ({ input, ctx }) => {+ const { id, config } = input;+ try {+ const model = ctx.taskModel;+ const resolved = await resolveOrThrow(model, id);+ const task = await model.updateTaskConfig(resolved.id, config);+ if (!task) throw new TRPCError({ code: 'NOT_FOUND', message: 'Task not found' });+ return { data: task, message: 'Config updated', success: true };+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ console.error('[task:updateConfig]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to update task config',+ });+ }+ }),+ updateStatus: taskProcedureWrite+ .input(+ z.object({+ actorAgentId: z.string().optional(),+ error: z.string().optional(),+ id: z.string(),+ operationId: z.string().optional(),+ status: z.enum(TASK_STATUSES),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ const { actorAgentId, ...statusInput } = input;+ try {+ // A person (or their agent) changed it: record who. System+ // transitions call the service without an actor and stay silent.+ const actor = await resolveActivityActor(ctx, actorAgentId);+ const result = await ctx.taskService.updateStatus(statusInput, actor);+ const {+ task,+ unlocked,+ paused,+ checkpointTriggered,+ allSubtasksDone,+ parentTaskId,+ completionDeferred,+ } = result;+ return {+ data: task,+ message: `Task ${input.status}`,+ success: true,+ ...(completionDeferred && { completionDeferred: true }),+ ...(unlocked.length > 0 && { unlocked }),+ ...(paused.length > 0 && { paused }),+ ...(checkpointTriggered && { checkpointTriggered: true }),+ ...(allSubtasksDone && { allSubtasksDone: true, parentTaskId }),+ };+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ console.error('[task:updateStatus]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to update status',+ });+ }+ }),+ updateStatusCascade: taskProcedureWrite+ .input(+ z.object({+ id: z.string(),+ status: z.enum(['canceled', 'completed']),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ try {+ const result = await ctx.taskService.updateStatusCascade(+ input,+ await resolveActivityActor(ctx),+ );+ return { data: result, message: `Task family ${input.status}`, success: true };+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ console.error('[task:updateStatusCascade]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to update task family status',+ });+ }+ }),+ acquireTaskLock: taskProcedureWrite.input(idInput).mutation(async ({ ctx, input }) => {+ if (!ctx.workspaceId) return { expiresAt: null, holderId: null, lockedByOther: false };+ const resolved = await resolveOrThrow(ctx.taskModel, input.id);+ const prev = await ctx.editLockService.getActiveHolder('task', resolved.id);+ const result = await ctx.editLockService.acquire('task', resolved.id);+ if ((result.holderId ?? null) !== (prev ?? null)) {+ void publishResourceEvent(+ { id: resolved.id, type: 'task' },+ { actorId: ctx.userId, data: { holderId: result.holderId }, type: 'lock.changed' },+ );+ }+ return result;+ }),+ getTaskLock: taskProcedureWrite.input(idInput).query(async ({ ctx, input }) => {+ if (!ctx.workspaceId) return { expiresAt: null, holderId: null, lockedByOther: false };+ const resolved = await resolveOrThrow(ctx.taskModel, input.id);+ const holder = await ctx.editLockService.getActiveHolder('task', resolved.id);+ return {+ expiresAt: null,+ holderId: holder ?? null,+ lockedByOther: Boolean(holder) && holder !== ctx.userId,+ };+ }),+ releaseTaskLock: taskProcedureWrite.input(idInput).mutation(async ({ ctx, input }) => {+ if (!ctx.workspaceId) return;+ const resolved = await resolveOrThrow(ctx.taskModel, input.id);+ // Only broadcast "unlocked" when we actually released our own lock β if the+ // lease expired and another member took over, the lock is still held.+ const released = await ctx.editLockService.release('task', resolved.id);+ if (!released) return;+ void publishResourceEvent(+ { id: resolved.id, type: 'task' },+ { actorId: ctx.userId, data: { holderId: null }, type: 'lock.changed' },+ );+ }),+});