Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

feat: add short task links like /acme/task/KAN-12 (#1891)

Andrejd5ad3fdd1453
diff --git a/apps/api/src/plugins/github/utils/branch-matcher.ts b/apps/api/src/plugins/github/utils/branch-matcher.ts
index 71ff8ee30..f68387756 100644
--- a/apps/api/src/plugins/github/utils/branch-matcher.ts
+++ b/apps/api/src/plugins/github/utils/branch-matcher.ts
@@ -69,19 +69,32 @@ export function extractTaskNumberFromBranch(
return null;
}
+const URL_PATTERN = /\bhttps?:\/\/\S+/gi;
+
+function withShortLinksAsTickets(text: string) {
+ return text.replace(URL_PATTERN, (url) => {
+ const ticket = url.match(
+ /\/task\/([^/?#\s]+-\d+)(?![\p{L}\p{N}\p{M}_~-])/u,
+ )?.[1];
+ return ticket ? ` ${ticket} ` : url;
+ });
+}
+
function extractExplicitTaskNumber(
text: string,
projectSlug?: string,
): number | null {
if (projectSlug) {
const slug = projectSlug.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
- const key = text.match(
+ const key = withShortLinksAsTickets(text).match(
new RegExp(`(?:^|[^\\w-])${slug}-(\\d+)(?=$|[^\\w])`, "i"),
);
if (key?.[1]) return Number.parseInt(key[1], 10);
}
- const task = text.match(/\btask[:\-\s#]+(\d+)\b/i);
+ const task = text
+ .replace(URL_PATTERN, "<link>")
+ .match(/\btask[:\-\s#]+(\d+)\b/i);
return task?.[1] ? Number.parseInt(task[1], 10) : null;
}
diff --git a/apps/api/src/project/controllers/create-project.ts b/apps/api/src/project/controllers/create-project.ts
index 587161225..a37b652aa 100644
--- a/apps/api/src/project/controllers/create-project.ts
+++ b/apps/api/src/project/controllers/create-project.ts
@@ -1,6 +1,8 @@
import { eq, max, sql } from "drizzle-orm";
+import { HTTPException } from "hono/http-exception";
import db from "../../database";
import { columnTable, projectTable } from "../../database/schema";
+import { findProjectKeyConflict, projectKeyTakenMessage } from "../project-key";
export const DEFAULT_PROJECT_COLUMNS = [
{ name: "To Do", slug: "to-do", position: 0, isFinal: false },
@@ -24,6 +26,13 @@ async function createProject(
sql`SELECT pg_advisory_xact_lock(1524, hashtext(${workspaceId}))`,
);
+ const keyConflict = await findProjectKeyConflict(tx, workspaceId, slug);
+ if (keyConflict) {
+ throw new HTTPException(409, {
+ message: projectKeyTakenMessage(slug, keyConflict.name),
+ });
+ }
+
// New projects go to the bottom of the workspace's ordering.
const [{ maxPosition } = { maxPosition: null }] = await tx
.select({ maxPosition: max(projectTable.position) })
diff --git a/apps/api/src/project/controllers/move-project.ts b/apps/api/src/project/controllers/move-project.ts
index 43d24b7a2..99696320a 100644
--- a/apps/api/src/project/controllers/move-project.ts
+++ b/apps/api/src/project/controllers/move-project.ts
@@ -1,13 +1,4 @@
-import {
- and,
- eq,
- inArray,
- isNotNull,
- max,
- ne,
- notInArray,
- sql,
-} from "drizzle-orm";
+import { and, eq, inArray, isNotNull, max, notInArray, sql } from "drizzle-orm";
import { HTTPException } from "hono/http-exception";
import createActivities from "../../activity/controllers/create-activities";
import db from "../../database";
@@ -24,6 +15,7 @@ import {
} from "../../database/schema";
import { publishEvent } from "../../events";
import { closeProjectConnections } from "../../ws";
+import { findProjectKeyConflict } from "../project-key";
async function moveProject(
id: string,
@@ -72,17 +64,12 @@ async function moveProject(
// rather than silently renaming a project out from under its ticket ids.
// Compared case-insensitively, since the lookup is. Archived projects
// count: their tasks still resolve by short id.
- const [keyConflict] = await tx
- .select({ name: projectTable.name })
- .from(projectTable)
- .where(
- and(
- eq(projectTable.workspaceId, targetWorkspaceId),
- ne(projectTable.id, id),
- sql`lower(${projectTable.slug}) = lower(${existingProject.slug})`,
- ),
- )
- .limit(1);
+ const keyConflict = await findProjectKeyConflict(
+ tx,
+ targetWorkspaceId,
+ existingProject.slug,
+ { excludeProjectId: id },
+ );
if (keyConflict) {
throw new HTTPException(409, {
diff --git a/apps/api/src/project/controllers/unarchive-project.ts b/apps/api/src/project/controllers/unarchive-project.ts
index ec8eabbeb..1d66f0648 100644
--- a/apps/api/src/project/controllers/unarchive-project.ts
+++ b/apps/api/src/project/controllers/unarchive-project.ts
@@ -1,36 +1,56 @@
-import { and, eq } from "drizzle-orm";
+import { and, eq, sql } from "drizzle-orm";
import { HTTPException } from "hono/http-exception";
import db from "../../database";
import { projectTable } from "../../database/schema";
+import { findProjectKeyConflict } from "../project-key";
async function unarchiveProject(id: string, workspaceId: string) {
- const [existingProject] = await db
- .select()
- .from(projectTable)
- .where(
- and(eq(projectTable.id, id), eq(projectTable.workspaceId, workspaceId)),
+ return db.transaction(async (tx) => {
+ await tx.execute(
+ sql`SELECT pg_advisory_xact_lock(1524, hashtext(${workspaceId}))`,
);
- if (!existingProject) {
- throw new HTTPException(404, {
- message:
- "Project doesn't exist or doesn't belong to the specified workspace",
- });
- }
-
- const [unarchivedProject] = await db
- .update(projectTable)
- .set({ archivedAt: null })
- .where(eq(projectTable.id, id))
- .returning();
-
- if (!unarchivedProject) {
- throw new HTTPException(500, {
- message: "Failed to unarchive project",
- });
- }
-
- return unarchivedProject;
+ const [existingProject] = await tx
+ .select()
+ .from(projectTable)
+ .where(
+ and(eq(projectTable.id, id), eq(projectTable.workspaceId, workspaceId)),
+ )
+ .for("update");
+
+ if (!existingProject) {
+ throw new HTTPException(404, {
+ message:
+ "Project doesn't exist or doesn't belong to the specified workspace",
+ });
+ }
+
+ const keyConflict = await findProjectKeyConflict(
+ tx,
+ workspaceId,
+ existingProject.slug,
+ { excludeProjectId: id },
+ );
+ if (keyConflict) {
+ throw new HTTPException(409, {
+ message: `This workspace already has a project using the key "${existingProject.slug}" (${keyConflict.name}). Change one of the keys before unarchiving this project.`,
+ });
+ }
+
+ const [unarchivedProject] = await tx
+ .update(projectTable)
+ .set({ archivedAt: null })
+ .where(eq(projectTable.id, id))
+ .returning();
+
+ if (!unarchivedProject) {
+ throw new HTTPException(500, {
+ message: "Failed to unarchive project",
+ });
+ }
+
+ return unarchivedProject;
+ });
}
export default unarchiveProject;
diff --git a/apps/api/src/project/controllers/update-project.ts b/apps/api/src/project/controllers/update-project.ts
index 887c8aac4..a60946fad 100644
--- a/apps/api/src/project/controllers/update-project.ts
+++ b/apps/api/src/project/controllers/update-project.ts
@@ -1,7 +1,12 @@
-import { and, eq } from "drizzle-orm";
+import { and, eq, sql } from "drizzle-orm";
import { HTTPException } from "hono/http-exception";
import db from "../../database";
import { projectTable } from "../../database/schema";
+import {
+ findProjectKeyConflict,
+ isSameProjectKey,
+ projectKeyTakenMessage,
+} from "../project-key";
async function updateProject(
id: string,
@@ -13,40 +18,58 @@ async function updateProject(
workspaceId: string,
canShare: boolean,
) {
- const [existingProject] = await db
- .select()
- .from(projectTable)
- .where(
- and(eq(projectTable.id, id), eq(projectTable.workspaceId, workspaceId)),
+ return db.transaction(async (tx) => {
+ await tx.execute(
+ sql`SELECT pg_advisory_xact_lock(1524, hashtext(${workspaceId}))`,
);
- if (!existingProject) {
- throw new HTTPException(404, {
- message:
- "Project doesn't exist or doesn't belong to the specified workspace",
- });
- }
-
- if (isPublic !== existingProject.isPublic && !canShare) {
- throw new HTTPException(403, {
- message:
- "Changing project visibility requires the project:share permission",
- });
- }
-
- const [updatedWorkspace] = await db
- .update(projectTable)
- .set({
- name,
- icon,
- slug,
- description,
- isPublic,
- })
- .where(eq(projectTable.id, id))
- .returning();
-
- return updatedWorkspace;
+ const [existingProject] = await tx
+ .select()
+ .from(projectTable)
+ .where(
+ and(eq(projectTable.id, id), eq(projectTable.workspaceId, workspaceId)),
+ )
+ .for("update");
+
+ if (!existingProject) {
+ throw new HTTPException(404, {
+ message:
+ "Project doesn't exist or doesn't belong to the specified workspace",
+ });
+ }
+
+ if (isPublic !== existingProject.isPublic && !canShare) {
+ throw new HTTPException(403, {
+ message:
+ "Changing project visibility requires the project:share permission",
+ });
+ }
+
+ if (!isSameProjectKey(slug, existingProject.slug)) {
+ const keyConflict = await findProjectKeyConflict(tx, workspaceId, slug, {
+ excludeProjectId: id,
+ });
+ if (keyConflict) {
+ throw new HTTPException(409, {
+ message: projectKeyTakenMessage(slug, keyConflict.name),
+ });
+ }
+ }
+
+ const [updatedProject] = await tx
+ .update(projectTable)
+ .set({
+ name,
+ icon,
+ slug,
+ description,
+ isPublic,
+ })
+ .where(eq(projectTable.id, id))
+ .returning();
+
+ return updatedProject;
+ });
}
export default updateProject;
diff --git a/apps/api/src/project/index.ts b/apps/api/src/project/index.ts
index 2689ac375..b9d5f3ea8 100644
--- a/apps/api/src/project/index.ts
+++ b/apps/api/src/project/index.ts
@@ -131,6 +131,7 @@ const createProjectRoute = createRoute({
403: errorResponse(
"No workspace access, or missing project:create permission",
),
+ 409: errorResponse("Another project in the workspace uses this key"),
},
});
@@ -207,6 +208,7 @@ const updateProjectRoute = createRoute({
403: errorResponse(
"No workspace access, missing project:update, or missing project:share when visibility changes",
),
+ 409: errorResponse("Another project in the workspace uses the new key"),
},
});
@@ -278,6 +280,7 @@ const unarchiveProjectRoute = createRoute({
403: errorResponse(
"No workspace access, or missing project:update permission",
),
+ 409: errorResponse("Another project in the workspace uses this key"),
},
});
diff --git a/apps/api/src/project/project-key.ts b/apps/api/src/project/project-key.ts
new file mode 100644
index 000000000..5a9b3b098
--- /dev/null
+++ b/apps/api/src/project/project-key.ts
@@ -0,0 +1,40 @@
+import { and, eq, ne, or, sql } from "drizzle-orm";
+import type db from "../database";
+import { projectTable } from "../database/schema";
+
+export function isSameProjectKey(a: string, b: string) {
+ return (
+ a.normalize("NFKC").toLowerCase() === b.normalize("NFKC").toLowerCase()
+ );
+}
+
+export function mayMatchProjectKey(key: string) {
+ return or(
+ sql`lower(${projectTable.slug}) = lower(${key.normalize("NFKC")})`,
+ sql`octet_length(${projectTable.slug}) <> char_length(${projectTable.slug})`,
+ );
+}
+
+export async function findProjectKeyConflict(
+ database: Pick<typeof db, "select">,
+ workspaceId: string,
+ key: string,
+ { excludeProjectId }: { excludeProjectId?: string } = {},
+) {
+ const projects = await database
+ .select({ name: projectTable.name, slug: projectTable.slug })
+ .from(projectTable)
+ .where(
+ and(
+ eq(projectTable.workspaceId, workspaceId),
+ mayMatchProjectKey(key),
+ excludeProjectId ? ne(projectTable.id, excludeProjectId) : undefined,
+ ),
+ );
+
+ return projects.find((project) => isSameProjectKey(project.slug, key));
+}
+
+export function projectKeyTakenMessage(key: string, projectName: string) {
+ return `This workspace already has a project using the key "${key}" (${projectName}). Choose a different key.`;
+}
diff --git a/apps/api/src/task/controllers/get-task-by-ticket-id.ts b/apps/api/src/task/controllers/get-task-by-ticket-id.ts
index 5812dbfaf..28402dfdb 100644
--- a/apps/api/src/task/controllers/get-task-by-ticket-id.ts
+++ b/apps/api/src/task/controllers/get-task-by-ticket-id.ts
@@ -1,27 +1,35 @@
-import { and, eq, ilike, inArray } from "drizzle-orm";
+import { and, eq, inArray, sql } from "drizzle-orm";
import { HTTPException } from "hono/http-exception";
import db from "../../database";
import {
projectTable,
taskTable,
userTable,
+ workspaceTable,
workspaceUserTable,
} from "../../database/schema";
-import { escapeLikePattern } from "../../search/like-pattern";
-import { TASK_SHORT_ID_PATTERN } from "../../search/task-short-id";
+import {
+ isSameProjectKey,
+ mayMatchProjectKey,
+} from "../../project/project-key";
+import { TICKET_ID_PATTERN } from "../ticket-id";
import { hasInstanceAdminRole } from "../../utils/instance-admin-role";
import getTask from "./get-task";
export default async function getTaskByTicketId(
ticketId: string,
userId: string,
- workspaceId?: string,
- projectId?: string,
+ {
+ workspaceId,
+ workspaceSlug,
+ projectId,
+ }: { workspaceId?: string; workspaceSlug?: string; projectId?: string } = {},
) {
- const match = ticketId.normalize("NFKC").match(TASK_SHORT_ID_PATTERN);
+ const match = ticketId.normalize("NFKC").match(TICKET_ID_PATTERN);
+ const projectKey = match?.[1];
const number = Number(match?.[2]);
if (
- !match?.[1] ||
+ !projectKey ||
!Number.isSafeInteger(number) ||
number < 1 ||
number > 2_147_483_647
@@ -40,32 +48,63 @@ export default async function getTaskByTicketId(
.from(workspaceUserTable)
.where(eq(workspaceUserTable.userId, userId));
- const matches = await db
- .select({ id: taskTable.id })
+ let slugWorkspaceIds: string[] | undefined;
+ if (workspaceSlug) {
+ const slugMatches = await db
+ .select({ id: workspaceTable.id, slug: workspaceTable.slug })
+ .from(workspaceTable)
+ .where(sql`lower(${workspaceTable.slug}) = lower(${workspaceSlug})`);
+ const exactMatch = slugMatches.find(
+ (workspace) => workspace.slug === workspaceSlug,
+ );
+ slugWorkspaceIds = exactMatch
+ ? [exactMatch.id]
+ : slugMatches.map((workspace) => workspace.id);
+ if (slugWorkspaceIds.length === 0) {
+ throw new HTTPException(404, { message: "Task not found" });
+ }
+ }
+
+ const candidates = await db
+ .select({
+ id: taskTable.id,
+ workspaceId: projectTable.workspaceId,
+ slug: projectTable.slug,
+ archivedAt: projectTable.archivedAt,
+ })
.from(taskTable)
.innerJoin(projectTable, eq(taskTable.projectId, projectTable.id))
.where(
and(
- ilike(projectTable.slug, escapeLikePattern(match[1])),
eq(taskTable.number, number),
+ mayMatchProjectKey(projectKey),
workspaceId ? eq(projectTable.workspaceId, workspaceId) : undefined,
+ slugWorkspaceIds
+ ? inArray(projectTable.workspaceId, slugWorkspaceIds)
+ : undefined,
projectId ? eq(projectTable.id, projectId) : undefined,
hasInstanceAdminRole(user?.role)
? undefined
: inArray(projectTable.workspaceId, memberWorkspaces),
),
- )
- .limit(2);
+ );
- const matchedTask = matches[0];
+ const rank = (candidate: { archivedAt: Date | null }) =>
+ candidate.archivedAt?.getTime() ?? Number.POSITIVE_INFINITY;
+ const [matchedTask, nextMatch] = candidates
+ .filter((candidate) => isSameProjectKey(candidate.slug, projectKey))
+ .sort((a, b) => (rank(a) === rank(b) ? 0 : rank(a) > rank(b) ? -1 : 1));
if (!matchedTask) {
throw new HTTPException(404, { message: "Task not found" });
}
- if (matches.length > 1) {
+ if (nextMatch && rank(nextMatch) === rank(matchedTask)) {
throw new HTTPException(409, {
message: "Task ticket ID matches multiple accessible tasks",
});
}
- return getTask(matchedTask.id);
+ return {
+ ...(await getTask(matchedTask.id)),
+ workspaceId: matchedTask.workspaceId,
+ };
}
diff --git a/apps/api/src/task/index.ts b/apps/api/src/task/index.ts
index 1263270c3..d2cd30d7c 100644
--- a/apps/api/src/task/index.ts
+++ b/apps/api/src/task/index.ts
@@ -76,6 +76,7 @@ import {
finalizedAssetSchema,
imageUploadSchema,
moveTaskResultSchema,
+ taskByTicketIdSchema,
taskExportSchema,
taskImportResultSchema,
taskSchema,
@@ -366,10 +367,10 @@ const getTaskByTicketIdRoute = createRoute({
tags: ["Tasks"],
summary: "Get task by ticket ID",
description:
- "Get a single task by its project key and number, such as KAN-12. If the ticket ID matches multiple accessible tasks, provide workspaceId or projectId to select one.",
+ "Get a single task by its project key and number, such as KAN-12. A match in an active project takes precedence, then the most recently archived project. If the ticket ID still matches multiple accessible tasks, narrow the lookup to a workspace with workspaceId or workspaceSlug, or to a single project with projectId.",
request: { params: ticketIdParam, query: ticketIdQuery },
responses: {
- 200: jsonResponse("Task details", taskWithAssigneeSchema),
+ 200: jsonResponse("Task details", taskByTicketIdSchema),
400: errorResponse("Invalid ticket ID"),
404: errorResponse("No accessible task has this ticket ID"),
409: errorResponse("Ticket ID matches multiple accessible tasks"),
@@ -928,14 +929,8 @@ const task = apiRouter<BaseVariables & { workspaceId: string }>()
})
.openapi(getTaskByTicketIdRoute, async (c) => {
const { ticketId } = c.req.valid("param");
- const { workspaceId, projectId } = c.req.valid("query");
return c.json(
- await getTaskByTicketId(
- ticketId,
- c.get("userId"),
- workspaceId,
- projectId,
- ),
+ await getTaskByTicketId(ticketId, c.get("userId"), c.req.valid("query")),
200,
);
})
diff --git a/apps/api/src/task/response.ts b/apps/api/src/task/response.ts
index d7238a921..e8eabb3a2 100644
--- a/apps/api/src/task/response.ts
+++ b/apps/api/src/task/response.ts
@@ -62,6 +62,14 @@ export const taskWithAssigneeSchema = taskSchema
})
.openapi("TaskWithAssignee");
+export const taskByTicketIdSchema = taskWithAssigneeSchema
+ .extend({
+ workspaceId: z.string().openapi({
+ description: "The workspace that owns the task's project.",
+ }),
+ })
+ .openapi("TaskByTicketId");
+
const taskLabelSchema = z
.object({ id: z.string(), name: z.string(), color: z.string() })
.openapi("TaskLabel");
diff --git a/apps/api/src/task/schema.ts b/apps/api/src/task/schema.ts
index b8cfb3649..7bea11e0e 100644
--- a/apps/api/src/task/schema.ts
+++ b/apps/api/src/task/schema.ts
@@ -1,6 +1,6 @@
import { pagingNumber, z } from "../openapi";
-import { TASK_SHORT_ID_PATTERN } from "../search/task-short-id";
import { MAX_TASK_POSITION } from "./controllers/next-task-position";
+import { TICKET_ID_PATTERN } from "./ticket-id";
import { VALID_PRIORITIES } from "./validate-task-fields";
export const taskParam = z.object({ id: z.string() });
@@ -9,10 +9,7 @@ export const ticketIdParam = z.object({
ticketId: z
.string()
.max(128)
- .refine(
- (value) => TASK_SHORT_ID_PATTERN.test(value),
- "Invalid task ticket ID",
- )
+ .refine((value) => TICKET_ID_PATTERN.test(value), "Invalid task ticket ID")
.openapi({
description: "Project key and task number, e.g. KAN-12.",
}),
@@ -22,6 +19,9 @@ export const ticketIdQuery = z.object({
workspaceId: z.string().min(1).optional().openapi({
description: "Select a workspace if the ticket ID exists in more than one.",
}),
+ workspaceSlug: z.string().min(1).max(128).optional().openapi({
+ description: "Select a workspace by its slug instead of its ID.",
+ }),
projectId: z.string().min(1).optional().openapi({
description: "Select a project if the ticket ID exists more than once.",
}),
diff --git a/apps/api/src/task/ticket-id.ts b/apps/api/src/task/ticket-id.ts
new file mode 100644
index 000000000..ff4cde48e
--- /dev/null
+++ b/apps/api/src/task/ticket-id.ts
@@ -0,0 +1 @@
+export const TICKET_ID_PATTERN = /^(.+)-(\d+)$/u;
diff --git a/apps/docs/core/integrations/gitea/setup.mdx b/apps/docs/core/integrations/gitea/setup.mdx
index 7ef148f39..d51c082f3 100644
--- a/apps/docs/core/integrations/gitea/setup.mdx
+++ b/apps/docs/core/integrations/gitea/setup.mdx
@@ -45,6 +45,20 @@ Save the repository connection, verify its current settings, then choose **Impor
Choose your branch naming pattern in the integration settings. In the project’s [Workflow settings](/core/functional/configure-workflows), map branch pushes, opened pull requests, and merged pull requests to the intended columns. Try one task first and check its status before adopting the pattern across your team.
+## Link task IDs to Kaneo
+
+Every task has a short link built from its workspace and ticket ID, such as `https://kaneo.example.com/acme/task/KAN-12/fix-login-timeout`. The title at the end is optional and ignored, so `https://kaneo.example.com/acme/task/KAN-12` opens the same task. **Copy link** on a task gives you this link, which shows your workspace’s part of the path.
+
+To turn references such as `KAN-12` in Gitea commits and pull requests into links, open the repository’s **Settings**, enable **Use External Issue Tracker**, and set:
+
+| Gitea setting | Value |
+| --- | --- |
+| External Issue Tracker URL | `https://kaneo.example.com` |
+| External Issue Tracker URL Format | `https://kaneo.example.com/acme/task/{index}`, with your workspace in place of `acme` |
+| External Issue Tracker Number Format | Alphanumeric |
+
+The alphanumeric format only matches keys of one to ten uppercase letters. For any other key, choose **Regular Expression** and match your project’s key exactly, such as `(DE_-\d+)`, `(ПРО-\d+)`, or `(OPS\.2-\d+)` with the `.` escaped. To link several projects, list their keys: `((?:KAN|OPS)-\d+)`.
+
## Replace a token or disconnect
To rotate credentials, enter a replacement token, verify access, and save. On an existing connection, an empty token field keeps the saved token; it does not clear it.
diff --git a/apps/docs/core/integrations/github/configuration.mdx b/apps/docs/core/integrations/github/configuration.mdx
index a7b52566a..60f33750b 100644
--- a/apps/docs/core/integrations/github/configuration.mdx
+++ b/apps/docs/core/integrations/github/configuration.mdx
@@ -126,7 +126,7 @@ Kaneo checks the configured branch pattern first, then explicit task references
Issue references use the remote repository's numbering. A title containing `#61` or a body containing `Closes #61` resolves through the issue link recorded by this integration. If GitHub issue 61 is linked to Kaneo task `PROJ-42`, the PR belongs to `PROJ-42`, even if `PROJ-61` also exists. Same-repository `owner/repo#61` references and issue URLs are also supported. References to another repository are ignored.
-If none of those match, Kaneo looks for a task link in the PR title or body. Paste the link from **Copy task link** on the task, and the PR is linked to that task. A PR that links to more than one task, or to a task in another project, is not linked.
+Links from **Copy task link**, such as `https://kaneo.example.com/acme/task/PROJ-42/fix-login`, contain the project key, so pasting one in the PR title or body links the PR to that task. If none of those match, Kaneo also looks for a full task URL (`/dashboard/workspace/.../task/...`). A PR with full URLs to more than one task, or to a task in another project, is not linked.
Without an explicit task reference, unmapped issues do not create PR associations. References that map to multiple tasks within the integration are skipped. Repeated issue links to the same task are accepted. Bare numeric title shortcuts such as `[42]`, `(42)`, or `42: ...` are not task identifiers; use the project key instead.
diff --git a/apps/docs/openapi.json b/apps/docs/openapi.json
index 511d34907..3ef2e70d8 100644
--- a/apps/docs/openapi.json
+++ b/apps/docs/openapi.json
@@ -1165,6 +1165,25 @@
"createdAt"
]
},
+ "TaskByTicketId": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/TaskWithAssignee"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "workspaceId": {
+ "type": "string",
+ "description": "The workspace that owns the task's project."
+ }
+ },
+ "required": [
+ "workspaceId"
+ ]
+ }
+ ]
+ },
"TaskWithAssignee": {
"allOf": [
{
@@ -7389,6 +7408,16 @@
}
}
}
+ },
+ "409": {
+ "description": "Another project in the workspace uses this key",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
}
}
}
@@ -7531,6 +7560,16 @@
}
}
}
+ },
+ "409": {
+ "description": "Another project in the workspace uses the new key",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
}
}
},
@@ -7902,6 +7941,16 @@
}
}
}
+ },
+ "409": {
+ "description": "Another project in the workspace uses this key",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
}
}
}
@@ -9504,7 +9553,7 @@
"Tasks"
],
"summary": "Get task by ticket ID",
- "description": "Get a single task by its project key and number, such as KAN-12. If the ticket ID matches multiple accessible tasks, provide workspaceId or projectId to select one.",
+ "description": "Get a single task by its project key and number, such as KAN-12. A match in an active project takes precedence, then the most recently archived project. If the ticket ID still matches multiple accessible tasks, narrow the lookup to a workspace with workspaceId or workspaceSlug, or to a single project with projectId.",
"parameters": [
{
"schema": {
@@ -9528,6 +9577,18 @@
"name": "workspaceId",
"in": "query"
},
+ {
+ "schema": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 128,
+ "description": "Select a workspace by its slug instead of its ID."
+ },
+ "required": false,
+ "description": "Select a workspace by its slug instead of its ID.",
+ "name": "workspaceSlug",
+ "in": "query"
+ },
{
"schema": {
"type": "string",
@@ -9546,7 +9607,7 @@
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/TaskWithAssignee"
+ "$ref": "#/components/schemas/TaskByTicketId"
}
}
}
diff --git a/apps/web/src/components/backlog-list-view/backlog-task-row.tsx b/apps/web/src/components/backlog-list-view/backlog-task-row.tsx
index 72e4c7e6d..8433d6770 100644
--- a/apps/web/src/components/backlog-list-view/backlog-task-row.tsx
+++ b/apps/web/src/components/backlog-list-view/backlog-task-row.tsx
@@ -326,6 +326,7 @@ const BacklogTaskRow = memo(function BacklogTaskRow({
taskCardContext={{
projectId,
worskpaceId: workspace.id,
+ workspaceSlug: workspace.slug,
}}
onDeleteClick={() => setIsDeleteTaskModalOpen(true)}
/>
diff --git a/apps/web/src/components/kanban-board/task-card-context-menu/task-card-context-menu-content.test.tsx b/apps/web/src/components/kanban-board/task-card-context-menu/task-card-context-menu-content.test.tsx
index 50280880c..e7117a154 100644
--- a/apps/web/src/components/kanban-board/task-card-context-menu/task-card-context-menu-content.test.tsx
+++ b/apps/web/src/components/kanban-board/task-card-context-menu/task-card-context-menu-content.test.tsx
@@ -70,6 +70,11 @@ vi.mock(
}),
);
+vi.mock("@tanstack/react-query", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@tanstack/react-query")>()),
+ useQueryClient: () => ({ getQueryData: () => [] }),
+}));
+
vi.mock("@/hooks/mutations/task/use-update-task", () => ({
useUpdateTask: () => ({ mutateAsync: vi.fn() }),
}));
diff --git a/apps/web/src/components/kanban-board/task-card-context-menu/task-card-context-menu-content.tsx b/apps/web/src/components/kanban-board/task-card-context-menu/task-card-context-menu-content.tsx
index f24165a66..3e750f1fd 100644
--- a/apps/web/src/components/kanban-board/task-card-context-menu/task-card-context-menu-content.tsx
+++ b/apps/web/src/components/kanban-board/task-card-context-menu/task-card-context-menu-content.tsx
@@ -1,3 +1,4 @@
+import { useQueryClient } from "@tanstack/react-query";
import { X } from "lucide-react";
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
@@ -20,6 +21,7 @@ import { useUpdateTaskDueDate } from "@/hooks/mutations/task/use-update-task-due
import { useUpdateTaskStatus } from "@/hooks/mutations/task/use-update-task-status";
import { useUpdateTaskPriority } from "@/hooks/mutations/task/use-update-task-status-priority";
import { useUpdateTaskTitle } from "@/hooks/mutations/task/use-update-task-title";
+import type getProjects from "@/fetchers/project/get-projects";
import { useGetColumns } from "@/hooks/queries/column/use-get-columns";
import { useGetActiveWorkspaceUsers } from "@/hooks/queries/workspace-users/use-get-active-workspace-users";
import { useWorkspacePermission } from "@/hooks/use-workspace-permission";
@@ -28,12 +30,14 @@ import { generateLink } from "@/lib/generate-link";
import { getInitials } from "@/lib/get-initials";
import { getPriorityLabel } from "@/lib/i18n/domain";
import { getPriorityIcon } from "@/lib/priority";
+import { getTaskPath } from "@/lib/task-link";
import { toast } from "@/lib/toast";
import useProjectStore from "@/store/project";
import type Task from "@/types/task";
type TaskCardContext = {
worskpaceId: string;
+ workspaceSlug?: string | null;
projectId: string;
};
@@ -50,6 +54,7 @@ export default function TaskCardContextMenuContent({
}: TaskCardContextMenuContentProps) {
const { t } = useTranslation();
const { project } = useProjectStore();
+ const queryClient = useQueryClient();
const { data: columnsData = [] } = useGetColumns(taskCardContext.projectId);
const columns =
project?.columns && project.columns.length > 0
@@ -93,7 +98,20 @@ export default function TaskCardContextMenuContent({
}, [workspaceUsers]);
const handleCopyTaskLink = () => {
- const path = `/dashboard/workspace/${taskCardContext.worskpaceId}/project/${taskCardContext.projectId}/task/${task.id}`;
+ const path = getTaskPath({
+ workspaceId: taskCardContext.worskpaceId,
+ workspace: {
+ id: taskCardContext.worskpaceId,
+ slug: taskCardContext.workspaceSlug,
+ },
+ projectId: taskCardContext.projectId,
+ workspaceProjects: queryClient.getQueryData<
+ Awaited<ReturnType<typeof getProjects>>
+ >(["projects", taskCardContext.worskpaceId]),
+ taskId: task.id,
+ taskNumber: task.number,
+ title: task.title,
+ });
const taskLink = generateLink(path);
navigator.clipboard.writeText(taskLink);
diff --git a/apps/web/src/components/kanban-board/task-card.tsx b/apps/web/src/components/kanban-board/task-card.tsx
index 183c1437a..2e9151dff 100644
--- a/apps/web/src/components/kanban-board/task-card.tsx
+++ b/apps/web/src/components/kanban-board/task-card.tsx
@@ -423,6 +423,7 @@ function TaskCard({
taskCardContext={{
projectId: project.id,
worskpaceId: workspace.id,
+ workspaceSlug: workspace.slug,
}}
onDeleteClick={() => setIsDeleteTaskModalOpen(true)}
/>
diff --git a/apps/web/src/components/list-view/task-row.tsx b/apps/web/src/components/list-view/task-row.tsx
index 66ce25f06..5da882b0f 100644
--- a/apps/web/src/components/list-view/task-row.tsx
+++ b/apps/web/src/components/list-view/task-row.tsx
@@ -253,6 +253,7 @@ function TaskRow({ task, projectSlug }: TaskRowProps) {
taskCardContext={{
projectId: project.id,
worskpaceId: workspace.id,
+ workspaceSlug: workspace.slug,
}}
onDeleteClick={() => setIsDeleteTaskModalOpen(true)}
/>
diff --git a/apps/web/src/components/task/subtask-row.tsx b/apps/web/src/components/task/subtask-row.tsx
index b921314f2..7c5b977e2 100644
--- a/apps/web/src/components/task/subtask-row.tsx
+++ b/apps/web/src/components/task/subtask-row.tsx
@@ -15,6 +15,7 @@ type SubtaskRowProps = {
tasks: Task[];
projectId: string;
workspaceId: string;
+ workspaceSlug?: string | null;
isSelected: boolean;
isFocused: boolean;
isCompleted: boolean;
@@ -33,6 +34,7 @@ export default function SubtaskRow({
tasks,
projectId,
workspaceId,
+ workspaceSlug,
isSelected,
isFocused,
isCompleted,
@@ -131,6 +133,7 @@ export default function SubtaskRow({
taskCardContext={{
projectId,
worskpaceId: workspaceId,
+ workspaceSlug,
}}
onDeleteClick={onDeleteClick}
/>
diff --git a/apps/web/src/components/task/task-properties-sidebar.tsx b/apps/web/src/components/task/task-properties-sidebar.tsx
index 85025f3b9..db9898256 100644
--- a/apps/web/src/components/task/task-properties-sidebar.tsx
+++ b/apps/web/src/components/task/task-properties-sidebar.tsx
@@ -18,6 +18,7 @@ import useGetLabelsByTask from "@/hooks/queries/label/use-get-labels-by-task";
import useGetProject from "@/hooks/queries/project/use-get-project";
import useGetProjects from "@/hooks/queries/project/use-get-projects";
import useGetTask from "@/hooks/queries/task/use-get-task";
+import useActiveWorkspace from "@/hooks/queries/workspace/use-active-workspace";
import { useGetActiveWorkspaceUsers } from "@/hooks/queries/workspace-users/use-get-active-workspace-users";
import { useTaskCopyShortcuts } from "@/hooks/use-task-copy-shortcuts";
import { getColumnIcon } from "@/lib/column";
@@ -27,10 +28,12 @@ import {
isTaskCompleted,
} from "@/lib/due-date-status";
import { formatDateShort } from "@/lib/format";
+import { generateLink } from "@/lib/generate-link";
import { getInitials } from "@/lib/get-initials";
import { getPriorityLabel, getStatusDisplayLabel } from "@/lib/i18n/domain";
import { resolveLabelColor } from "@/lib/label-color";
import { getPriorityIcon } from "@/lib/priority";
+import { getTaskPath } from "@/lib/task-link";
import { toast } from "@/lib/toast";
import TaskActions from "./task-actions";
import TaskAssigneePopover from "./task-assignee-popover";
@@ -84,6 +87,7 @@ export default function TaskPropertiesSidebar({
const { t } = useTranslation();
const { data: task } = useGetTask(taskId ?? "");
const { data: project } = useGetProject({ id: projectId, workspaceId });
+ const { data: workspace } = useActiveWorkspace();
const { data: columns = [] } = useGetColumns(projectId);
const taskIsCompleted = isTaskCompleted(task?.status ?? "", columns);
const { data: workspaceUsers } = useGetActiveWorkspaceUsers(workspaceId);
@@ -121,8 +125,19 @@ export default function TaskPropertiesSidebar({
);
const handleCopyTaskLink = () => {
+ if (!taskId) return;
navigator.clipboard.writeText(
- `${window.location.origin}/dashboard/workspace/${workspaceId}/project/${projectId}/task/${taskId}`,
+ generateLink(
+ getTaskPath({
+ workspaceId,
+ workspace,
+ projectId,
+ workspaceProjects,
+ taskId,
+ taskNumber,
+ title: task?.title,
+ }),
+ ),
);
toast.message(t("tasks:properties.taskLinkCopied"));
};
diff --git a/apps/web/src/components/task/task-subtasks.tsx b/apps/web/src/components/task/task-subtasks.tsx
index 4d3019fe7..0413b5c51 100644
--- a/apps/web/src/components/task/task-subtasks.tsx
+++ b/apps/web/src/components/task/task-subtasks.tsx
@@ -378,6 +378,7 @@ export default function TaskSubtasks({
tasks={getTargetTasks(taskObj)}
projectId={subtask.task.projectId}
workspaceId={workspace?.id ?? workspaceId}
+ workspaceSlug={workspace?.slug}
isSelected={isSelected}
isFocused={focusedIndex === index}
isCompleted={subtask.task.isCompleted}
diff --git a/apps/web/src/fetchers/task/get-task-by-ticket-id.ts b/apps/web/src/fetchers/task/get-task-by-ticket-id.ts
new file mode 100644
index 000000000..c6c109c50
--- /dev/null
+++ b/apps/web/src/fetchers/task/get-task-by-ticket-id.ts
@@ -0,0 +1,17 @@
+import { client } from "@kaneo/libs";
+import { HttpError } from "@/lib/http-error";
+
+async function getTaskByTicketId(ticketId: string, workspaceSlug: string) {
+ const response = await client.task["by-ticket-id"][":ticketId"].$get({
+ param: { ticketId },
+ query: { workspaceSlug },
+ });
+
+ if (!response.ok) {
+ throw new HttpError(response.status, await response.text());
+ }
+
+ return response.json();
+}
+
+export default getTaskByTicketId;
diff --git a/apps/web/src/hooks/mutations/workspace/use-update-workspace.ts b/apps/web/src/hooks/mutations/workspace/use-update-workspace.ts
index fbbf59527..fc75733f3 100644
--- a/apps/web/src/hooks/mutations/workspace/use-update-workspace.ts
+++ b/apps/web/src/hooks/mutations/workspace/use-update-workspace.ts
@@ -1,6 +1,5 @@
import { useMutation } from "@tanstack/react-query";
import { authClient } from "@/lib/auth-client";
-import { createSlug } from "@/lib/utils/create-slug";
type UpdateWorkspaceRequest = {
workspaceId: string;
@@ -31,9 +30,6 @@ function useUpdateWorkspace() {
if (name !== undefined) {
updateData.name = name;
- if (slug === undefined) {
- updateData.slug = createSlug(name);
- }
}
if (slug !== undefined) {
diff --git a/apps/web/src/lib/task-link.ts b/apps/web/src/lib/task-link.ts
new file mode 100644
index 000000000..05562ebca
--- /dev/null
+++ b/apps/web/src/lib/task-link.ts
@@ -0,0 +1,71 @@
+import { createSlug } from "@/lib/utils/create-slug";
+import { isReservedWorkspaceSlug } from "@/lib/utils/create-workspace-slug";
+
+const MAX_TITLE_SLUG_LENGTH = 60;
+const MAX_LOOKUP_VALUE_LENGTH = 128;
+
+type TaskPathInput = {
+ workspaceId: string;
+ workspace?: { id: string; slug?: string | null } | null;
+ projectId: string;
+ workspaceProjects?: { id: string; slug: string }[];
+ taskId: string;
+ taskNumber?: number | null;
+ title?: string | null;
+};
+
+function isLinkSegment(value: string) {
+ return (
+ value.length <= MAX_LOOKUP_VALUE_LENGTH &&
+ /^[\p{L}\p{N}\p{M}._~-]+$/u.test(value)
+ );
+}
+
+function getUniqueProjectKey(
+ projects: { id: string; slug: string }[],
+ projectId: string,
+) {
+ const key = projects.find((project) => project.id === projectId)?.slug;
+ if (!key) return undefined;
+
+ const normalizedKey = key.normalize("NFKC").toLowerCase();
+ const sharesKey = projects.some(
+ (project) =>
+ project.id !== projectId &&
+ project.slug.normalize("NFKC").toLowerCase() === normalizedKey,
+ );
+ return sharesKey ? undefined : key;
+}
+
+export function getTaskPath({
+ workspaceId,
+ workspace,
+ projectId,
+ workspaceProjects = [],
+ taskId,
+ taskNumber,
+ title,
+}: TaskPathInput) {
+ const fullPath = `/dashboard/workspace/${workspaceId}/project/${projectId}/task/${taskId}`;
+ const workspaceSlug =
+ workspace?.id === workspaceId ? workspace.slug : undefined;
+ const projectKey = getUniqueProjectKey(workspaceProjects, projectId);
+ if (
+ !workspaceSlug ||
+ !projectKey ||
+ !taskNumber ||
+ !isLinkSegment(workspaceSlug) ||
+ isReservedWorkspaceSlug(workspaceSlug)
+ ) {
+ return fullPath;
+ }
+
+ const ticketId = `${projectKey}-${taskNumber}`;
+ if (!isLinkSegment(ticketId)) return fullPath;
+
+ const titleSlug = createSlug(title ?? "")
+ .slice(0, MAX_TITLE_SLUG_LENGTH)
+ .replace(/-+$/, "");
+
+ return `/${workspaceSlug}/task/${ticketId}${titleSlug ? `/${titleSlug}` : ""}`;
+}
diff --git a/apps/web/src/lib/utils/create-workspace-slug.ts b/apps/web/src/lib/utils/create-workspace-slug.ts
index 317704d93..5edf5a932 100644
--- a/apps/web/src/lib/utils/create-workspace-slug.ts
+++ b/apps/web/src/lib/utils/create-workspace-slug.ts
@@ -2,6 +2,29 @@ import { createSlug } from "./create-slug";
const RANDOM_SUFFIX_LENGTH = 12;
+const RESERVED_WORKSPACE_SLUGS = new Set([
+ ".",
+ "..",
+ ".well-known",
+ "api",
+ "assets",
+ "auth",
+ "dashboard",
+ "device",
+ "images",
+ "invitation",
+ "invitations",
+ "mcp",
+ "onboarding",
+ "profile-setup",
+ "public-project",
+ "test-error",
+]);
+
+export function isReservedWorkspaceSlug(slug: string): boolean {
+ return RESERVED_WORKSPACE_SLUGS.has(slug.toLowerCase());
+}
+
export function createWorkspaceBaseSlug(value: string): string {
return createSlug(value) || "workspace";
}
@@ -19,7 +42,10 @@ export function createUniqueWorkspaceSlug(
Array.from(existingSlugs, (slug) => slug?.toLowerCase()).filter(Boolean),
);
- if (!usedSlugs.has(baseSlug.toLowerCase())) {
+ if (
+ !usedSlugs.has(baseSlug.toLowerCase()) &&
+ !isReservedWorkspaceSlug(baseSlug)
+ ) {
return baseSlug;
}
diff --git a/apps/web/src/routeTree.gen.ts b/apps/web/src/routeTree.gen.ts
index 44f7535e1..4c35140ec 100644
--- a/apps/web/src/routeTree.gen.ts
+++ b/apps/web/src/routeTree.gen.ts
@@ -39,6 +39,7 @@ import { Route as LayoutAuthenticatedDashboardSettingsProjectsRouteImport } from
import { Route as LayoutAuthenticatedDashboardSettingsWorkspaceRouteImport } from './routes/_layout/_authenticated/dashboard/settings/workspace'
import { Route as LayoutAuthenticatedDashboardWorkspaceWorkspaceIdRouteImport } from './routes/_layout/_authenticated/dashboard/workspace/$workspaceId'
import { Route as LayoutAuthenticatedDashboardWorkspaceCreateRouteImport } from './routes/_layout/_authenticated/dashboard/workspace/create'
+import { Route as LayoutAuthenticatedWorkspaceSlugTaskTicketIdChar123TitleChar125RouteImport } from './routes/_layout/_authenticated/$workspaceSlug/task.$ticketId.{-$title}'
import { Route as LayoutAuthenticatedDashboardSettingsAccountDeveloperRouteImport } from './routes/_layout/_authenticated/dashboard/settings/account/developer'
import { Route as LayoutAuthenticatedDashboardSettingsAccountInformationRouteImport } from './routes/_layout/_authenticated/dashboard/settings/account/information'
import { Route as LayoutAuthenticatedDashboardSettingsAccountNotificationsRouteImport } from './routes/_layout/_authenticated/dashboard/settings/account/notifications'
@@ -229,6 +230,14 @@ const LayoutAuthenticatedDashboardWorkspaceCreateRoute =
path: '/workspace/create',
getParentRoute: () => LayoutAuthenticatedDashboardRoute,
} as any)
+const LayoutAuthenticatedWorkspaceSlugTaskTicketIdChar123TitleChar125Route =
+ LayoutAuthenticatedWorkspaceSlugTaskTicketIdChar123TitleChar125RouteImport.update(
+ {
+ id: '/$workspaceSlug/task/$ticketId/{-$title}',
+ path: '/$workspaceSlug/task/$ticketId/{-$title}',
+ getParentRoute: () => LayoutAuthenticatedRoute,
+ } as any,
+ )
const LayoutAuthenticatedDashboardSettingsAccountDeveloperRoute =
LayoutAuthenticatedDashboardSettingsAccountDeveloperRouteImport.update({
id: '/developer',
@@ -449,6 +458,7 @@ export interface FileRoutesByFullPath {
'/dashboard/settings/workspace': typeof LayoutAuthenticatedDashboardSettingsWorkspaceRouteWithChildren
'/dashboard/workspace/$workspaceId': typeof LayoutAuthenticatedDashboardWorkspaceWorkspaceIdRouteWithChildren
'/dashboard/workspace/create': typeof LayoutAuthenticatedDashboardWorkspaceCreateRoute
+ '/$workspaceSlug/task/$ticketId/{-$title}': typeof LayoutAuthenticatedWorkspaceSlugTaskTicketIdChar123TitleChar125Route
'/dashboard/settings/account/developer': typeof LayoutAuthenticatedDashboardSettingsAccountDeveloperRoute
'/dashboard/settings/account/information': typeof LayoutAuthenticatedDashboardSettingsAccountInformationRoute
'/dashboard/settings/account/notifications': typeof LayoutAuthenticatedDashboardSettingsAccountNotificationsRoute
@@ -503,6 +513,7 @@ export interface FileRoutesByTo {
'/dashboard/settings/projects': typeof LayoutAuthenticatedDashboardSettingsProjectsRouteWithChildren
'/dashboard/settings/workspace': typeof LayoutAuthenticatedDashboardSettingsWorkspaceRouteWithChildren
'/dashboard/workspace/create': typeof LayoutAuthenticatedDashboardWorkspaceCreateRoute
+ '/$workspaceSlug/task/$ticketId/{-$title}': typeof LayoutAuthenticatedWorkspaceSlugTaskTicketIdChar123TitleChar125Route
'/dashboard/settings/account/developer': typeof LayoutAuthenticatedDashboardSettingsAccountDeveloperRoute
'/dashboard/settings/account/information': typeof LayoutAuthenticatedDashboardSettingsAccountInformationRoute
'/dashboard/settings/account/notifications': typeof LayoutAuthenticatedDashboardSettingsAccountNotificationsRoute
@@ -563,6 +574,7 @@ export interface FileRoutesById {
'/_layout/_authenticated/dashboard/settings/workspace': typeof LayoutAuthenticatedDashboardSettingsWorkspaceRouteWithChildren
'/_layout/_authenticated/dashboard/workspace/$workspaceId': typeof LayoutAuthenticatedDashboardWorkspaceWorkspaceIdRouteWithChildren
'/_layout/_authenticated/dashboard/workspace/create': typeof LayoutAuthenticatedDashboardWorkspaceCreateRoute
+ '/_layout/_authenticated/$workspaceSlug/task/$ticketId/{-$title}': typeof LayoutAuthenticatedWorkspaceSlugTaskTicketIdChar123TitleChar125Route
'/_layout/_authenticated/dashboard/settings/account/developer': typeof LayoutAuthenticatedDashboardSettingsAccountDeveloperRoute
'/_layout/_authenticated/dashboard/settings/account/information': typeof LayoutAuthenticatedDashboardSettingsAccountInformationRoute
'/_layout/_authenticated/dashboard/settings/account/notifications': typeof LayoutAuthenticatedDashboardSettingsAccountNotificationsRoute
@@ -622,6 +634,7 @@ export interface FileRouteTypes {
| '/dashboard/settings/workspace'
| '/dashboard/workspace/$workspaceId'
| '/dashboard/workspace/create'
+ | '/$workspaceSlug/task/$ticketId/{-$title}'
| '/dashboard/settings/account/developer'
| '/dashboard/settings/account/information'
| '/dashboard/settings/account/notifications'
@@ -676,6 +689,7 @@ export interface FileRouteTypes {
| '/dashboard/settings/projects'
| '/dashboard/settings/workspace'
| '/dashboard/workspace/create'
+ | '/$workspaceSlug/task/$ticketId/{-$title}'
| '/dashboard/settings/account/developer'
| '/dashboard/settings/account/information'
| '/dashboard/settings/account/notifications'
@@ -735,6 +749,7 @@ export interface FileRouteTypes {
| '/_layout/_authenticated/dashboard/settings/workspace'
| '/_layout/_authenticated/dashboard/workspace/$workspaceId'
| '/_layout/_authenticated/dashboard/workspace/create'
+ | '/_layout/_authenticated/$workspaceSlug/task/$ticketId/{-$title}'
| '/_layout/_authenticated/dashboard/settings/account/developer'
| '/_layout/_authenticated/dashboard/settings/account/information'
| '/_layout/_authenticated/dashboard/settings/account/notifications'
@@ -987,6 +1002,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof LayoutAuthenticatedDashboardWorkspaceCreateRouteImport
parentRoute: typeof LayoutAuthenticatedDashboardRoute
}
+ '/_layout/_authenticated/$workspaceSlug/task/$ticketId/{-$title}': {
+ id: '/_layout/_authenticated/$workspaceSlug/task/$ticketId/{-$title}'
+ path: '/$workspaceSlug/task/$ticketId/{-$title}'
+ fullPath: '/$workspaceSlug/task/$ticketId/{-$title}'
+ preLoaderRoute: typeof LayoutAuthenticatedWorkspaceSlugTaskTicketIdChar123TitleChar125RouteImport
+ parentRoute: typeof LayoutAuthenticatedRoute
+ }
'/_layout/_authenticated/dashboard/settings/account/developer': {
id: '/_layout/_authenticated/dashboard/settings/account/developer'
path: '/developer'
@@ -1376,6 +1398,7 @@ interface LayoutAuthenticatedRouteChildren {
LayoutAuthenticatedInvitationsRoute: typeof LayoutAuthenticatedInvitationsRoute
LayoutAuthenticatedOnboardingRoute: typeof LayoutAuthenticatedOnboardingRoute
LayoutAuthenticatedProfileSetupRoute: typeof LayoutAuthenticatedProfileSetupRoute
+ LayoutAuthenticatedWorkspaceSlugTaskTicketIdChar123TitleChar125Route: typeof LayoutAuthenticatedWorkspaceSlugTaskTicketIdChar123TitleChar125Route
}
const LayoutAuthenticatedRouteChildren: LayoutAuthenticatedRouteChildren = {
@@ -1384,6 +1407,8 @@ const LayoutAuthenticatedRouteChildren: LayoutAuthenticatedRouteChildren = {
LayoutAuthenticatedInvitationsRoute: LayoutAuthenticatedInvitationsRoute,
LayoutAuthenticatedOnboardingRoute: LayoutAuthenticatedOnboardingRoute,
LayoutAuthenticatedProfileSetupRoute: LayoutAuthenticatedProfileSetupRoute,
+ LayoutAuthenticatedWorkspaceSlugTaskTicketIdChar123TitleChar125Route:
+ LayoutAuthenticatedWorkspaceSlugTaskTicketIdChar123TitleChar125Route,
}
const LayoutAuthenticatedRouteWithChildren =
diff --git a/apps/web/src/routes/_layout/_authenticated/$workspaceSlug/task.$ticketId.{-$title}.tsx b/apps/web/src/routes/_layout/_authenticated/$workspaceSlug/task.$ticketId.{-$title}.tsx
new file mode 100644
index 000000000..a87451a64
--- /dev/null
+++ b/apps/web/src/routes/_layout/_authenticated/$workspaceSlug/task.$ticketId.{-$title}.tsx
@@ -0,0 +1,73 @@
+import { createFileRoute, Link, redirect } from "@tanstack/react-router";
+import { useTranslation } from "react-i18next";
+import PageTitle from "@/components/page-title";
+import { Button } from "@/components/ui/button";
+import getTaskByTicketId from "@/fetchers/task/get-task-by-ticket-id";
+import {
+ HttpError,
+ handleUnauthorized,
+ isUnauthorizedError,
+} from "@/lib/http-error";
+
+export const Route = createFileRoute(
+ "/_layout/_authenticated/$workspaceSlug/task/$ticketId/{-$title}",
+)({
+ loader: async ({ params }) => {
+ let task: Awaited<ReturnType<typeof getTaskByTicketId>>;
+ try {
+ task = await getTaskByTicketId(params.ticketId, params.workspaceSlug);
+ } catch (error) {
+ if (isUnauthorizedError(error)) {
+ handleUnauthorized();
+ return;
+ }
+ if (!(error instanceof HttpError)) throw error;
+ if (error.status === 409) return { failure: "ambiguous" as const };
+ if (error.status === 400 || error.status === 404) {
+ return { failure: "notFound" as const };
+ }
+ throw error;
+ }
+
+ throw redirect({
+ to: "/dashboard/workspace/$workspaceId/project/$projectId/task/$taskId",
+ params: {
+ workspaceId: task.workspaceId,
+ projectId: task.projectId,
+ taskId: task.id,
+ },
+ replace: true,
+ });
+ },
+ component: RouteComponent,
+});
+
+function RouteComponent() {
+ const { t } = useTranslation();
+ const { ticketId } = Route.useParams();
+ const result = Route.useLoaderData();
+
+ if (!result) return null;
+
+ const isAmbiguous = result.failure === "ambiguous";
+ const title = isAmbiguous
+ ? t("tasks:common.ticketAmbiguous")
+ : t("tasks:common.taskNotFound");
+
+ return (
+ <>
+ <PageTitle title={title} />
+ <div className="flex min-h-svh w-full flex-col items-center justify-center gap-4 bg-background px-4 py-12 text-center">
+ <h1 className="text-2xl font-bold">{title}</h1>
+ <p className="text-muted-foreground max-w-md">
+ {isAmbiguous
+ ? t("tasks:common.ticketAmbiguousDescription", { ticketId })
+ : t("tasks:common.ticketNotFoundDescription", { ticketId })}
+ </p>
+ <Button variant="outline" render={<Link to="/dashboard" />}>
+ {t("workspace:search.backToDashboard")}
+ </Button>
+ </div>
+ </>
+ );
+}
diff --git a/i18n/az-AZ.json b/i18n/az-AZ.json
index 7a9005df1..b076d01ba 100644
--- a/i18n/az-AZ.json
+++ b/i18n/az-AZ.json
@@ -2201,6 +2201,9 @@
"loadingTask": "Tapşırıq yüklənir...",
"taskNotFound": "Tapşırıq tapılmadı",
"taskNotFoundDescription": "Axtardığınız tapşırıq mövcud deyil və ya silinib.",
+ "ticketAmbiguous": "Tapşırıq ID-si birdən çox tapşırığa uyğun gəlir",
+ "ticketAmbiguousDescription": "{{ticketId}} bu iş sahəsində birdən çox layihədəki tapşırıqlara uyğun gəlir. Linki düzəltmək üçün həmin layihələrdən birinə fərqli açar verin.",
+ "ticketNotFoundDescription": "Bu iş sahəsində {{ticketId}} ID-li tapşırıq yoxdur və ya ona girişiniz yoxdur.",
"customFields": "Custom Fields"
},
"detail": {
diff --git a/i18n/de-DE.json b/i18n/de-DE.json
index cec3e49d2..186305577 100644
--- a/i18n/de-DE.json
+++ b/i18n/de-DE.json
@@ -2201,6 +2201,9 @@
"loadingTask": "Aufgabe wird geladen...",
"taskNotFound": "Aufgabe nicht gefunden",
"taskNotFoundDescription": "Die gesuchte Aufgabe existiert nicht oder wurde gelöscht.",
+ "ticketAmbiguous": "Aufgaben-ID passt zu mehreren Aufgaben",
+ "ticketAmbiguousDescription": "{{ticketId}} passt zu Aufgaben in mehreren Projekten dieses Workspaces. Gib einem dieser Projekte einen anderen Schlüssel, damit der Link funktioniert.",
+ "ticketNotFoundDescription": "In diesem Workspace gibt es keine Aufgabe mit der ID {{ticketId}}, oder du hast keinen Zugriff darauf.",
"customFields": "Custom Fields"
},
"detail": {
diff --git a/i18n/el-GR.json b/i18n/el-GR.json
index 93ea301d4..1bc2eac38 100644
--- a/i18n/el-GR.json
+++ b/i18n/el-GR.json
@@ -2201,6 +2201,9 @@
"loadingTask": "Φόρτωση εργασίας...",
"taskNotFound": "Η εργασία δεν βρέθηκε",
"taskNotFoundDescription": "Η εργασία που αναζητάτε δεν υπάρχει ή έχει διαγραφεί.",
+ "ticketAmbiguous": "Το αναγνωριστικό αντιστοιχεί σε περισσότερες από μία εργασίες",
+ "ticketAmbiguousDescription": "Το {{ticketId}} αντιστοιχεί σε εργασίες σε περισσότερα από ένα έργα αυτού του χώρου εργασίας. Δώστε σε ένα από αυτά τα έργα διαφορετικό κλειδί για να λειτουργήσει ο σύνδεσμος.",
+ "ticketNotFoundDescription": "Δεν υπάρχει εργασία με αναγνωριστικό {{ticketId}} σε αυτόν τον χώρο εργασίας ή δεν έχετε πρόσβαση σε αυτήν.",
"customFields": "Custom Fields"
},
"detail": {
diff --git a/i18n/en-US.json b/i18n/en-US.json
index a6ee95794..1929a5b91 100644
--- a/i18n/en-US.json
+++ b/i18n/en-US.json
@@ -2202,6 +2202,9 @@
"loadingTask": "Loading task...",
"taskNotFound": "Task not found",
"taskNotFoundDescription": "The task you are looking for does not exist or has been deleted.",
+ "ticketAmbiguous": "Task ID matches more than one task",
+ "ticketAmbiguousDescription": "{{ticketId}} matches tasks in more than one project in this workspace. Give one of those projects a different key to fix the link.",
+ "ticketNotFoundDescription": "No task with the ID {{ticketId}} exists in this workspace, or you don't have access to it.",
"customFields": "Custom Fields"
},
"detail": {
diff --git a/i18n/es-ES.json b/i18n/es-ES.json
index 2e55808b4..f236f3103 100644
--- a/i18n/es-ES.json
+++ b/i18n/es-ES.json
@@ -2212,6 +2212,9 @@
"loadingTask": "Cargando tarea...",
"taskNotFound": "Tarea no encontrada",
"taskNotFoundDescription": "La tarea que buscas no existe o ha sido eliminada.",
+ "ticketAmbiguous": "El ID coincide con más de una tarea",
+ "ticketAmbiguousDescription": "{{ticketId}} coincide con tareas de más de un proyecto en este espacio de trabajo. Asigna una clave diferente a uno de esos proyectos para que el enlace funcione.",
+ "ticketNotFoundDescription": "No existe ninguna tarea con el ID {{ticketId}} en este espacio de trabajo, o no tienes acceso a ella.",
"customFields": "Custom Fields"
},
"detail": {
diff --git a/i18n/fr-FR.json b/i18n/fr-FR.json
index 3c9033da0..a7d68f0db 100644
--- a/i18n/fr-FR.json
+++ b/i18n/fr-FR.json
@@ -2212,6 +2212,9 @@
"loadingTask": "Chargement de la tâche...",
"taskNotFound": "Tâche non trouvée",
"taskNotFoundDescription": "La tâche que vous recherchez n'existe pas ou a été supprimée.",
+ "ticketAmbiguous": "Cet identifiant correspond à plusieurs tâches",
+ "ticketAmbiguousDescription": "{{ticketId}} correspond à des tâches dans plusieurs projets de cet espace de travail. Attribuez une clé différente à l'un de ces projets pour que le lien fonctionne.",
+ "ticketNotFoundDescription": "Aucune tâche avec l'identifiant {{ticketId}} n'existe dans cet espace de travail, ou vous n'y avez pas accès.",
"customFields": "Custom Fields"
},
"detail": {
diff --git a/i18n/hi-IN.json b/i18n/hi-IN.json
index 338f739b1..772fcf18f 100644
--- a/i18n/hi-IN.json
+++ b/i18n/hi-IN.json
@@ -2201,6 +2201,9 @@
"loadingTask": "कार्य लोड हो रहा है...",
"taskNotFound": "कार्य नहीं मिला",
"taskNotFoundDescription": "जो कार्य आप खोज रहे हैं वह मौजूद नहीं है या हटा दिया गया है।",
+ "ticketAmbiguous": "यह कार्य ID एक से अधिक कार्यों से मेल खाती है",
+ "ticketAmbiguousDescription": "{{ticketId}} इस वर्कस्पेस के एक से अधिक प्रोजेक्ट के कार्यों से मेल खाती है। लिंक ठीक करने के लिए उनमें से किसी एक प्रोजेक्ट को अलग कुंजी दें।",
+ "ticketNotFoundDescription": "इस वर्कस्पेस में {{ticketId}} ID वाला कोई कार्य नहीं है, या आपके पास उसकी पहुँच नहीं है।",
"customFields": "Custom Fields"
},
"detail": {
diff --git a/i18n/id-ID.json b/i18n/id-ID.json
index 28fb2c541..1d38c0d23 100644
--- a/i18n/id-ID.json
+++ b/i18n/id-ID.json
@@ -2190,6 +2190,9 @@
"loadingTask": "Memuat tugas...",
"taskNotFound": "Tugas tidak ditemukan",
"taskNotFoundDescription": "Tugas yang Anda cari tidak ada atau telah dihapus.",
+ "ticketAmbiguous": "ID tugas cocok dengan lebih dari satu tugas",
+ "ticketAmbiguousDescription": "{{ticketId}} cocok dengan tugas di lebih dari satu proyek di ruang kerja ini. Berikan kunci yang berbeda ke salah satu proyek tersebut agar tautan berfungsi.",
+ "ticketNotFoundDescription": "Tidak ada tugas dengan ID {{ticketId}} di ruang kerja ini, atau Anda tidak memiliki akses ke tugas tersebut.",
"customFields": "Custom Fields"
},
"detail": {
diff --git a/i18n/it-IT.json b/i18n/it-IT.json
index bb58d1f6d..f8e559311 100644
--- a/i18n/it-IT.json
+++ b/i18n/it-IT.json
@@ -2212,6 +2212,9 @@
"loadingTask": "Caricamento attività...",
"taskNotFound": "Attività non trovata",
"taskNotFoundDescription": "L'attività che stai cercando non esiste o è stata eliminata.",
+ "ticketAmbiguous": "L'ID corrisponde a più attività",
+ "ticketAmbiguousDescription": "{{ticketId}} corrisponde ad attività in più progetti di questo workspace. Assegna una chiave diversa a uno di questi progetti per far funzionare il link.",
+ "ticketNotFoundDescription": "In questo workspace non esiste un'attività con ID {{ticketId}}, oppure non hai accesso a essa.",
"customFields": "Custom Fields"
},
"detail": {
diff --git a/i18n/ja-JP.json b/i18n/ja-JP.json
index 693a02aed..a988b0c49 100644
--- a/i18n/ja-JP.json
+++ b/i18n/ja-JP.json
@@ -2190,6 +2190,9 @@
"loadingTask": "タスクを読み込み中...",
"taskNotFound": "タスクが見つかりません",
"taskNotFoundDescription": "お探しのタスクは存在しないか、削除されました。",
+ "ticketAmbiguous": "このタスクIDは複数のタスクに一致します",
+ "ticketAmbiguousDescription": "{{ticketId}} はこのワークスペース内の複数のプロジェクトのタスクに一致します。リンクを機能させるには、いずれかのプロジェクトのキーを変更してください。",
+ "ticketNotFoundDescription": "このワークスペースに ID が {{ticketId}} のタスクが存在しないか、アクセス権がありません。",
"customFields": "Custom Fields"
},
"detail": {
diff --git a/i18n/ko-KR.json b/i18n/ko-KR.json
index d53973437..d991c2163 100644
--- a/i18n/ko-KR.json
+++ b/i18n/ko-KR.json
@@ -2190,6 +2190,9 @@
"loadingTask": "작업 로딩 중...",
"taskNotFound": "작업을 찾을 수 없음",
"taskNotFoundDescription": "찾는 작업이 존재하지 않거나 삭제되었습니다.",
+ "ticketAmbiguous": "작업 ID가 여러 작업과 일치합니다",
+ "ticketAmbiguousDescription": "{{ticketId}}이(가) 이 워크스페이스의 여러 프로젝트에 있는 작업과 일치합니다. 링크가 작동하도록 해당 프로젝트 중 하나의 키를 변경하세요.",
+ "ticketNotFoundDescription": "이 워크스페이스에 ID가 {{ticketId}}인 작업이 없거나 해당 작업에 대한 접근 권한이 없습니다.",
"customFields": "Custom Fields"
},
"detail": {
diff --git a/i18n/mk-MK.json b/i18n/mk-MK.json
index 1e1cefa29..f7c7051a1 100644
--- a/i18n/mk-MK.json
+++ b/i18n/mk-MK.json
@@ -2201,6 +2201,9 @@
"loadingTask": "Се вчитува задача...",
"taskNotFound": "Задачата не е пронајдена",
"taskNotFoundDescription": "Задачата што ја барате не постои или е избришана.",
+ "ticketAmbiguous": "ID-то на задачата одговара на повеќе задачи",
+ "ticketAmbiguousDescription": "{{ticketId}} одговара на задачи во повеќе проекти во овој работен простор. Доделете различен клуч на еден од тие проекти за врската да работи.",
+ "ticketNotFoundDescription": "Во овој работен простор не постои задача со ID {{ticketId}} или немате пристап до неа.",
"customFields": "Custom Fields"
},
"detail": {
diff --git a/i18n/nl-NL.json b/i18n/nl-NL.json
index 80f60345c..fa1d66559 100644
--- a/i18n/nl-NL.json
+++ b/i18n/nl-NL.json
@@ -2201,6 +2201,9 @@
"loadingTask": "Taak laden...",
"taskNotFound": "Taak niet gevonden",
"taskNotFoundDescription": "De taak die u zoekt bestaat niet of is verwijderd.",
+ "ticketAmbiguous": "Taak-ID komt overeen met meerdere taken",
+ "ticketAmbiguousDescription": "{{ticketId}} komt overeen met taken in meerdere projecten in deze werkruimte. Geef een van die projecten een andere sleutel om de link te laten werken.",
+ "ticketNotFoundDescription": "Er bestaat geen taak met de ID {{ticketId}} in deze werkruimte, of u hebt er geen toegang toe.",
"customFields": "Custom Fields"
},
"detail": {
diff --git a/i18n/pl-PL.json b/i18n/pl-PL.json
index 7140aa3da..f0c8be599 100644
--- a/i18n/pl-PL.json
+++ b/i18n/pl-PL.json
@@ -2541,6 +2541,9 @@
"selectTask": "Wybierz zadanie",
"taskNotFound": "Nie znaleziono zadania",
"taskNotFoundDescription": "Zadanie, którego szukasz, nie istnieje lub zostało usunięte.",
+ "ticketAmbiguous": "Identyfikator pasuje do więcej niż jednego zadania",
+ "ticketAmbiguousDescription": "{{ticketId}} pasuje do zadań w więcej niż jednym projekcie w tym obszarze roboczym. Nadaj jednemu z tych projektów inny klucz, aby link działał.",
+ "ticketNotFoundDescription": "W tym obszarze roboczym nie ma zadania o identyfikatorze {{ticketId}} lub nie masz do niego dostępu.",
"customFields": "Custom Fields"
},
"contextMenu": {
diff --git a/i18n/pt-BR.json b/i18n/pt-BR.json
index 009693f26..bf62bfb75 100644
--- a/i18n/pt-BR.json
+++ b/i18n/pt-BR.json
@@ -2212,6 +2212,9 @@
"loadingTask": "Carregando tarefa...",
"taskNotFound": "Tarefa não encontrada",
"taskNotFoundDescription": "A tarefa que você está procurando não existe ou foi excluída.",
+ "ticketAmbiguous": "O ID corresponde a mais de uma tarefa",
+ "ticketAmbiguousDescription": "{{ticketId}} corresponde a tarefas em mais de um projeto neste espaço de trabalho. Dê uma chave diferente a um desses projetos para que o link funcione.",
+ "ticketNotFoundDescription": "Nenhuma tarefa com o ID {{ticketId}} existe neste espaço de trabalho, ou você não tem acesso a ela.",
"customFields": "Custom Fields"
},
"detail": {
diff --git a/i18n/ru-RU.json b/i18n/ru-RU.json
index 43a44adaa..4785161d9 100644
--- a/i18n/ru-RU.json
+++ b/i18n/ru-RU.json
@@ -2231,6 +2231,9 @@
"loadingTask": "Загрузка задачи...",
"taskNotFound": "Задача не найдена",
"taskNotFoundDescription": "Задача, которую вы ищете, не существует или была удалена.",
+ "ticketAmbiguous": "Идентификатор соответствует нескольким задачам",
+ "ticketAmbiguousDescription": "{{ticketId}} соответствует задачам в нескольких проектах этой рабочей области. Задайте одному из этих проектов другой ключ, чтобы ссылка заработала.",
+ "ticketNotFoundDescription": "В этой рабочей области нет задачи с идентификатором {{ticketId}}, или у вас нет к ней доступа.",
"customFields": "Custom Fields"
},
"detail": {
diff --git a/i18n/schema.json b/i18n/schema.json
index d3370f103..51568624d 100644
--- a/i18n/schema.json
+++ b/i18n/schema.json
@@ -8900,6 +8900,15 @@
"taskNotFoundDescription": {
"type": "string"
},
+ "ticketAmbiguous": {
+ "type": "string"
+ },
+ "ticketAmbiguousDescription": {
+ "type": "string"
+ },
+ "ticketNotFoundDescription": {
+ "type": "string"
+ },
"customFields": {
"type": "string"
}
@@ -8909,6 +8918,9 @@
"loadingTask",
"taskNotFound",
"taskNotFoundDescription",
+ "ticketAmbiguous",
+ "ticketAmbiguousDescription",
+ "ticketNotFoundDescription",
"customFields"
]
},
diff --git a/i18n/tr-TR.json b/i18n/tr-TR.json
index dc9ed57c1..0b8beecfe 100644
--- a/i18n/tr-TR.json
+++ b/i18n/tr-TR.json
@@ -2201,6 +2201,9 @@
"loadingTask": "Talep yükleniyor...",
"taskNotFound": "Talep bulunamadı",
"taskNotFoundDescription": "Aradığınız talep mevcut değil veya silinmiş.",
+ "ticketAmbiguous": "Talep kimliği birden fazla talep ile eşleşiyor",
+ "ticketAmbiguousDescription": "{{ticketId}} bu çalışma alanındaki birden fazla projedeki taleplerle eşleşiyor. Bağlantının çalışması için bu projelerden birine farklı bir anahtar verin.",
+ "ticketNotFoundDescription": "Bu çalışma alanında {{ticketId}} kimliğine sahip bir talep yok veya bu talebe erişiminiz yok.",
"customFields": "Custom Fields"
},
"detail": {
diff --git a/i18n/uk-UA.json b/i18n/uk-UA.json
index a6f346cf1..7cd14d1c2 100644
--- a/i18n/uk-UA.json
+++ b/i18n/uk-UA.json
@@ -2223,6 +2223,9 @@
"loadingTask": "Завантаження завдання...",
"taskNotFound": "Завдання не знайдено",
"taskNotFoundDescription": "Завдання, яке ви шукаєте, не існує або було видалено.",
+ "ticketAmbiguous": "Ідентифікатор відповідає кільком завданням",
+ "ticketAmbiguousDescription": "{{ticketId}} відповідає завданням у кількох проєктах цього робочого простору. Призначте одному з цих проєктів інший ключ, щоб посилання працювало.",
+ "ticketNotFoundDescription": "У цьому робочому просторі немає завдання з ідентифікатором {{ticketId}}, або у вас немає до нього доступу.",
"customFields": "Custom Fields"
},
"detail": {
diff --git a/i18n/vi-VN.json b/i18n/vi-VN.json
index 2a0bd251b..e9cb2f0db 100644
--- a/i18n/vi-VN.json
+++ b/i18n/vi-VN.json
@@ -2190,6 +2190,9 @@
"loadingTask": "Đang tải công việc...",
"taskNotFound": "Không tìm thấy công việc",
"taskNotFoundDescription": "Công việc bạn đang tìm không tồn tại hoặc đã bị xóa.",
+ "ticketAmbiguous": "Mã công việc khớp với nhiều công việc",
+ "ticketAmbiguousDescription": "{{ticketId}} khớp với công việc trong nhiều dự án của không gian làm việc này. Hãy đặt khóa khác cho một trong các dự án đó để liên kết hoạt động.",
+ "ticketNotFoundDescription": "Không có công việc nào có mã {{ticketId}} trong không gian làm việc này, hoặc bạn không có quyền truy cập.",
"customFields": "Custom Fields"
},
"detail": {
diff --git a/i18n/zh-CN.json b/i18n/zh-CN.json
index 7a49a5154..82747fe63 100644
--- a/i18n/zh-CN.json
+++ b/i18n/zh-CN.json
@@ -2190,6 +2190,9 @@
"loadingTask": "正在加载任务…",
"taskNotFound": "未找到任务",
"taskNotFoundDescription": "你查找的任务不存在或已删除。",
+ "ticketAmbiguous": "该任务 ID 匹配多个任务",
+ "ticketAmbiguousDescription": "{{ticketId}} 匹配此工作区中多个项目的任务。请为其中一个项目设置不同的键,使链接正常工作。",
+ "ticketNotFoundDescription": "此工作区中不存在 ID 为 {{ticketId}} 的任务,或你无权访问该任务。",
"customFields": "Custom Fields"
},
"detail": {
diff --git a/tests/api-integration/project.test.ts b/tests/api-integration/project.test.ts
index d1d5f57ac..e392c4e80 100644
--- a/tests/api-integration/project.test.ts
+++ b/tests/api-integration/project.test.ts
@@ -1,10 +1,13 @@
-import { eq } from "drizzle-orm";
+import { eq, inArray } from "drizzle-orm";
import { beforeEach, describe, expect, it } from "vite-plus/test";
import db, { schema } from "../../apps/api/src/database";
import { createApp } from "../../apps/api/src/index";
import { mockAnonymousSession, mockAuthenticatedSession } from "./helpers/auth";
import { resetTestDatabase } from "./helpers/database";
-import { createWorkspaceMember } from "./helpers/fixtures";
+import {
+ createProjectFixture,
+ createWorkspaceMember,
+} from "./helpers/fixtures";
describe("API integration: project creation", () => {
beforeEach(async () => {
@@ -127,4 +130,120 @@ describe("API integration: project creation", () => {
"You don't have access to this workspace",
);
});
+
+ it("rejects a project key already used in the workspace", async () => {
+ const member = await createWorkspaceMember();
+ const other = await createWorkspaceMember();
+ await createProjectFixture({
+ workspaceId: member.workspace.id,
+ name: "Kanban",
+ slug: "KAN",
+ });
+ mockAuthenticatedSession(member.user);
+ const { app } = createApp();
+ const create = (workspaceId: string, slug: string) =>
+ app.request("/api/project", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ workspaceId,
+ name: "New",
+ icon: "Folder",
+ slug,
+ }),
+ });
+
+ const duplicate = await create(member.workspace.id, "kan");
+ expect(duplicate.status).toBe(409);
+ await expect(duplicate.text()).resolves.toContain('"kan" (Kanban)');
+ expect((await create(member.workspace.id, "KAN")).status).toBe(409);
+
+ mockAuthenticatedSession(other.user);
+ expect((await create(other.workspace.id, "KAN")).status).toBe(200);
+ });
+
+ it("rejects renaming a project to a key already used in the workspace", async () => {
+ const member = await createWorkspaceMember({ role: "admin" });
+ await createProjectFixture({
+ workspaceId: member.workspace.id,
+ name: "Kanban",
+ slug: "KAN",
+ });
+ const { project } = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ name: "Design",
+ slug: "DES",
+ });
+ const { project: twin } = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ name: "Design Twin",
+ slug: "des",
+ });
+ mockAuthenticatedSession(member.user);
+ const { app } = createApp();
+ const update = (id: string, name: string, slug: string) =>
+ app.request(`/api/project/${id}`, {
+ method: "PUT",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ name,
+ icon: "Folder",
+ slug,
+ description: "",
+ isPublic: false,
+ }),
+ });
+
+ expect((await update(twin.id, "Design Twin Renamed", "des")).status).toBe(
+ 200,
+ );
+ expect((await update(project.id, "Design", "KAN")).status).toBe(409);
+ expect((await update(project.id, "Design", "DSN")).status).toBe(200);
+ });
+
+ it("rejects unarchiving a project whose key another project uses", async () => {
+ const member = await createWorkspaceMember({ role: "admin" });
+ await createProjectFixture({
+ workspaceId: member.workspace.id,
+ name: "Kanban",
+ slug: "KAN",
+ });
+ const { project: archived } = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ slug: "kan",
+ });
+ const { project: archivedTwin } = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ slug: "OLD",
+ });
+ const { project: otherArchived } = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ slug: "old",
+ });
+ const { project: uniqueArchived } = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ slug: "NEW",
+ });
+ await db
+ .update(schema.projectTable)
+ .set({ archivedAt: new Date() })
+ .where(
+ inArray(schema.projectTable.id, [
+ archived.id,
+ archivedTwin.id,
+ otherArchived.id,
+ uniqueArchived.id,
+ ]),
+ );
+ mockAuthenticatedSession(member.user);
+ const { app } = createApp();
+ const unarchive = (id: string) =>
+ app.request(`/api/project/${id}/unarchive`, { method: "PUT" });
+
+ const conflict = await unarchive(archived.id);
+ expect(conflict.status).toBe(409);
+ await expect(conflict.text()).resolves.toContain("(Kanban)");
+ expect((await unarchive(archivedTwin.id)).status).toBe(409);
+ expect((await unarchive(uniqueArchived.id)).status).toBe(200);
+ });
});
diff --git a/tests/api-integration/task-ticket-id.test.ts b/tests/api-integration/task-ticket-id.test.ts
index c93657553..cbe907d30 100644
--- a/tests/api-integration/task-ticket-id.test.ts
+++ b/tests/api-integration/task-ticket-id.test.ts
@@ -1,3 +1,4 @@
+import { eq, inArray } from "drizzle-orm";
import { beforeEach, describe, expect, it } from "vite-plus/test";
import db, { schema } from "../../apps/api/src/database";
import { createApp } from "../../apps/api/src/index";
@@ -54,6 +55,7 @@ describe("API integration: task ticket ID lookup", () => {
description: "Full description",
assigneeName: member.user.name,
projectId: project.id,
+ workspaceId: member.workspace.id,
number: 23,
});
const missing = await app.request("/api/task/by-ticket-id/DE_-24");
@@ -62,6 +64,10 @@ describe("API integration: task ticket ID lookup", () => {
`/api/task/by-ticket-id/DE_-23?workspaceId=${outsider.workspace.id}`,
);
expect(privateSelection.status).toBe(404);
+ const privateSlug = await app.request(
+ `/api/task/by-ticket-id/DE_-23?workspaceSlug=${outsider.workspace.slug}`,
+ );
+ expect(privateSlug.status).toBe(404);
});
it("disambiguates accessible tasks by workspace or project", async () => {
@@ -110,7 +116,24 @@ describe("API integration: task ticket ID lookup", () => {
`/api/task/by-ticket-id/KAN-12?workspaceId=${other.workspace.id}`,
);
expect(selected.status).toBe(200);
- expect(await selected.json()).toMatchObject({ title: "Second" });
+ expect(await selected.json()).toMatchObject({
+ title: "Second",
+ workspaceId: other.workspace.id,
+ });
+
+ const bySlug = await app.request(
+ `/api/task/by-ticket-id/KAN-12?workspaceSlug=${other.workspace.slug}`,
+ );
+ expect(bySlug.status).toBe(200);
+ const byUpperSlug = await app.request(
+ `/api/task/by-ticket-id/KAN-12?workspaceSlug=${other.workspace.slug.toUpperCase()}`,
+ );
+ expect(byUpperSlug.status).toBe(200);
+ expect(await bySlug.json()).toMatchObject({ title: "Second" });
+ const unknownSlug = await app.request(
+ "/api/task/by-ticket-id/KAN-12?workspaceSlug=no-such-workspace",
+ );
+ expect(unknownSlug.status).toBe(404);
});
it("accepts a ticket ID generated from a numeric-leading project name", async () => {
@@ -132,6 +155,138 @@ describe("API integration: task ticket ID lookup", () => {
expect(await response.json()).toMatchObject({ title: "Numeric key" });
});
+ it("prefers an exact workspace slug over a case-insensitive match", async () => {
+ const member = await createWorkspaceMember();
+ const other = await createWorkspaceMember();
+ await db.insert(schema.workspaceUserTable).values({
+ workspaceId: other.workspace.id,
+ userId: member.user.id,
+ role: "member",
+ joinedAt: new Date(),
+ });
+ await db
+ .update(schema.workspaceTable)
+ .set({ slug: "case-ws" })
+ .where(eq(schema.workspaceTable.id, member.workspace.id));
+ await db
+ .update(schema.workspaceTable)
+ .set({ slug: "CASE-WS" })
+ .where(eq(schema.workspaceTable.id, other.workspace.id));
+ const lower = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ slug: "KAN",
+ });
+ const upper = await createProjectFixture({
+ workspaceId: other.workspace.id,
+ slug: "KAN",
+ });
+ await db.insert(schema.taskTable).values([
+ { projectId: lower.project.id, title: "Lower", number: 12 },
+ { projectId: upper.project.id, title: "Upper", number: 12 },
+ ]);
+
+ mockAuthenticatedSession(member.user);
+ const { app } = createApp();
+ const exactLower = await app.request(
+ "/api/task/by-ticket-id/KAN-12?workspaceSlug=case-ws",
+ );
+ expect(await exactLower.json()).toMatchObject({ title: "Lower" });
+ const exactUpper = await app.request(
+ "/api/task/by-ticket-id/KAN-12?workspaceSlug=CASE-WS",
+ );
+ expect(await exactUpper.json()).toMatchObject({ title: "Upper" });
+ const mixed = await app.request(
+ "/api/task/by-ticket-id/KAN-12?workspaceSlug=Case-Ws",
+ );
+ expect(mixed.status).toBe(409);
+ });
+
+ it("resolves a project key outside the generated key format", async () => {
+ const member = await createWorkspaceMember();
+ const { project } = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ slug: "OPS.2",
+ });
+ await db.insert(schema.taskTable).values({
+ projectId: project.id,
+ title: "Dotted key",
+ number: 12,
+ });
+
+ mockAuthenticatedSession(member.user);
+ const { app } = createApp();
+ const response = await app.request("/api/task/by-ticket-id/OPS.2-12");
+ expect(response.status).toBe(200);
+ expect(await response.json()).toMatchObject({ title: "Dotted key" });
+ });
+
+ it("resolves a full-width project key as stored", async () => {
+ const member = await createWorkspaceMember();
+ const { project } = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ slug: "ABC",
+ });
+ await db.insert(schema.taskTable).values({
+ projectId: project.id,
+ title: "Full-width key",
+ number: 1,
+ });
+
+ mockAuthenticatedSession(member.user);
+ const { app } = createApp();
+ const response = await app.request(
+ `/api/task/by-ticket-id/${encodeURIComponent("ABC-1")}`,
+ );
+ expect(response.status).toBe(200);
+ expect(await response.json()).toMatchObject({ title: "Full-width key" });
+ const normalized = await app.request("/api/task/by-ticket-id/abc-1");
+ expect(normalized.status).toBe(200);
+ expect(await normalized.json()).toMatchObject({ title: "Full-width key" });
+ });
+
+ it("prefers an active project over an archived one sharing its key", async () => {
+ const member = await createWorkspaceMember();
+ const { project: active } = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ slug: "ARC",
+ });
+ const { project: archived } = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ slug: "arc",
+ });
+ const { project: alsoArchived } = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ slug: "Arc",
+ });
+ await db
+ .update(schema.projectTable)
+ .set({ archivedAt: new Date() })
+ .where(inArray(schema.projectTable.id, [archived.id, alsoArchived.id]));
+ await db.insert(schema.taskTable).values([
+ { projectId: active.id, title: "Active", number: 5 },
+ { projectId: archived.id, title: "Archived", number: 5 },
+ { projectId: alsoArchived.id, title: "Also archived", number: 5 },
+ { projectId: archived.id, title: "Archived only", number: 6 },
+ { projectId: alsoArchived.id, title: "Also archived only", number: 6 },
+ ]);
+
+ mockAuthenticatedSession(member.user);
+ const { app } = createApp();
+ const preferred = await app.request("/api/task/by-ticket-id/ARC-5");
+ expect(preferred.status).toBe(200);
+ expect(await preferred.json()).toMatchObject({ title: "Active" });
+ const archivedOnly = await app.request("/api/task/by-ticket-id/ARC-6");
+ expect(archivedOnly.status).toBe(409);
+
+ await db
+ .update(schema.projectTable)
+ .set({ archivedAt: new Date(Date.now() + 60_000) })
+ .where(eq(schema.projectTable.id, active.id));
+ const afterArchiving = await app.request("/api/task/by-ticket-id/ARC-5");
+ expect(afterArchiving.status).toBe(200);
+ expect(await afterArchiving.json()).toMatchObject({ title: "Active" });
+ });
+
it("rejects invalid and unauthenticated lookups", async () => {
const member = await createWorkspaceMember();
mockAuthenticatedSession(member.user);
diff --git a/tests/api/plugins/github/utils/branch-matcher.test.ts b/tests/api/plugins/github/utils/branch-matcher.test.ts
index c08791f30..7311b8866 100644
--- a/tests/api/plugins/github/utils/branch-matcher.test.ts
+++ b/tests/api/plugins/github/utils/branch-matcher.test.ts
@@ -194,6 +194,77 @@ describe("extractTaskNumberFromPRBody", () => {
expect(unlinkedTaskNumber).toBeNull();
});
+ it.each([
+ "https://kaneo.example.com/acme/task/KAN-42",
+ "https://kaneo.example.com/acme/task/KAN-42/fix-kan-7-login",
+ "[Task](https://kaneo.example.com/acme/task/kan-42/fix-login)",
+ ])("recognizes the short task link %s", (body) => {
+ expect(extractTaskNumberFromPRBody(body, "KAN")).toBe(42);
+ });
+
+ it("ignores a workspace slug that looks like a ticket ID", () => {
+ expect(
+ extractTaskNumberFromPRBody(
+ "See https://kaneo.example.com/kan-42/task/OPS-5/fix-login",
+ "KAN",
+ ),
+ ).toBeNull();
+ expect(
+ extractTaskNumberFromPRBody(
+ "See https://kaneo.example.com/KAN-42/task/OPS-5.",
+ "KAN",
+ ),
+ ).toBeNull();
+ });
+
+ it("reads a short link that ends a sentence", () => {
+ expect(
+ extractTaskNumberFromPRBody(
+ "Fixes https://kaneo.example.com/acme/task/KAN-42.",
+ "KAN",
+ ),
+ ).toBe(42);
+ });
+
+ it("ignores the project key in another project's link title", () => {
+ expect(
+ extractTaskNumberFromPRBody(
+ "See https://kaneo.example.com/acme/task/OPS-5/kan-7-follow-up",
+ "KAN",
+ ),
+ ).toBeNull();
+ });
+
+ it("does not join text around a link into a task marker", () => {
+ expect(
+ extractTaskNumberFromPRBody("Task https://example.com 123", "KAN"),
+ ).toBeNull();
+ });
+
+ it("ignores task markers inside another project's link", () => {
+ expect(
+ extractTaskNumberFromPRBody(
+ "See https://kaneo.example.com/acme/task/OPS-5/fix-task-3-sorting",
+ "KAN",
+ ),
+ ).toBeNull();
+ expect(
+ extractTaskNumberFromPRBody(
+ "task: 7, see https://kaneo.example.com/acme/task/OPS-5/fix-task-3",
+ "KAN",
+ ),
+ ).toBe(7);
+ });
+
+ it("recognizes a short task link with a non-Latin project key", () => {
+ expect(
+ extractTaskNumberFromPRBody(
+ "https://kaneo.example.com/acme/task/ПРО-42/fix-login",
+ "ПРО",
+ ),
+ ).toBe(42);
+ });
+
it.each([
"Closes #61",
"Fixes #61",