Skip to content

⭐️⭐️⭐️ 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.

fix: let a project with a legacy key take a valid one (#449)

Croffc9e82d9376cb
diff --git a/apps/api/src/modules/projects/__tests__/integration/project-key.test.ts b/apps/api/src/modules/projects/__tests__/integration/project-key.test.ts
new file mode 100644
index 00000000..7046c07d
--- /dev/null
+++ b/apps/api/src/modules/projects/__tests__/integration/project-key.test.ts
@@ -0,0 +1,63 @@
+import { describe, it, expect, beforeEach } from 'bun:test';
+import { eq } from 'drizzle-orm';
+import { db, project } from '@repo/db';
+import { authedApi } from '#tests/helpers/app';
+import { signUpTestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
+
+// A key stored before the key pattern existed may start with a digit. Such a project
+// can take a valid key; a valid key does not change.
+
+async function ownerWithProject(key: string) {
+ const user = await signUpTestUser();
+ const api = authedApi(user.cookie);
+ const created = (await api.projects.post({ key: 'TMP', name: 'Trader' })).data!;
+ await db.update(project).set({ key }).where(eq(project.id, created.id));
+ return { api, created };
+}
+
+describe('project key rename', () => {
+ beforeEach(async () => {
+ await resetDb();
+ });
+
+ it('renames a key that starts with a digit, once', async () => {
+ const { api, created } = await ownerWithProject('7XTR');
+
+ const renamed = await api
+ .projects({ projectKey: `${created.teamId}.7XTR` })
+ .patch({ key: 'XTR' });
+ expect(renamed.status).toBe(200);
+ expect(renamed.data).toMatchObject({ key: 'XTR', ref: `${created.teamId}.XTR` });
+
+ const again = await api.projects({ projectKey: `${created.teamId}.XTR` }).patch({ key: 'ABC' });
+ expect(again.status).toBe(400);
+ });
+
+ it('renames through the team route', async () => {
+ const { api, created } = await ownerWithProject('7XTR');
+
+ const renamed = await api
+ .teams({ teamId: created.teamId })
+ .projects({ projectId: created.id })
+ .patch({ key: 'XTR' });
+ expect(renamed.data).toMatchObject({ key: 'XTR' });
+ });
+
+ it('accepts the unchanged valid key', async () => {
+ const user = await signUpTestUser();
+ const api = authedApi(user.cookie);
+ const created = (await api.projects.post({ key: 'MKT', name: 'Marketing' })).data!;
+
+ const res = await api.projects({ projectKey: created.ref }).patch({ key: 'MKT', name: 'Ads' });
+ expect(res.data).toMatchObject({ key: 'MKT', name: 'Ads' });
+ });
+
+ it('refuses a key another project of the team has', async () => {
+ const { api, created } = await ownerWithProject('7XTR');
+ await api.projects.post({ key: 'XTR', name: 'Other' });
+
+ const res = await api.projects({ projectKey: `${created.teamId}.7XTR` }).patch({ key: 'XTR' });
+ expect(res.status).toBe(409);
+ });
+});
diff --git a/apps/api/src/modules/projects/index.ts b/apps/api/src/modules/projects/index.ts
index d11643ba..8e22478b 100644
--- a/apps/api/src/modules/projects/index.ts
+++ b/apps/api/src/modules/projects/index.ts
@@ -184,8 +184,8 @@ export const projectRoutes = new Elysia({ name: 'projects', detail: { tags: ['Pr
},
)
- // Updates a project's editable metadata (name, description). The key is the
- // immutable issue-identifier prefix and cannot change. Owner-only.
+ // Updates a project's name, description, and a key that does not match the key
+ // pattern (see updateProject). Owner-only.
.patch(
'/projects/:projectKey',
async ({ project, body }) => {
@@ -196,13 +196,15 @@ export const projectRoutes = new Elysia({ name: 'projects', detail: { tags: ['Pr
{
body: updateProjectBody,
projectOwner: true,
- response: { 200: ProjectResponse, ...commonErrors },
+ response: { 200: ProjectResponse, ...commonErrors, ...errors(409) },
detail: {
summary: 'Update a project',
description:
"Update a project's name and/or description. The description is given to the " +
`agents of the project in their system prompt; up to ${PROJECT_DESCRIPTION_LIMIT} ` +
- 'characters. The key is immutable.',
+ 'characters. The key changes only when it does not match the key pattern: a key ' +
+ 'created before the pattern existed, for example one that starts with a digit. ' +
+ 'A key that another project of the team has is refused with 409.',
...mcpTool('update_project'),
},
},
diff --git a/apps/api/src/modules/projects/key.ts b/apps/api/src/modules/projects/key.ts
new file mode 100644
index 00000000..e5690f2d
--- /dev/null
+++ b/apps/api/src/modules/projects/key.ts
@@ -0,0 +1 @@
+export const PROJECT_KEY_PATTERN = '^[A-Z][A-Z0-9]{0,9}$';
diff --git a/apps/api/src/modules/projects/model.ts b/apps/api/src/modules/projects/model.ts
index b87f6240..22735177 100644
--- a/apps/api/src/modules/projects/model.ts
+++ b/apps/api/src/modules/projects/model.ts
@@ -1,4 +1,5 @@
import { t } from 'elysia';
+import { PROJECT_KEY_PATTERN } from './key';
import { PROJECT_FEATURES } from '#shared/features';
import { ColumnResponse } from '#modules/columns/model';
import { CustomFieldResponse } from '#modules/custom-fields/model';
@@ -13,11 +14,13 @@ import { COPY_INCLUDE_KEYS } from './copy';
// input tokens each time, so it is capped on the way in and cut again in the prompt.
export const PROJECT_DESCRIPTION_LIMIT = 2000;
+const projectKey = t.String({
+ pattern: PROJECT_KEY_PATTERN,
+ description: 'Upper-case letters and digits, starting with a letter, up to 10 characters.',
+});
+
const projectBody = t.Object({
- key: t.String({
- pattern: '^[A-Z][A-Z0-9]{0,9}$',
- description: 'Upper-case letters and digits, starting with a letter, up to 10 characters.',
- }),
+ key: projectKey,
name: t.String({ minLength: 1 }),
description: t.Optional(t.String({ maxLength: PROJECT_DESCRIPTION_LIMIT })),
});
@@ -51,6 +54,7 @@ export const copyProjectBody = t.Composite([
]);
export const updateProjectBody = t.Object({
+ key: t.Optional(projectKey),
name: t.Optional(t.String({ minLength: 1 })),
description: t.Optional(t.String({ maxLength: PROJECT_DESCRIPTION_LIMIT })),
});
diff --git a/apps/api/src/modules/projects/service.ts b/apps/api/src/modules/projects/service.ts
index ec6e03e8..9d4c05f5 100644
--- a/apps/api/src/modules/projects/service.ts
+++ b/apps/api/src/modules/projects/service.ts
@@ -31,6 +31,7 @@ import {
type SQL,
} from 'drizzle-orm';
import { HttpError, iso } from '#shared/lib';
+import { PROJECT_KEY_PATTERN } from './key';
import {
defaultMemberPermissions,
fullPermissions,
@@ -519,14 +520,23 @@ export async function createProject(
});
}
-// Updates a project's editable metadata (name, description). The key is the
-// issue-identifier prefix (e.g. "MKT-42") and is immutable, so it is not editable
-// here. Only the provided fields change.
+// A key stored before PROJECT_KEY_PATTERN existed (e.g. "7XTR") cannot form an issue
+// identifier, so it may be replaced once. A valid key does not change.
export async function updateProject(
projectId: number,
- patch: { name?: string; description?: string },
+ patch: { key?: string; name?: string; description?: string },
): Promise<ProjectRow | null> {
const values: Partial<typeof project.$inferInsert> = {};
+ if (patch.key !== undefined) {
+ const current = await getProjectById(projectId);
+ if (!current) return null;
+ if (patch.key !== current.key) {
+ if (new RegExp(PROJECT_KEY_PATTERN).test(current.key)) {
+ throw new HttpError(400, 'The project key cannot change');
+ }
+ values.key = patch.key;
+ }
+ }
if (patch.name !== undefined) values.name = patch.name;
if (patch.description !== undefined) values.description = patch.description;
if (Object.keys(values).length === 0) return getProjectById(projectId);
diff --git a/apps/api/src/modules/teams/index.ts b/apps/api/src/modules/teams/index.ts
index d4f577d5..28ac1de2 100644
--- a/apps/api/src/modules/teams/index.ts
+++ b/apps/api/src/modules/teams/index.ts
@@ -359,11 +359,13 @@ export const teamRoutes = new Elysia({ name: 'teams', detail: { tags: ['Teams']
teamManager: true,
params: teamProjectParams,
body: updateProjectBody,
- response: { 200: ProjectResponse, ...errors(400, 401, 403, 404) },
+ response: { 200: ProjectResponse, ...errors(400, 401, 403, 404, 409) },
detail: {
summary: 'Update a project of the team',
description:
- 'Update the name and/or description of a project the team owns. The key is immutable.',
+ 'Update the name and/or description of a project the team owns. The key changes ' +
+ 'only when it does not match the key pattern, for example one that starts with a ' +
+ 'digit. A key that another project of the team has is refused with 409.',
},
},
)
diff --git a/apps/web/messages/ar/projects.json b/apps/web/messages/ar/projects.json
index 7e8b0820..6a0fdce4 100644
--- a/apps/web/messages/ar/projects.json
+++ b/apps/web/messages/ar/projects.json
@@ -16,6 +16,8 @@
},
"editDialog": {
"title": "تعديل المشروع",
+ "key": "المفتاح",
+ "keyHint": "تتطلب روابط المهام مفتاحًا من أحرف كبيرة وأرقام يبدأ بحرف. بعد حفظه، لا يمكن تغيير المفتاح.",
"name": "الاسم",
"description": "الوصف",
"submit": "حفظ"
diff --git a/apps/web/messages/en/projects.json b/apps/web/messages/en/projects.json
index 916bed4b..41ddd12f 100644
--- a/apps/web/messages/en/projects.json
+++ b/apps/web/messages/en/projects.json
@@ -16,6 +16,8 @@
},
"editDialog": {
"title": "Edit project",
+ "key": "Key",
+ "keyHint": "Issue links need a key of capital letters and digits that starts with a letter. After you save it, the key cannot change.",
"name": "Name",
"description": "Description",
"submit": "Save"
diff --git a/apps/web/messages/es-ES/projects.json b/apps/web/messages/es-ES/projects.json
index 3ee24ec1..bacd9de0 100644
--- a/apps/web/messages/es-ES/projects.json
+++ b/apps/web/messages/es-ES/projects.json
@@ -16,6 +16,8 @@
},
"editDialog": {
"title": "Editar proyecto",
+ "key": "Clave",
+ "keyHint": "Los enlaces a incidencias necesitan una clave de letras mayúsculas y dígitos que empiece por una letra. Después de guardarla, la clave no se puede cambiar.",
"name": "Nombre",
"description": "Descripción",
"submit": "Guardar"
diff --git a/apps/web/messages/fr/projects.json b/apps/web/messages/fr/projects.json
index 20fd0570..aa9b9f14 100644
--- a/apps/web/messages/fr/projects.json
+++ b/apps/web/messages/fr/projects.json
@@ -16,6 +16,8 @@
},
"editDialog": {
"title": "Modifier le projet",
+ "key": "Clé",
+ "keyHint": "Les liens vers les tickets exigent une clé en lettres majuscules et chiffres qui commence par une lettre. Une fois enregistrée, la clé ne peut plus changer.",
"name": "Nom",
"description": "Description",
"submit": "Enregistrer"
diff --git a/apps/web/messages/id/projects.json b/apps/web/messages/id/projects.json
index 19ae2fb4..65108341 100644
--- a/apps/web/messages/id/projects.json
+++ b/apps/web/messages/id/projects.json
@@ -16,6 +16,8 @@
},
"editDialog": {
"title": "Ubah proyek",
+ "key": "Kunci",
+ "keyHint": "Tautan issue memerlukan kunci berupa huruf kapital dan angka yang diawali huruf. Setelah disimpan, kunci tidak dapat diubah.",
"name": "Nama",
"description": "Deskripsi",
"submit": "Simpan"
diff --git a/apps/web/messages/pt-BR/projects.json b/apps/web/messages/pt-BR/projects.json
index ae7bb99e..b948fa07 100644
--- a/apps/web/messages/pt-BR/projects.json
+++ b/apps/web/messages/pt-BR/projects.json
@@ -16,6 +16,8 @@
},
"editDialog": {
"title": "Editar projeto",
+ "key": "Chave",
+ "keyHint": "Os links de issues precisam de uma chave com letras maiúsculas e dígitos que comece com uma letra. Depois de salva, a chave não pode ser alterada.",
"name": "Nome",
"description": "Descrição",
"submit": "Salvar"
diff --git a/apps/web/messages/ru/projects.json b/apps/web/messages/ru/projects.json
index d9cf751a..632e4947 100644
--- a/apps/web/messages/ru/projects.json
+++ b/apps/web/messages/ru/projects.json
@@ -16,6 +16,8 @@
},
"editDialog": {
"title": "Изменить проект",
+ "key": "Ключ",
+ "keyHint": "Для ссылок на задачи ключ должен состоять из заглавных латинских букв и цифр и начинаться с буквы. После сохранения ключ изменить нельзя.",
"name": "Название",
"description": "Описание",
"submit": "Сохранить"
diff --git a/apps/web/messages/uk/projects.json b/apps/web/messages/uk/projects.json
index 0189b08d..45a6051a 100644
--- a/apps/web/messages/uk/projects.json
+++ b/apps/web/messages/uk/projects.json
@@ -16,6 +16,8 @@
},
"editDialog": {
"title": "Змінити проєкт",
+ "key": "Ключ",
+ "keyHint": "Для посилань на задачі ключ має складатися з великих латинських літер і цифр і починатися з літери. Після збереження ключ змінити не можна.",
"name": "Назва",
"description": "Опис",
"submit": "Зберегти"
diff --git a/apps/web/messages/zh-CN/projects.json b/apps/web/messages/zh-CN/projects.json
index 308254d4..2f8e0c47 100644
--- a/apps/web/messages/zh-CN/projects.json
+++ b/apps/web/messages/zh-CN/projects.json
@@ -16,6 +16,8 @@
},
"editDialog": {
"title": "编辑项目",
+ "key": "标识",
+ "keyHint": "事项链接要求标识由大写字母和数字组成,并以字母开头。保存后,标识不能再更改。",
"name": "名称",
"description": "描述",
"submit": "保存"
diff --git a/apps/web/src/features/teams/components/projects/TeamProjectEditModal.tsx b/apps/web/src/features/teams/components/projects/TeamProjectEditModal.tsx
index 04f43b9e..62f07fc9 100644
--- a/apps/web/src/features/teams/components/projects/TeamProjectEditModal.tsx
+++ b/apps/web/src/features/teams/components/projects/TeamProjectEditModal.tsx
@@ -11,9 +11,10 @@ import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
+import { isValidKey, normalizeKey } from '@/utils/projectKey';
-// Renames a project the team owns and edits what it is for. The key is immutable,
-// so it trails the title instead of being a field.
+// Renames a project the team owns and edits what it is for. The key trails the
+// title, and is a field only while it is not a valid key (see isValidKey).
export default function TeamProjectEditModal({
teamId,
project,
@@ -26,10 +27,12 @@ export default function TeamProjectEditModal({
const t = useTranslations('projects.editDialog');
const [name, setName] = useState(project.name);
const [description, setDescription] = useState(project.description);
+ const keyEditable = !isValidKey(project.key);
+ const [key, setKey] = useState(() => normalizeKey(project.key));
const updateProject = useUpdateTeamProject();
// Names the team in the header, the same as when the project was created.
const team = useTeam(teamId);
- const canSubmit = !updateProject.isPending && name.trim() !== '';
+ const canSubmit = !updateProject.isPending && name.trim() !== '' && key !== '';
function submit() {
if (!canSubmit) return;
@@ -38,7 +41,11 @@ export default function TeamProjectEditModal({
teamId,
projectId: project.id,
projectKey: project.ref,
- patch: { name: name.trim(), description: description.trim() },
+ patch: {
+ name: name.trim(),
+ description: description.trim(),
+ ...(keyEditable && { key }),
+ },
},
{ onSuccess: onClose },
);
@@ -60,6 +67,13 @@ export default function TeamProjectEditModal({
className="pb-3"
>
<div className="flex flex-col gap-3">
+ {keyEditable && (
+ <div className="space-y-1.5">
+ <Label>{t('key')}</Label>
+ <Input value={key} onChange={(e) => setKey(normalizeKey(e.target.value))} />
+ <p className="text-xs text-muted-foreground">{t('keyHint')}</p>
+ </div>
+ )}
<div className="space-y-1.5">
<Label>{t('name')}</Label>
<Input
diff --git a/apps/web/src/lib/api/endpoints/teams.ts b/apps/web/src/lib/api/endpoints/teams.ts
index 7cea270b..7ecb3488 100644
--- a/apps/web/src/lib/api/endpoints/teams.ts
+++ b/apps/web/src/lib/api/endpoints/teams.ts
@@ -271,7 +271,7 @@ export const copyTeamProject = (
export const updateTeamProject = (
teamId: number,
projectId: number,
- patch: { name?: string; description?: string },
+ patch: { key?: string; name?: string; description?: string },
) =>
request<Project>(`/teams/${teamId}/projects/${projectId}`, {
method: 'PATCH',
diff --git a/apps/web/src/services/projects.service.ts b/apps/web/src/services/projects.service.ts
index 68215e30..f75673b6 100644
--- a/apps/web/src/services/projects.service.ts
+++ b/apps/web/src/services/projects.service.ts
@@ -152,16 +152,27 @@ export function useUpdateTeamProject() {
teamId: number;
projectId: number;
projectKey: string;
- patch: { name?: string; description?: string };
+ patch: { key?: string; name?: string; description?: string };
}) => updateTeamProject(teamId, projectId, patch),
onSuccess: (updated, { teamId, projectKey }) => {
qc.setQueryData<Project[]>(qk.projects, (prev) =>
prev?.map((p) =>
- p.ref === projectKey ? { ...p, name: updated.name, description: updated.description } : p,
+ p.ref === projectKey
+ ? {
+ ...p,
+ key: updated.key,
+ ref: updated.ref,
+ name: updated.name,
+ description: updated.description,
+ }
+ : p,
),
);
void qc.invalidateQueries({ queryKey: qk.projects });
- void qc.invalidateQueries({ queryKey: qk.project(projectKey) });
+ // A renamed key leaves the old ref naming no project, so its cache is dropped
+ // rather than refetched.
+ if (updated.ref !== projectKey) qc.removeQueries({ queryKey: qk.project(projectKey) });
+ else void qc.invalidateQueries({ queryKey: qk.project(projectKey) });
void qc.invalidateQueries({ queryKey: qk.team(teamId) });
},
});
diff --git a/apps/web/src/utils/projectKey.ts b/apps/web/src/utils/projectKey.ts
index b3bb276d..e9703d1b 100644
--- a/apps/web/src/utils/projectKey.ts
+++ b/apps/web/src/utils/projectKey.ts
@@ -72,3 +72,9 @@ export function normalizeKey(input: string): string {
.replace(/^\d+/, '')
.slice(0, KEY_MAX_LENGTH);
}
+
+// Whether a stored key matches what normalizeKey produces. A project created before
+// that rule existed may carry a key that does not, and may then change it.
+export function isValidKey(key: string): boolean {
+ return normalizeKey(key) === key && key !== '';
+}