π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(task): treat empty assignee ids as unset and surface the PG cause on createTask (#19990)
Arvin Xudfaef141be91
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.test.tsindex 270e9813bed..5812e24fdc8 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.test.ts@@ -301,6 +301,79 @@ describe('createTaskRuntime', () => {});});+ it('treats empty-string assignees as omitted so they never reach the FK columns', async () => {+ const deps = makeDeps();++ const runtime = createTaskRuntime({+ agentModel: deps.agentModel as any,+ agentId: 'agt-xyz',+ taskCaller: deps.taskCaller,+ taskModel: deps.taskModel as any,+ taskService: deps.taskService as any,+ });++ const result = await runtime.createTask({+ assigneeAgentId: '',+ assigneeUserId: ' ',+ instruction: 'Do something',+ name: 'Test',+ parentIdentifier: '',+ });++ expect(result.success).toBe(true);+ expect(deps.agentModel.existsById).not.toHaveBeenCalled();+ expect(deps.taskModel.resolve).not.toHaveBeenCalled();+ expect(deps.taskService.createTask).toHaveBeenCalledWith(+ expect.objectContaining({ assigneeAgentId: 'agt-xyz', assigneeUserId: undefined }),+ );+ });++ it('surfaces the PG error code and constraint instead of only the drizzle query text', async () => {+ const deps = makeDeps();+ const pgCause = Object.assign(+ new Error(+ 'insert or update on table "tasks" violates foreign key constraint "tasks_assignee_user_id_users_id_fk"',+ ),+ {+ code: '23503',+ constraint: 'tasks_assignee_user_id_users_id_fk',+ detail: 'Key (assignee_user_id)=(usr_missing) is not present in table "users".',+ severity: 'ERROR',+ table: 'tasks',+ },+ );+ deps.taskService.createTask.mockRejectedValue(+ new Error('Failed query: insert into "tasks" (...) values (...) params: ...', {+ cause: pgCause,+ }),+ );++ const runtime = createTaskRuntime({+ agentModel: deps.agentModel as any,+ agentId: 'agt-xyz',+ taskCaller: deps.taskCaller,+ taskModel: deps.taskModel as any,+ taskService: deps.taskService as any,+ });++ const result = await runtime.createTask({+ assigneeUserId: 'usr_missing',+ instruction: 'Do something',+ name: 'Test',+ });+ const batch = await runtime.createTasks({+ tasks: [{ assigneeUserId: 'usr_missing', instruction: 'Do something', name: 'Test' }],+ });++ expect(result.success).toBe(false);+ expect(result.content).toContain('Failed to create task');+ expect(result.content).toContain('PG 23503');+ expect(result.content).toContain('constraint=tasks_assignee_user_id_users_id_fk');+ expect(result.content).not.toContain('Failed query');+ expect(batch.success).toBe(false);+ expect(batch.content).toContain('constraint=tasks_assignee_user_id_users_id_fk');+ });+it('leaves createdByAgentId undefined when no agentId in context', async () => {const deps = makeDeps();diff --git a/apps/server/src/services/toolExecution/serverRuntimes/task.ts b/apps/server/src/services/toolExecution/serverRuntimes/task.tsindex e3638973d11..fe80c321480 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/task.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/task.ts@@ -31,6 +31,7 @@ import { WorkspaceModel } from '@/database/models/workspace';import { WorkspaceMemberModel } from '@/database/models/workspaceMember';import { tasks } from '@/database/schemas';import { appEnv } from '@/envs/app';+import { formatPgError, unwrapPgError } from '@/server/modules/AgentRuntime/pgError';import { taskRouter } from '@/server/routers/lambda/task';import { TaskService } from '@/server/services/task';import { after } from '@/server/utils/scheduleAfterResponse';@@ -189,8 +190,16 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {};const createTaskImpl = async (- args: CreateTaskArgs,+ rawArgs: CreateTaskArgs,): Promise<{ content: string; identifier?: string; success: boolean; taskId?: string }> => {+ // Models fill optional ids with "" β treat blanks as omitted so they fall+ // back to the defaults instead of hitting the foreign keys as ''.+ const args: CreateTaskArgs = {+ ...rawArgs,+ assigneeAgentId: rawArgs.assigneeAgentId?.trim() || undefined,+ assigneeUserId: rawArgs.assigneeUserId?.trim() || undefined,+ parentIdentifier: rawArgs.parentIdentifier?.trim() || undefined,+ };let parentLabel: string | undefined;// Pre-resolve parent identifier so we can surface a tool-friendly error@@ -226,17 +235,29 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {// Executing agent and human owner are independent, coexisting sides (the// member owns the outcome, the agent executes) β a member owner does not// suppress the usual current-agent default.- const task = await taskService().createTask({- assigneeAgentId: args.assigneeAgentId ?? (scope === 'task' ? undefined : agentId),- assigneeUserId: args.assigneeUserId,- context: origin ? { origin } : undefined,- createdByAgentId: agentId,- instruction: args.instruction,- name: args.name,- parentTaskId,- priority: args.priority,- sortOrder: args.sortOrder,- });+ let task: Awaited<ReturnType<TaskService['createTask']>>;+ try {+ task = await taskService().createTask({+ assigneeAgentId: args.assigneeAgentId ?? (scope === 'task' ? undefined : agentId),+ assigneeUserId: args.assigneeUserId,+ context: origin ? { origin } : undefined,+ createdByAgentId: agentId,+ instruction: args.instruction,+ name: args.name,+ parentTaskId,+ priority: args.priority,+ sortOrder: args.sortOrder,+ });+ } catch (error) {+ // Drizzle's message is only `Failed query: insert β¦ params: β¦`, where+ // null and '' both print as empty, so agents misread it (e.g. as a null+ // workspace or a duplicate identifier). Surface the PG cause (SQLSTATE ++ // constraint + detail) instead. Non-DB errors (TRPCError etc.) already+ // carry an actionable message and keep propagating as before.+ const pgError = unwrapPgError(error);+ if (!pgError) throw error;+ return { content: `Failed to create task: ${formatPgError(pgError)}`, success: false };+ }notifyMemberAssigned(task);diff --git a/packages/builtin-tool-task/src/client/executor/assignee.test.ts b/packages/builtin-tool-task/src/client/executor/assignee.test.tsindex db67b3fe5b5..9e2f996530c 100644--- a/packages/builtin-tool-task/src/client/executor/assignee.test.ts+++ b/packages/builtin-tool-task/src/client/executor/assignee.test.ts@@ -98,6 +98,17 @@ describe('TaskExecutor β human assignee (assigneeUserId)', () => {);});+ it('treats empty-string assignees as omitted instead of sending them to the server', async () => {+ await taskExecutor.createTask(+ { assigneeAgentId: '', assigneeUserId: '', instruction: 'x', name: 'x' },+ { agentId: 'agt-current' } as any,+ );++ expect(mocks.createTask).toHaveBeenCalledWith(+ expect.objectContaining({ assigneeAgentId: 'agt-current', assigneeUserId: undefined }),+ );+ });+it('accepts an explicit agent and a member in the same call (coexisting assignees)', async () => {const result = await taskExecutor.createTask({assigneeAgentId: 'agt-1',diff --git a/packages/builtin-tool-task/src/client/executor/index.ts b/packages/builtin-tool-task/src/client/executor/index.tsindex e5b4d6de867..425957b1efb 100644--- a/packages/builtin-tool-task/src/client/executor/index.ts+++ b/packages/builtin-tool-task/src/client/executor/index.ts@@ -211,15 +211,18 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {): Promise<BuiltinToolResult> => {try {log('[TaskExecutor] createTask - params:', params);+ // Models fill optional ids with "" β treat blanks as omitted so they fall+ // back to the defaults instead of hitting the foreign keys as ''.const parentIdentifier = params.parentIdentifier?.trim() || undefined;+ const assigneeAgentId = params.assigneeAgentId?.trim() || undefined;+ const assigneeUserId = params.assigneeUserId?.trim() || undefined;// Executing agent and human owner are independent, coexisting sides (the// member owns the outcome, the agent executes) β a member owner does not// suppress the usual current-agent default.const task = await getTaskStoreState().createTask({- assigneeAgentId:- params.assigneeAgentId ?? (ctx?.scope === 'task' ? undefined : ctx?.agentId),- assigneeUserId: params.assigneeUserId,+ assigneeAgentId: assigneeAgentId ?? (ctx?.scope === 'task' ? undefined : ctx?.agentId),+ assigneeUserId,createdByAgentId: ctx?.agentId,instruction: params.instruction,name: params.name,diff --git a/packages/database/src/models/__tests__/task.test.ts b/packages/database/src/models/__tests__/task.test.tsindex 3d1a9b2ce15..44467b5ea97 100644--- a/packages/database/src/models/__tests__/task.test.ts+++ b/packages/database/src/models/__tests__/task.test.ts@@ -53,6 +53,31 @@ describe('TaskModel', () => {});describe('create', () => {+ // LLMs (notably gpt-family models) fill optional tool fields with "". An+ // empty id must mean "unassigned", never reach the FK columns as ''.+ it('should store empty-string assigneeUserId as null instead of violating the FK', async () => {+ const agentId = await createAgent('task-empty-assignee-agent');+ const model = new TaskModel(serverDB, userId);++ const task = await model.create({+ assigneeAgentId: agentId,+ assigneeUserId: '',+ instruction: 'y',+ name: 'x',+ });++ expect(task.assigneeUserId).toBeNull();+ expect(task.assigneeAgentId).toBe(agentId);+ });++ it('should store blank assigneeAgentId as null instead of violating the FK', async () => {+ const model = new TaskModel(serverDB, userId);++ const task = await model.create({ assigneeAgentId: ' ', instruction: 'y', name: 'x' });++ expect(task.assigneeAgentId).toBeNull();+ });+it('should create a task with auto-generated identifier', async () => {const model = new TaskModel(serverDB, userId);const result = await model.create({@@ -222,6 +247,21 @@ describe('TaskModel', () => {expect(updated!.name).toBe('Updated name');});+ it('should clear assignees when updated with empty strings instead of violating the FK', async () => {+ const agentId = await createAgent('task-update-empty-assignee-agent');+ const model = new TaskModel(serverDB, userId);+ const task = await model.create({+ assigneeAgentId: agentId,+ assigneeUserId: userId,+ instruction: 'Original',+ });++ const updated = await model.update(task.id, { assigneeAgentId: '', assigneeUserId: '' });++ expect(updated!.assigneeAgentId).toBeNull();+ expect(updated!.assigneeUserId).toBeNull();+ });+it('should not update task owned by another user', async () => {const model1 = new TaskModel(serverDB, userId);const model2 = new TaskModel(serverDB, userId2);diff --git a/packages/database/src/models/task.ts b/packages/database/src/models/task.tsindex 52da551ba2f..6ab0215571e 100644--- a/packages/database/src/models/task.ts+++ b/packages/database/src/models/task.ts@@ -112,6 +112,25 @@ const snapshotAutomation = (row: {};};+// Foreign-key id columns a caller may clear or leave unset. LLM tool calls often+// fill optional ids with "" β that must mean "unset", never reach the FK as ''.+const TASK_NULLABLE_REF_KEYS = ['assigneeAgentId', 'assigneeUserId', 'parentTaskId'] as const;++const normalizeTaskRefs = <+ T extends Partial<Record<(typeof TASK_NULLABLE_REF_KEYS)[number], unknown>>,+>(+ data: T,+): T => {+ const normalized = { ...data };+ for (const key of TASK_NULLABLE_REF_KEYS) {+ const value = normalized[key];+ if (typeof value === 'string' && !value.trim()) {+ (normalized as Record<string, unknown>)[key] = null;+ }+ }+ return normalized;+};+export const isTaskIdentifierUniqueViolation = (error: unknown): boolean => {const message = error instanceof Error ? error.message : String(error);const code =@@ -337,7 +356,7 @@ export class TaskModel {},options: { maxRetries?: number } = {},): Promise<TaskItem> {- const { identifierPrefix = 'T', ...rest } = data;+ const { identifierPrefix = 'T', ...rest } = normalizeTaskRefs(data);// Retry loop to handle concurrent creates (parallel tool calls)const maxRetries = options.maxRetries ?? 5;@@ -458,7 +477,7 @@ export class TaskModel {const updated = await this.db.update(tasks)- .set({ ...data, updatedAt: new Date() })+ .set({ ...normalizeTaskRefs(data), updatedAt: new Date() }).where(and(eq(tasks.id, id), this.ownership())).returning();return updated[0] || null;