⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.
TypeScript agenticagileai-agentsbug-reportingbug-trackerganttissue-trackerjirajira-alternativekanbanlinearlinear-alternativeopen-sourceproduct-managementproject-managementroadmapself-hostedsprint-planningteam-collaborationtrello-alternative
fix(api): keep a rejected option list from creating a field, and name the right permission (#312)
Croff7829a2f3ddc4
diff --git a/apps/api/src/modules/agents/schedules/__tests__/integration/agent-schedules.test.ts b/apps/api/src/modules/agents/schedules/__tests__/integration/agent-schedules.test.tsindex 2f0f82b5..a10cad43 100644--- a/apps/api/src/modules/agents/schedules/__tests__/integration/agent-schedules.test.ts+++ b/apps/api/src/modules/agents/schedules/__tests__/integration/agent-schedules.test.ts@@ -89,6 +89,14 @@ describe('agent schedules', () => {expect(list.data?.[0].id).toBe(created.data!.id);});+ it('rejects a name the agent already has a schedule under', async () => {+ const { asOwner } = await setup();+ const agentId = await createAgent(asOwner);+ await createSchedule(asOwner, agentId);+ const res = await createSchedule(asOwner, agentId);+ expect(res.status).toBe(409);+ });+it('rejects an invalid cron expression', async () => {const { asOwner } = await setup();const agentId = await createAgent(asOwner);diff --git a/apps/api/src/modules/agents/schedules/index.ts b/apps/api/src/modules/agents/schedules/index.tsindex e3b64862..d297fff4 100644--- a/apps/api/src/modules/agents/schedules/index.ts+++ b/apps/api/src/modules/agents/schedules/index.ts@@ -3,8 +3,8 @@ import { authContext } from '#shared/auth-context';import { guards } from '#shared/guards';import { requireUser } from '#shared/access';import { noContent } from '#shared/http';-import { HttpError } from '#shared/lib';-import { accessErrors, commonErrors } from '#shared/responses';+import { HttpError, rethrowDuplicate } from '#shared/lib';+import { accessErrors, commonErrors, errors } from '#shared/responses';import { mcpTool } from '#mcp/generate';import { nextCronRun } from './cron';import {@@ -58,16 +58,21 @@ export const agentScheduleRoutes = new Elysia({'/projects/:projectKey/agent-schedules',async ({ project, body, set, user }) => {const cron = body.cron.trim();- const row = await createAgentSchedule({- projectId: project.id,- agentId: body.agentId,- actorUserId: requireUser(user).id,- name: requiredText(body.name, 'Name'),- prompt: requiredText(body.prompt, 'Task'),- cron,- status: body.status ?? 'active',- nextRunAt: nextCronRun(cron),- });+ let row;+ try {+ row = await createAgentSchedule({+ projectId: project.id,+ agentId: body.agentId,+ actorUserId: requireUser(user).id,+ name: requiredText(body.name, 'Name'),+ prompt: requiredText(body.prompt, 'Task'),+ cron,+ status: body.status ?? 'active',+ nextRunAt: nextCronRun(cron),+ });+ } catch (err) {+ rethrowDuplicate(err, 'schedule');+ }if (!row) throw new HttpError(400, 'Select an agent from this project');set.status = 201;return row;@@ -75,7 +80,7 @@ export const agentScheduleRoutes = new Elysia({{body: createScheduleBody,permission: ['ai_agents', 'create'],- response: { 201: AgentScheduleResponse, ...commonErrors },+ response: { 201: AgentScheduleResponse, ...commonErrors, ...errors(409) },detail: {summary: 'Create an agent schedule',description: 'Create a schedule that sends a task to an agent on a cron.',@@ -94,19 +99,24 @@ export const agentScheduleRoutes = new Elysia({let nextRunAt: Date | undefined;if (cron !== undefined) nextRunAt = nextCronRun(cron);else if (resuming) nextRunAt = nextCronRun(current.cron);- const row = await updateAgentSchedule(- project.id,- params.scheduleId,- {- ...(body.agentId !== undefined ? { agentId: body.agentId } : {}),- ...(body.name !== undefined ? { name: requiredText(body.name, 'Name') } : {}),- ...(body.prompt !== undefined ? { prompt: requiredText(body.prompt, 'Task') } : {}),- ...(cron !== undefined ? { cron } : {}),- ...(nextRunAt !== undefined ? { nextRunAt } : {}),- ...(body.status !== undefined ? { status: body.status } : {}),- },- requireUser(user).id,- );+ let row;+ try {+ row = await updateAgentSchedule(+ project.id,+ params.scheduleId,+ {+ ...(body.agentId !== undefined ? { agentId: body.agentId } : {}),+ ...(body.name !== undefined ? { name: requiredText(body.name, 'Name') } : {}),+ ...(body.prompt !== undefined ? { prompt: requiredText(body.prompt, 'Task') } : {}),+ ...(cron !== undefined ? { cron } : {}),+ ...(nextRunAt !== undefined ? { nextRunAt } : {}),+ ...(body.status !== undefined ? { status: body.status } : {}),+ },+ requireUser(user).id,+ );+ } catch (err) {+ rethrowDuplicate(err, 'schedule');+ }if (!row) throw new HttpError(404, 'Schedule not found');return row;},@@ -114,7 +124,7 @@ export const agentScheduleRoutes = new Elysia({params: scheduleParams,body: updateScheduleBody,permission: ['ai_agents', 'edit'],- response: { 200: AgentScheduleResponse, ...commonErrors },+ response: { 200: AgentScheduleResponse, ...commonErrors, ...errors(409) },detail: {summary: 'Update an agent schedule',description: "Update a schedule's agent, task, cron, or status.",diff --git a/apps/api/src/modules/custom-fields/__tests__/integration/custom-fields.test.ts b/apps/api/src/modules/custom-fields/__tests__/integration/custom-fields.test.tsindex ef4f52a8..5d04e4db 100644--- a/apps/api/src/modules/custom-fields/__tests__/integration/custom-fields.test.ts+++ b/apps/api/src/modules/custom-fields/__tests__/integration/custom-fields.test.ts@@ -219,6 +219,17 @@ describe('custom-fields', () => {});expect(res.status).toBe(400);});++ it('creates no field when its options are rejected', async () => {+ const { asOwner } = await setupProject();+ const res = await fields(asOwner).post({+ name: 'Priority',+ fieldType: 'select',+ options: ['Yes', 'Yes'],+ });+ expect(res.status).toBe(409);+ expect(await listFields(asOwner)).toEqual([]);+ });});describe('list', () => {diff --git a/apps/api/src/modules/custom-fields/index.ts b/apps/api/src/modules/custom-fields/index.tsindex aea34c61..a8ec1eca 100644--- a/apps/api/src/modules/custom-fields/index.ts+++ b/apps/api/src/modules/custom-fields/index.ts@@ -1,8 +1,8 @@import { Elysia, t } from 'elysia';import { noContent } from '#shared/http';import { guards } from '#shared/guards';-import { HttpError } from '#shared/lib';-import { commonErrors } from '#shared/responses';+import { HttpError, rethrowDuplicate } from '#shared/lib';+import { commonErrors, errors } from '#shared/responses';import { mcpTool } from '#mcp/generate';import {CustomFieldListResponse,@@ -46,13 +46,17 @@ export const customFieldRoutes = new Elysia({.post('/projects/:projectKey/custom-fields',async ({ project, body, set }) => {- set.status = 201;- return createCustomField({ projectId: project.id, ...body });+ try {+ set.status = 201;+ return await createCustomField({ projectId: project.id, ...body });+ } catch (err) {+ rethrowDuplicate(err, 'field option');+ }},{body: createCustomFieldBody,permission: ['custom_fields', 'create'],- response: { 201: CustomFieldResponse, ...commonErrors },+ response: { 201: CustomFieldResponse, ...commonErrors, ...errors(409) },detail: {summary: 'Create a custom field',description: 'Create a custom field for a project.',@@ -64,7 +68,12 @@ export const customFieldRoutes = new Elysia({.patch('/projects/:projectKey/custom-fields/:fieldId',async ({ project, params, body }) => {- const field = await updateCustomField(project.id, params.fieldId, body);+ let field;+ try {+ field = await updateCustomField(project.id, params.fieldId, body);+ } catch (err) {+ rethrowDuplicate(err, 'field option');+ }if (!field) throw new HttpError(404, 'Custom field not found');return field;},@@ -72,14 +81,14 @@ export const customFieldRoutes = new Elysia({body: updateCustomFieldBody,params: fieldParams,permission: ['custom_fields', 'edit'],- response: { 200: CustomFieldResponse, ...commonErrors },+ response: { 200: CustomFieldResponse, ...commonErrors, ...errors(409) },detail: {summary: 'Update a custom field',description:'Update a custom field. Changing its type clears the values issues hold in it, ' +'narrowing a member scope clears the ones it no longer allows, and an option left ' +'out of `options` is deleted along with the selections of it.',- ...mcpTool('update_custom_field'),+ ...mcpTool('update_custom_field', { destructiveHint: true }),},},)diff --git a/apps/api/src/modules/custom-fields/service.ts b/apps/api/src/modules/custom-fields/service.tsindex ad44a661..8657047b 100644--- a/apps/api/src/modules/custom-fields/service.ts+++ b/apps/api/src/modules/custom-fields/service.ts@@ -168,25 +168,29 @@ export async function createCustomField(input: {sql`${customField.issueTypeId} IS NOT DISTINCT FROM ${issueTypeId}`,),);- const [row] = await db- .insert(customField)- .values({- projectId: input.projectId,- issueTypeId,- name: input.name,- fieldType: input.fieldType,- memberScope: input.fieldType === 'member' ? (input.memberScope ?? 'all') : null,- showInBody: input.showInBody ?? false,- position: Number(pos),- })- .returning({ id: customField.id });const options = input.options ?? [];- if (options.length > 0) {- await db- .insert(customFieldOption)- .values(options.map((value, index) => ({ fieldId: row.id, value, position: index })));- }- return (await getCustomFieldById(input.projectId, row.id))!;+ // One transaction, so a rejected option list leaves no field behind.+ const id = await db.transaction(async (tx) => {+ const [row] = await tx+ .insert(customField)+ .values({+ projectId: input.projectId,+ issueTypeId,+ name: input.name,+ fieldType: input.fieldType,+ memberScope: input.fieldType === 'member' ? (input.memberScope ?? 'all') : null,+ showInBody: input.showInBody ?? false,+ position: Number(pos),+ })+ .returning({ id: customField.id });+ if (options.length > 0) {+ await tx+ .insert(customFieldOption)+ .values(options.map((value, index) => ({ fieldId: row.id, value, position: index })));+ }+ return row.id;+ });+ return (await getCustomFieldById(input.projectId, id))!;}type Transaction = Parameters<Parameters<typeof db.transaction>[0]>[0];diff --git a/apps/api/src/modules/issue-types/index.ts b/apps/api/src/modules/issue-types/index.tsindex 7f500201..d9f8ca7e 100644--- a/apps/api/src/modules/issue-types/index.ts+++ b/apps/api/src/modules/issue-types/index.ts@@ -2,8 +2,8 @@ import { Elysia, t } from 'elysia';import { mcpTool } from '#mcp/generate';import { noContent } from '#shared/http';import { guards } from '#shared/guards';-import { HttpError } from '#shared/lib';-import { commonErrors } from '#shared/responses';+import { HttpError, rethrowDuplicate } from '#shared/lib';+import { commonErrors, errors } from '#shared/responses';import {IssueTypeResponse,createIssueTypeBody,@@ -20,13 +20,17 @@ export const issueTypeRoutes = new Elysia({.post('/projects/:projectKey/issue-types',async ({ project, body, set }) => {- set.status = 201;- return createIssueType({ projectId: project.id, ...body });+ try {+ set.status = 201;+ return await createIssueType({ projectId: project.id, ...body });+ } catch (err) {+ rethrowDuplicate(err, 'issue type');+ }},{body: createIssueTypeBody,permission: ['issue_types', 'create'],- response: { 201: IssueTypeResponse, ...commonErrors },+ response: { 201: IssueTypeResponse, ...commonErrors, ...errors(409) },detail: {summary: 'Create an issue type',description:@@ -39,7 +43,12 @@ export const issueTypeRoutes = new Elysia({.patch('/projects/:projectKey/issue-types/:typeId',async ({ params, project, body }) => {- const type = await updateIssueType(params.typeId, project.id, body);+ let type;+ try {+ type = await updateIssueType(params.typeId, project.id, body);+ } catch (err) {+ rethrowDuplicate(err, 'issue type');+ }if (!type) throw new HttpError(404, 'Issue type not found');return type;},@@ -47,7 +56,7 @@ export const issueTypeRoutes = new Elysia({body: updateIssueTypeBody,params: issueTypeParams,permission: ['issue_types', 'edit'],- response: { 200: IssueTypeResponse, ...commonErrors },+ response: { 200: IssueTypeResponse, ...commonErrors, ...errors(409) },detail: {summary: 'Update an issue type',description: "Update an issue type's name, color, or default flag.",diff --git a/apps/api/src/modules/issues/index.ts b/apps/api/src/modules/issues/index.tsindex 12f8c260..c0211ae8 100644--- a/apps/api/src/modules/issues/index.ts+++ b/apps/api/src/modules/issues/index.ts@@ -1036,7 +1036,9 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issuesdetail: {summary: 'Change a time entry',description:- "Change the time, the day or the note of an entry. Another member's entry needs work_items delete.",+ 'Change the time, the day or the note of an entry. Your own entry needs work_items ' ++ "edit; another member's entry is a record of what they did, so only a project owner " ++ 'can change it.',...mcpTool('update_worklog'),},},@@ -1056,7 +1058,9 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issuesdetail: {summary: 'Delete a time entry',description:- "Remove one entry, lowering the issue's logged time by it. Another member's entry needs work_items delete.",+ "Remove one entry, lowering the issue's logged time by it. Your own entry needs " ++ "work_items edit; another member's entry is a record of what they did, so only a " ++ 'project owner can remove it.',...mcpTool('delete_worklog'),},},diff --git a/apps/api/src/modules/note-boards/index.ts b/apps/api/src/modules/note-boards/index.tsindex 5a0db875..3142e6b0 100644--- a/apps/api/src/modules/note-boards/index.ts+++ b/apps/api/src/modules/note-boards/index.ts@@ -195,7 +195,7 @@ export const noteBoardRoutes = new Elysia({summary: 'Update a note board',description:'Rename a board, change who sees it, or replace its `canvas`. `visibility` is "public" (every project member), "private" (the creator alone), or "restricted" (the creator plus the project members in `memberIds`, which replaces the granted list as a whole). Only the board creator can change either. Adding, editing, connecting, or deleting a card is a change to `canvas` (see `get_note_board`). It is replaced as a whole: read the board first, then send every node and edge that must stay — anything left out is deleted.',- ...mcpTool('update_note_board'),+ ...mcpTool('update_note_board', { destructiveHint: true }),},},)diff --git a/apps/api/src/shared/lib.ts b/apps/api/src/shared/lib.tsindex fa1b50b9..4bceea35 100644--- a/apps/api/src/shared/lib.ts+++ b/apps/api/src/shared/lib.ts@@ -60,7 +60,8 @@ export function pgErrorCode(err: unknown): string | undefined {// other error is rethrown unchanged.export function rethrowDuplicate(err: unknown, what: string): never {if (pgErrorCode(err) === '23505') {- throw new HttpError(409, `A ${what} with this name already exists.`);+ const article = /^[aeiou]/i.test(what) ? 'An' : 'A';+ throw new HttpError(409, `${article} ${what} with this name already exists.`);}throw err;}