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(api,web): duplicate a task from the card context menu (#1609)

Tristan BRINGUIER19778b707e72
diff --git a/apps/api/src/mcp/tools.ts b/apps/api/src/mcp/tools.ts
index 6fd6889b5..108a95d9b 100644
--- a/apps/api/src/mcp/tools.ts
+++ b/apps/api/src/mcp/tools.ts
@@ -453,6 +453,28 @@ export function registerMcpTools(
},
);
+ registerTool(
+ "duplicate_task",
+ {
+ description:
+ "Duplicate a task in the same project, copying its fields and labels. Pass title to rename the copy.",
+ inputSchema: z.object({
+ taskId: nonEmptyString,
+ title: optionalNonEmptyString,
+ }),
+ },
+ async (args) => {
+ const body: Record<string, string> = {};
+ if (args.title !== undefined) body.title = args.title;
+ return run(() =>
+ client.json(`/api/task/duplicate/${encodeURIComponent(args.taskId)}`, {
+ method: "POST",
+ body: JSON.stringify(body),
+ }),
+ );
+ },
+ );
+
registerTool(
"update_task",
{
diff --git a/apps/api/src/storage/s3.ts b/apps/api/src/storage/s3.ts
index fc33e61ec..f3a451b9e 100644
--- a/apps/api/src/storage/s3.ts
+++ b/apps/api/src/storage/s3.ts
@@ -1,5 +1,6 @@
import { Readable } from "node:stream";
import {
+ CopyObjectCommand,
DeleteObjectCommand,
GetObjectCommand,
HeadObjectCommand,
@@ -431,6 +432,30 @@ export async function getPrivateObject(key: string): Promise<AssetObject> {
};
}
+export async function copyTaskAssetObject({
+ sourceKey,
+ destination,
+}: {
+ sourceKey: string;
+ destination: TaskImageUploadContext;
+}): Promise<string> {
+ const config = getStorageConfig();
+ const client = getClient(config);
+ const key = applyKeyPrefix(config.keyPrefix, buildObjectKey(destination));
+
+ await client.send(
+ new CopyObjectCommand({
+ Bucket: config.bucket,
+ CopySource: [config.bucket, ...sourceKey.split("/")]
+ .map(encodeURIComponent)
+ .join("/"),
+ Key: key,
+ }),
+ );
+
+ return key;
+}
+
export async function deleteS3Object(key: string): Promise<void> {
const config = getStorageConfig();
const client = getClient(config);
diff --git a/apps/api/src/task/controllers/duplicate-task.ts b/apps/api/src/task/controllers/duplicate-task.ts
new file mode 100644
index 000000000..7ed63f24a
--- /dev/null
+++ b/apps/api/src/task/controllers/duplicate-task.ts
@@ -0,0 +1,362 @@
+import { createId } from "@paralleldrive/cuid2";
+import { and, eq } from "drizzle-orm";
+import { HTTPException } from "hono/http-exception";
+import db from "../../database";
+import {
+ assetTable,
+ columnTable,
+ customFieldDefinitionTable,
+ customFieldValueTable,
+ labelTable,
+ projectTable,
+ taskRelationTable,
+ taskTable,
+ userTable,
+} from "../../database/schema";
+import { publishEvent } from "../../events";
+import { contentReferencesAsset } from "../../storage/cleanup-assets";
+import { copyTaskAssetObject, deleteS3Object } from "../../storage/s3";
+import { assertAssignableUser } from "../../utils/assert-assignable-user";
+import {
+ assertRequiredCustomFields,
+ assertValidTaskStatus,
+} from "../validate-task-fields";
+import { claimTaskNumber } from "./claim-task-numbers";
+import { nextTaskPosition } from "./next-task-position";
+
+async function discardCopiedObjects(objectKeys: string[]) {
+ await Promise.all(
+ objectKeys.map((objectKey) =>
+ deleteS3Object(objectKey).catch((error) => {
+ console.error("Failed to discard a duplicated task asset:", error);
+ }),
+ ),
+ );
+}
+
+// Assets are addressed by `/api/asset/<id>` inside the description, so the copy
+// needs its own asset rows and stored objects. Sharing the source rows is not an
+// option: `asset.objectKey` is unique and deleting the source task cascades to them.
+async function duplicateDescriptionAssets({
+ sourceTask,
+ duplicatedTaskId,
+ workspaceId,
+}: {
+ sourceTask: typeof taskTable.$inferSelect;
+ duplicatedTaskId: string;
+ workspaceId: string;
+}) {
+ const description = sourceTask.description;
+
+ if (!description) {
+ return { assets: [], description };
+ }
+
+ const sourceAssets = await db
+ .select()
+ .from(assetTable)
+ .where(
+ and(
+ eq(assetTable.taskId, sourceTask.id),
+ eq(assetTable.projectId, sourceTask.projectId),
+ eq(assetTable.workspaceId, workspaceId),
+ ),
+ );
+
+ const referencedAssets = sourceAssets.filter((asset) =>
+ contentReferencesAsset(description, asset.id),
+ );
+
+ const assets: (typeof assetTable.$inferInsert)[] = [];
+ let duplicatedDescription = description;
+
+ try {
+ for (const asset of referencedAssets) {
+ const duplicatedAssetId = createId();
+ const objectKey = await copyTaskAssetObject({
+ sourceKey: asset.objectKey,
+ destination: {
+ workspaceId,
+ projectId: sourceTask.projectId,
+ taskId: duplicatedTaskId,
+ surface: asset.surface === "comment" ? "comment" : "description",
+ filename: asset.filename,
+ contentType: asset.mimeType,
+ },
+ });
+
+ assets.push({
+ id: duplicatedAssetId,
+ workspaceId,
+ projectId: sourceTask.projectId,
+ taskId: duplicatedTaskId,
+ objectKey,
+ filename: asset.filename,
+ mimeType: asset.mimeType,
+ size: asset.size,
+ kind: asset.kind,
+ surface: asset.surface,
+ createdBy: asset.createdBy,
+ });
+
+ duplicatedDescription = duplicatedDescription.replaceAll(
+ `/api/asset/${asset.id}`,
+ `/api/asset/${duplicatedAssetId}`,
+ );
+ }
+ } catch (error) {
+ await discardCopiedObjects(assets.map((asset) => asset.objectKey));
+
+ console.error("Failed to copy task attachments:", error);
+ throw new HTTPException(503, {
+ message: "Failed to copy the task attachments",
+ });
+ }
+
+ return { assets, description: duplicatedDescription };
+}
+
+async function duplicateTask({
+ taskId,
+ currentUserId,
+ title,
+}: {
+ taskId: string;
+ currentUserId: string;
+ title?: string;
+}) {
+ const sourceTask = await db.query.taskTable.findFirst({
+ where: eq(taskTable.id, taskId),
+ });
+
+ if (!sourceTask) {
+ throw new HTTPException(404, {
+ message: "Task not found",
+ });
+ }
+
+ const [project] = await db
+ .select({ workspaceId: projectTable.workspaceId })
+ .from(projectTable)
+ .where(eq(projectTable.id, sourceTask.projectId))
+ .limit(1);
+
+ if (!project) {
+ throw new HTTPException(404, {
+ message: "Project not found",
+ });
+ }
+
+ await assertValidTaskStatus(sourceTask.status, sourceTask.projectId);
+ if (sourceTask.userId)
+ await assertAssignableUser(sourceTask.userId, project.workspaceId);
+ const column = await db.query.columnTable.findFirst({
+ where: and(
+ eq(columnTable.projectId, sourceTask.projectId),
+ eq(columnTable.slug, sourceTask.status),
+ ),
+ });
+
+ const fieldDefinitions = await db
+ .select()
+ .from(customFieldDefinitionTable)
+ .where(eq(customFieldDefinitionTable.projectId, sourceTask.projectId));
+ const sourceCustomFields = await db
+ .select({
+ fieldId: customFieldValueTable.fieldId,
+ value: customFieldValueTable.value,
+ })
+ .from(customFieldValueTable)
+ .innerJoin(
+ customFieldDefinitionTable,
+ eq(customFieldValueTable.fieldId, customFieldDefinitionTable.id),
+ )
+ .where(
+ and(
+ eq(customFieldValueTable.taskId, sourceTask.id),
+ eq(customFieldDefinitionTable.projectId, sourceTask.projectId),
+ ),
+ );
+ const customFields = sourceCustomFields.map(({ fieldId, value }) => ({
+ fieldId,
+ value: value ?? "",
+ }));
+ // Older tasks may predate a required field. Apply its current default or fail
+ // validation, just as creation does, before copying anything in storage.
+ for (const definition of fieldDefinitions) {
+ if (!definition.required || !definition.defaultValue?.trim()) continue;
+ const existing = customFields.find(
+ (field) => field.fieldId === definition.id,
+ );
+ if (!existing)
+ customFields.push({
+ fieldId: definition.id,
+ value: definition.defaultValue.trim(),
+ });
+ else if (!existing.value.trim())
+ existing.value = definition.defaultValue.trim();
+ }
+ await assertRequiredCustomFields(sourceTask.projectId, customFields);
+
+ const sourceLabels = await db
+ .select({
+ name: labelTable.name,
+ color: labelTable.color,
+ workspaceId: labelTable.workspaceId,
+ })
+ .from(labelTable)
+ .where(
+ and(
+ eq(labelTable.taskId, sourceTask.id),
+ eq(labelTable.workspaceId, project.workspaceId),
+ ),
+ );
+
+ // A duplicated subtask stays a subtask of the same parents. The source's own
+ // subtasks are not duplicated: a copy is one task, not a tree.
+ const parentRelations = await db
+ .select({
+ parentTaskId: taskRelationTable.sourceTaskId,
+ parentProjectId: taskTable.projectId,
+ relationType: taskRelationTable.relationType,
+ })
+ .from(taskRelationTable)
+ .innerJoin(taskTable, eq(taskRelationTable.sourceTaskId, taskTable.id))
+ .innerJoin(projectTable, eq(taskTable.projectId, projectTable.id))
+ .where(
+ and(
+ eq(taskRelationTable.targetTaskId, sourceTask.id),
+ eq(projectTable.workspaceId, project.workspaceId),
+ eq(taskRelationTable.relationType, "subtask"),
+ ),
+ );
+
+ // The destination object keys embed the new task id, so it is generated up front
+ // instead of being left to the insert.
+ const duplicatedTaskId = createId();
+
+ const { assets, description } = await duplicateDescriptionAssets({
+ sourceTask,
+ duplicatedTaskId,
+ workspaceId: project.workspaceId,
+ });
+
+ let duplicated: {
+ task: typeof taskTable.$inferSelect;
+ relations: (typeof taskRelationTable.$inferSelect)[];
+ };
+
+ try {
+ duplicated = await db.transaction(async (tx) => {
+ const taskNumber = await claimTaskNumber(sourceTask.projectId, tx);
+ const nextPosition = await nextTaskPosition(
+ tx,
+ sourceTask.projectId,
+ sourceTask.status,
+ column?.id ?? null,
+ );
+
+ const [task] = await tx
+ .insert(taskTable)
+ .values({
+ id: duplicatedTaskId,
+ projectId: sourceTask.projectId,
+ userId: sourceTask.userId,
+ title: title?.trim() || sourceTask.title,
+ status: sourceTask.status,
+ columnId: column?.id ?? null,
+ startDate: sourceTask.startDate,
+ dueDate: sourceTask.dueDate,
+ description,
+ priority: sourceTask.priority,
+ number: taskNumber,
+ position: nextPosition,
+ })
+ .returning();
+
+ if (!task) {
+ throw new HTTPException(500, {
+ message: "Failed to duplicate task",
+ });
+ }
+
+ if (customFields.length > 0) {
+ await tx
+ .insert(customFieldValueTable)
+ .values(customFields.map((field) => ({ ...field, taskId: task.id })));
+ }
+
+ if (sourceLabels.length > 0) {
+ await tx.insert(labelTable).values(
+ sourceLabels.map((label) => ({
+ name: label.name,
+ color: label.color,
+ taskId: task.id,
+ workspaceId: label.workspaceId,
+ })),
+ );
+ }
+
+ if (assets.length > 0) {
+ await tx.insert(assetTable).values(assets);
+ }
+
+ const relations =
+ parentRelations.length > 0
+ ? await tx
+ .insert(taskRelationTable)
+ .values(
+ parentRelations.map((relation) => ({
+ sourceTaskId: relation.parentTaskId,
+ targetTaskId: task.id,
+ relationType: relation.relationType,
+ })),
+ )
+ .returning()
+ : [];
+
+ return { task, relations };
+ });
+ } catch (error) {
+ await discardCopiedObjects(assets.map((asset) => asset.objectKey));
+ throw error;
+ }
+
+ const duplicatedTask = duplicated.task;
+
+ const [assignee] = duplicatedTask.userId
+ ? await db
+ .select({ name: userTable.name })
+ .from(userTable)
+ .where(eq(userTable.id, duplicatedTask.userId))
+ : [];
+
+ await publishEvent("task.created", {
+ ...duplicatedTask,
+ taskId: duplicatedTask.id,
+ userId: duplicatedTask.userId ?? "",
+ currentUserId,
+ type: "created",
+ content: null,
+ });
+
+ for (const relation of duplicated.relations) {
+ const parentProjectId = parentRelations.find(
+ (parentRelation) => parentRelation.parentTaskId === relation.sourceTaskId,
+ )?.parentProjectId;
+
+ await publishEvent("task-relation.created", {
+ ...relation,
+ taskId: relation.sourceTaskId,
+ projectId: parentProjectId ?? sourceTask.projectId,
+ userId: currentUserId,
+ });
+ }
+
+ return {
+ ...duplicatedTask,
+ assigneeName: assignee?.name,
+ };
+}
+
+export default duplicateTask;
diff --git a/apps/api/src/task/index.ts b/apps/api/src/task/index.ts
index 29f89ec08..20cc805ab 100644
--- a/apps/api/src/task/index.ts
+++ b/apps/api/src/task/index.ts
@@ -33,6 +33,7 @@ import { workspaceAccess } from "../utils/workspace-access-middleware";
import bulkUpdateTasks from "./controllers/bulk-update-tasks";
import createTask from "./controllers/create-task";
import deleteTask from "./controllers/delete-task";
+import duplicateTask from "./controllers/duplicate-task";
import exportTasks from "./controllers/export-tasks";
import getTask from "./controllers/get-task";
import getTasks from "./controllers/get-tasks";
@@ -72,6 +73,7 @@ import {
createTaskBody,
descriptionMatchesQuery,
descriptionPageQuery,
+ duplicateTaskBody,
finalizeImageUploadBody,
imageUploadBody,
importTasksBody,
@@ -168,6 +170,37 @@ const createTaskRoute = createRoute({
},
});
+const duplicateTaskRoute = createRoute({
+ method: "post",
+ path: "/duplicate/{id}",
+ operationId: "duplicateTask",
+ tags: ["Tasks"],
+ summary: "Duplicate a task",
+ description:
+ "Copy a task into the same project and column, including custom fields, labels, description assets and same-workspace parent links. Comments, time entries and child tasks are not copied.",
+ middleware: [
+ workspaceAccess.fromTask(),
+ requireWorkspacePermission({ task: ["create"] }),
+ requireEntitlement,
+ ] as const,
+ request: {
+ params: taskParam,
+ body: {
+ required: true,
+ content: { "application/json": { schema: duplicateTaskBody } },
+ },
+ },
+ responses: {
+ 200: jsonResponse("The duplicated task", taskSchema),
+ 400: errorResponse("Invalid task fields or request"),
+ 401: errorResponse("Unauthorized"),
+ 403: errorResponse("No workspace access or task:create permission"),
+ 404: errorResponse("Task or project not found"),
+ 409: errorResponse("Task column has reached its capacity"),
+ 503: errorResponse("Unable to copy task attachments"),
+ },
+});
+
const getTaskRoute = createRoute({
method: "get",
operationId: "getTask",
@@ -679,6 +712,18 @@ const task = apiRouter<BaseVariables & { workspaceId: string }>()
return c.json(task, 200);
})
+ .openapi(duplicateTaskRoute, async (c) => {
+ const { id } = c.req.valid("param");
+ const { title } = c.req.valid("json");
+ return c.json(
+ await duplicateTask({
+ taskId: id,
+ title,
+ currentUserId: c.get("userId"),
+ }),
+ 200,
+ );
+ })
.openapi(getTaskRoute, async (c) => {
const { id } = c.req.valid("param");
diff --git a/apps/api/src/task/schema.ts b/apps/api/src/task/schema.ts
index 5d290e58a..654ad808d 100644
--- a/apps/api/src/task/schema.ts
+++ b/apps/api/src/task/schema.ts
@@ -139,3 +139,5 @@ export const descriptionMatchesQuery = z.object({
query: z.string().trim().min(1).max(256),
after: z.string().min(1).max(128).optional(),
});
+
+export const duplicateTaskBody = z.object({ title: z.string().optional() });
diff --git a/apps/docs/core/integrations/mcp.mdx b/apps/docs/core/integrations/mcp.mdx
index 1344cb44b..e259d07b3 100644
--- a/apps/docs/core/integrations/mcp.mdx
+++ b/apps/docs/core/integrations/mcp.mdx
@@ -128,7 +128,7 @@ Both the HTTP endpoint and stdio package expose the same tools:
- Session: `whoami`, `list_workspaces`, `list_workspace_members`, `list_notifications`
- Search: `search`
- Projects: `list_projects`, `get_project`, `create_project`, `update_project`, `list_project_columns`
-- Tasks: `list_tasks`, `get_task`, `create_task`, `update_task`, `delete_task`, `move_task`, `update_task_status`, `update_task_assignee`, `update_task_due_date`, `list_task_activity`
+- Tasks: `list_tasks`, `get_task`, `create_task`, `duplicate_task`, `update_task`, `delete_task`, `move_task`, `update_task_status`, `update_task_assignee`, `update_task_due_date`, `list_task_activity`
- Time entries: `list_task_time_entries`, `get_time_entry`, `create_time_entry`, `update_time_entry`
- Comments: `list_task_comments`, `create_task_comment`
- Labels: `list_workspace_labels`, `create_label`, `attach_label_to_task`, `detach_label_from_task`, `delete_label`
diff --git a/apps/docs/openapi.json b/apps/docs/openapi.json
index d104d3019..fe60d4328 100644
--- a/apps/docs/openapi.json
+++ b/apps/docs/openapi.json
@@ -7474,6 +7474,113 @@
}
}
},
+ "/task/duplicate/{id}": {
+ "post": {
+ "operationId": "duplicateTask",
+ "tags": [
+ "Tasks"
+ ],
+ "summary": "Duplicate a task",
+ "description": "Copy a task into the same project and column, including custom fields, labels, description assets and same-workspace parent links. Comments, time entries and child tasks are not copied.",
+ "parameters": [
+ {
+ "schema": {
+ "type": "string"
+ },
+ "required": true,
+ "name": "id",
+ "in": "path"
+ }
+ ],
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object",
+ "properties": {
+ "title": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "The duplicated task",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Task"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid task fields or request",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "Unauthorized",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "No workspace access or task:create permission",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "Task or project not found",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "409": {
+ "description": "Task column has reached its capacity",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "503": {
+ "description": "Unable to copy task attachments",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/task/{id}": {
"get": {
"operationId": "getTask",
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 ed1230e5b..8485053ab 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
@@ -1,9 +1,16 @@
-import { cleanup, render, screen } from "@testing-library/react";
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import type Task from "@/types/task";
import TaskCardContextMenuContent from "./task-card-context-menu-content";
+const duplicateTask = vi.fn();
+const canCreateTasks = vi.fn(() => true);
+vi.mock("@/hooks/mutations/task/use-duplicate-task", () => ({
+ useDuplicateTask: () => ({ mutate: duplicateTask }),
+}));
+
afterEach(() => {
+ canCreateTasks.mockReturnValue(true);
cleanup();
vi.clearAllMocks();
});
@@ -16,9 +23,15 @@ vi.mock("@/components/ui/context-menu", () => ({
}): React.JSX.Element => <div>{children}</div>,
ContextMenuItem: ({
children,
+ onClick,
}: {
children: React.ReactNode;
- }): React.JSX.Element => <div>{children}</div>,
+ onClick?: () => void;
+ }): React.JSX.Element => (
+ <button type="button" onClick={onClick}>
+ {children}
+ </button>
+ ),
ContextMenuSeparator: (): React.JSX.Element => <div />,
ContextMenuSub: ({
children,
@@ -87,6 +100,7 @@ vi.mock("@/hooks/mutations/task/use-update-task-title", () => ({
vi.mock("@/hooks/use-workspace-permission", () => ({
useWorkspacePermission: () => ({
+ canCreateTasks,
canUpdateTasks: () => true,
canDeleteTasks: () => true,
canAssignTasks: () => true,
@@ -103,7 +117,8 @@ vi.mock("@/store/project", () => ({
vi.mock("react-i18next", () => ({
useTranslation: () => ({
- t: (key: string) => key,
+ t: (key: string, options?: { title?: string }) =>
+ options?.title ? `${key}|${options.title}` : key,
}),
}));
@@ -157,3 +172,19 @@ describe("TaskCardContextMenuContent", () => {
expect(screen.getByText("tasks:actions.markAsPlanned")).toBeInTheDocument();
});
});
+
+it("duplicates using the localized title suffix", () => {
+ renderTask(task);
+ fireEvent.click(
+ screen.getByRole("button", { name: "tasks:actions.duplicate" }),
+ );
+ expect(duplicateTask).toHaveBeenCalledWith({
+ taskId: task.id,
+ title: `tasks:duplicate.titleSuffix|${task.title}`,
+ });
+});
+it("hides duplication without task-create permission", () => {
+ canCreateTasks.mockReturnValue(false);
+ renderTask(task);
+ expect(screen.queryByText("tasks:actions.duplicate")).toBeNull();
+});
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 cc9acd8bc..f24165a66 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
@@ -12,6 +12,7 @@ import {
ContextMenuSubContent,
ContextMenuSubTrigger,
} from "@/components/ui/context-menu";
+import { useDuplicateTask } from "@/hooks/mutations/task/use-duplicate-task";
import { useUpdateTask } from "@/hooks/mutations/task/use-update-task";
import { useUpdateTaskAssignee } from "@/hooks/mutations/task/use-update-task-assignee";
import { useUpdateTaskDescription } from "@/hooks/mutations/task/use-update-task-description";
@@ -74,8 +75,10 @@ export default function TaskCardContextMenuContent({
const { mutateAsync: updateTaskTitle } = useUpdateTaskTitle();
const { mutateAsync: updateTaskDescription } = useUpdateTaskDescription();
const { mutateAsync: updateTaskDueDate } = useUpdateTaskDueDate();
- const { canUpdateTasks, canDeleteTasks, canAssignTasks } =
+ const { mutate: duplicateTask } = useDuplicateTask();
+ const { canCreateTasks, canUpdateTasks, canDeleteTasks, canAssignTasks } =
useWorkspacePermission();
+ const canCreate = canCreateTasks();
const canEdit = canUpdateTasks();
const canDelete = canDeleteTasks();
const canAssign = canAssignTasks();
@@ -97,6 +100,13 @@ export default function TaskCardContextMenuContent({
toast.success(t("tasks:contextMenu.copyLinkSuccess"));
};
+ const handleDuplicateTask = () => {
+ duplicateTask({
+ taskId: task.id,
+ title: t("tasks:duplicate.titleSuffix", { title: task.title }),
+ });
+ };
+
const handleChange = async (field: keyof Task, value: string | Date) => {
try {
switch (field) {
@@ -295,25 +305,34 @@ export default function TaskCardContextMenuContent({
</ContextMenuSub>
)}
- {(canEdit || canDelete) && (
+ {(canCreate || canEdit || canDelete) && (
<>
- {canEdit && (
+ {(canCreate || canEdit) && (
<>
<ContextMenuSeparator />
- <ContextMenuItem
- onClick={() => handleChange("status", "archived")}
- >
- <span>{t("tasks:actions.archive")}</span>
- </ContextMenuItem>
-
- {task.status !== "planned" && (
- <ContextMenuItem
- onClick={() => handleChange("status", "planned")}
- >
- <span>{t("tasks:actions.markAsPlanned")}</span>
+ {canCreate && (
+ <ContextMenuItem onClick={handleDuplicateTask}>
+ <span>{t("tasks:actions.duplicate")}</span>
</ContextMenuItem>
)}
+
+ {canEdit && (
+ <>
+ <ContextMenuItem
+ onClick={() => handleChange("status", "archived")}
+ >
+ <span>{t("tasks:actions.archive")}</span>
+ </ContextMenuItem>
+ {task.status !== "planned" && (
+ <ContextMenuItem
+ onClick={() => handleChange("status", "planned")}
+ >
+ <span>{t("tasks:actions.markAsPlanned")}</span>
+ </ContextMenuItem>
+ )}
+ </>
+ )}
</>
)}
diff --git a/apps/web/src/fetchers/task/duplicate-task.ts b/apps/web/src/fetchers/task/duplicate-task.ts
new file mode 100644
index 000000000..20067035d
--- /dev/null
+++ b/apps/web/src/fetchers/task/duplicate-task.ts
@@ -0,0 +1,25 @@
+import { client } from "@kaneo/libs";
+
+async function duplicateTask({
+ taskId,
+ title,
+}: {
+ taskId: string;
+ title?: string;
+}) {
+ const response = await client.task.duplicate[":id"].$post({
+ param: { id: taskId },
+ json: { title },
+ });
+
+ if (!response.ok) {
+ const error = await response.text();
+ throw new Error(error);
+ }
+
+ const data = await response.json();
+
+ return data;
+}
+
+export default duplicateTask;
diff --git a/apps/web/src/hooks/mutations/task/use-duplicate-task.ts b/apps/web/src/hooks/mutations/task/use-duplicate-task.ts
new file mode 100644
index 000000000..b9c6af2d3
--- /dev/null
+++ b/apps/web/src/hooks/mutations/task/use-duplicate-task.ts
@@ -0,0 +1,29 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { useTranslation } from "react-i18next";
+import duplicateTask from "@/fetchers/task/duplicate-task";
+import { toast } from "@/lib/toast";
+
+export function useDuplicateTask() {
+ const { t } = useTranslation();
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: duplicateTask,
+ onSuccess: (task) => {
+ toast.success(t("tasks:duplicate.success"));
+ queryClient.invalidateQueries({
+ queryKey: ["tasks", task.projectId],
+ });
+ // Duplicating a subtask attaches the copy to the same parents, so any open
+ // relation list is stale even though the copy is not the task we know about.
+ queryClient.invalidateQueries({
+ queryKey: ["task-relations"],
+ });
+ },
+ onError: (error) => {
+ toast.error(
+ error instanceof Error ? error.message : t("tasks:duplicate.error"),
+ );
+ },
+ });
+}
diff --git a/i18n/az-AZ.json b/i18n/az-AZ.json
index bc0376c6a..9a2b50ed0 100644
--- a/i18n/az-AZ.json
+++ b/i18n/az-AZ.json
@@ -2255,7 +2255,8 @@
"actions": {
"archive": "Arxivlə",
"markAsPlanned": "Planlaşdırılmış kimi işarələ",
- "delete": "Sil..."
+ "delete": "Sil...",
+ "duplicate": "Duplicate"
},
"bulk": {
"selectedCount": "{{count}} seçilib",
@@ -2304,7 +2305,12 @@
"descriptionSearchError": "Description search failed. Results may be incomplete.",
"descriptionRetry": "Retry",
"descriptionLoading": "Loading description…",
- "descriptionLoadError": "The description could not be loaded. Retry to load the current version."
+ "descriptionLoadError": "The description could not be loaded. Retry to load the current version.",
+ "duplicate": {
+ "error": "Failed to duplicate task",
+ "success": "Task duplicated successfully",
+ "titleSuffix": "{{title}} (copy)"
+ }
},
"invitations": {
"email": {
diff --git a/i18n/de-DE.json b/i18n/de-DE.json
index 2acdbf946..32732bf01 100644
--- a/i18n/de-DE.json
+++ b/i18n/de-DE.json
@@ -2196,6 +2196,11 @@
"success": "Aufgabe erfolgreich gelöscht",
"error": "Aufgabe konnte nicht gelöscht werden"
},
+ "duplicate": {
+ "titleSuffix": "{{title}} (Kopie)",
+ "success": "Aufgabe erfolgreich dupliziert",
+ "error": "Aufgabe konnte nicht dupliziert werden"
+ },
"archive": {
"success": "{{count}} Aufgaben archiviert"
},
@@ -2240,6 +2245,7 @@
"copyLinkSuccess": "Aufgabenlink kopiert!"
},
"actions": {
+ "duplicate": "Duplizieren",
"archive": "Archivieren",
"markAsPlanned": "Als geplant markieren",
"delete": "Löschen..."
diff --git a/i18n/el-GR.json b/i18n/el-GR.json
index 1fd30f71f..be4b4d980 100644
--- a/i18n/el-GR.json
+++ b/i18n/el-GR.json
@@ -2196,6 +2196,11 @@
"success": "Η εργασία διαγράφηκε με επιτυχία",
"error": "Αποτυχία διαγραφής εργασίας"
},
+ "duplicate": {
+ "titleSuffix": "{{title}} (αντίγραφο)",
+ "success": "Το αντίγραφο της εργασίας δημιουργήθηκε με επιτυχία",
+ "error": "Αποτυχία δημιουργίας αντιγράφου εργασίας"
+ },
"archive": {
"success": "Αρχειοθετήθηκαν {{count}} εργασίες"
},
@@ -2240,6 +2245,7 @@
"copyLinkSuccess": "Ο σύνδεσμος της εργασίας αντιγράφηκε!"
},
"actions": {
+ "duplicate": "Δημιουργία αντιγράφου",
"archive": "Αρχειοθέτηση",
"markAsPlanned": "Επισήμανση ως προγραμματισμένη",
"delete": "Διαγραφή..."
diff --git a/i18n/en-US.json b/i18n/en-US.json
index b4947cd36..81d0b4839 100644
--- a/i18n/en-US.json
+++ b/i18n/en-US.json
@@ -2209,6 +2209,11 @@
"success": "Task deleted successfully",
"error": "Failed to delete task"
},
+ "duplicate": {
+ "titleSuffix": "{{title}} (copy)",
+ "success": "Task duplicated successfully",
+ "error": "Failed to duplicate task"
+ },
"archive": {
"success": "Archived {{count}} tasks"
},
@@ -2253,6 +2258,7 @@
"copyLinkSuccess": "Task link copied!"
},
"actions": {
+ "duplicate": "Duplicate",
"archive": "Archive",
"markAsPlanned": "Mark as planned",
"delete": "Delete..."
diff --git a/i18n/es-ES.json b/i18n/es-ES.json
index a81561c33..08a63e7c2 100644
--- a/i18n/es-ES.json
+++ b/i18n/es-ES.json
@@ -2192,6 +2192,11 @@
"success": "Tarea eliminada correctamente",
"error": "Error al eliminar la tarea"
},
+ "duplicate": {
+ "titleSuffix": "{{title}} (copia)",
+ "success": "Tarea duplicada correctamente",
+ "error": "Error al duplicar la tarea"
+ },
"archive": {
"success": "Se han archivado {{count}} tareas"
},
@@ -2237,6 +2242,7 @@
"copyLinkSuccess": "¡Enlace a la tarea copiado!"
},
"actions": {
+ "duplicate": "Duplicar",
"archive": "Archivar",
"markAsPlanned": "Marcar como planeada",
"delete": "Eliminar..."
diff --git a/i18n/fr-FR.json b/i18n/fr-FR.json
index 9021a8dfa..42b2d8c4c 100644
--- a/i18n/fr-FR.json
+++ b/i18n/fr-FR.json
@@ -2203,6 +2203,11 @@
"success": "Tâche supprimée avec succès",
"error": "Échec de la suppression de la tâche"
},
+ "duplicate": {
+ "titleSuffix": "{{title}} (copie)",
+ "success": "Tâche dupliquée avec succès",
+ "error": "Échec de la duplication de la tâche"
+ },
"archive": {
"success": "{{count}} tâches archivées"
},
@@ -2248,6 +2253,7 @@
"copyLinkSuccess": "Lien de la tâche copié !"
},
"actions": {
+ "duplicate": "Dupliquer",
"archive": "Archiver",
"markAsPlanned": "Marquer comme planifié",
"delete": "Supprimer..."
diff --git a/i18n/hi-IN.json b/i18n/hi-IN.json
index 3c1f93176..77d16c9ff 100644
--- a/i18n/hi-IN.json
+++ b/i18n/hi-IN.json
@@ -2196,6 +2196,11 @@
"success": "कार्य सफलतापूर्वक हटाया गया",
"error": "कार्य हटाने में विफल"
},
+ "duplicate": {
+ "titleSuffix": "{{title}} (प्रतिलिपि)",
+ "success": "कार्य सफलतापूर्वक डुप्लिकेट किया गया",
+ "error": "कार्य डुप्लिकेट करने में विफल"
+ },
"archive": {
"success": "{{count}} कार्य संग्रहित किए गए"
},
@@ -2240,6 +2245,7 @@
"copyLinkSuccess": "कार्य लिंक कॉपी किया गया!"
},
"actions": {
+ "duplicate": "डुप्लिकेट करें",
"archive": "संग्रहित करें",
"markAsPlanned": "नियोजित चिह्नित करें",
"delete": "हटाएँ..."
diff --git a/i18n/id-ID.json b/i18n/id-ID.json
index 5d9778936..f1f6b0f8d 100644
--- a/i18n/id-ID.json
+++ b/i18n/id-ID.json
@@ -2189,6 +2189,11 @@
"success": "Tugas berhasil dihapus",
"error": "Gagal menghapus tugas"
},
+ "duplicate": {
+ "titleSuffix": "{{title}} (salinan)",
+ "success": "Tugas berhasil diduplikasi",
+ "error": "Gagal menduplikasi tugas"
+ },
"archive": {
"success": "{{count}} tugas diarsipkan"
},
@@ -2232,6 +2237,7 @@
"copyLinkSuccess": "Tautan tugas disalin!"
},
"actions": {
+ "duplicate": "Duplikat",
"archive": "Arsipkan",
"markAsPlanned": "Tandai sebagai direncanakan",
"delete": "Hapus..."
diff --git a/i18n/it-IT.json b/i18n/it-IT.json
index 0e8f074b7..df6682ff3 100644
--- a/i18n/it-IT.json
+++ b/i18n/it-IT.json
@@ -2203,6 +2203,11 @@
"success": "Attività eliminata con successo",
"error": "Eliminazione attività fallita"
},
+ "duplicate": {
+ "titleSuffix": "{{title}} (copia)",
+ "success": "Attività duplicata con successo",
+ "error": "Duplicazione attività fallita"
+ },
"archive": {
"success": "{{count}} attività archiviate"
},
@@ -2248,6 +2253,7 @@
"copyLinkSuccess": "Link attività copiato!"
},
"actions": {
+ "duplicate": "Duplica",
"archive": "Archivia",
"markAsPlanned": "Segna come pianificata",
"delete": "Elimina..."
diff --git a/i18n/ja-JP.json b/i18n/ja-JP.json
index 6d78ceec8..444a2f2af 100644
--- a/i18n/ja-JP.json
+++ b/i18n/ja-JP.json
@@ -2247,7 +2247,8 @@
"actions": {
"archive": "アーカイブ",
"markAsPlanned": "計画中に設定",
- "delete": "削除..."
+ "delete": "削除...",
+ "duplicate": "Duplicate"
},
"bulk": {
"selectedCount": "{{count}} 件選択中",
@@ -2296,7 +2297,12 @@
"descriptionSearchError": "Description search failed. Results may be incomplete.",
"descriptionRetry": "Retry",
"descriptionLoading": "Loading description…",
- "descriptionLoadError": "The description could not be loaded. Retry to load the current version."
+ "descriptionLoadError": "The description could not be loaded. Retry to load the current version.",
+ "duplicate": {
+ "error": "Failed to duplicate task",
+ "success": "Task duplicated successfully",
+ "titleSuffix": "{{title}} (copy)"
+ }
},
"invitations": {
"email": {
diff --git a/i18n/ko-KR.json b/i18n/ko-KR.json
index 2d67194ab..1ab5a309b 100644
--- a/i18n/ko-KR.json
+++ b/i18n/ko-KR.json
@@ -2202,6 +2202,11 @@
"success": "작업이 삭제되었습니다",
"error": "작업 삭제에 실패했습니다"
},
+ "duplicate": {
+ "titleSuffix": "{{title}} (사본)",
+ "success": "작업이 복제되었습니다",
+ "error": "작업 복제에 실패했습니다"
+ },
"archive": {
"success": "작업 {{count}}개를 보관했습니다"
},
@@ -2245,6 +2250,7 @@
"copyLinkSuccess": "작업 링크가 복사되었습니다!"
},
"actions": {
+ "duplicate": "복제",
"archive": "보관",
"markAsPlanned": "계획됨으로 표시",
"delete": "삭제..."
diff --git a/i18n/mk-MK.json b/i18n/mk-MK.json
index b0a9e756c..244a1b893 100644
--- a/i18n/mk-MK.json
+++ b/i18n/mk-MK.json
@@ -2196,6 +2196,11 @@
"success": "Задачата е успешно избришана",
"error": "Неуспешно бришење на задача"
},
+ "duplicate": {
+ "titleSuffix": "{{title}} (копија)",
+ "success": "Задачата е успешно дуплирана",
+ "error": "Неуспешно дуплирање на задача"
+ },
"archive": {
"success": "Архивирани {{count}} задачи"
},
@@ -2240,6 +2245,7 @@
"copyLinkSuccess": "Линкот на задачата е копиран!"
},
"actions": {
+ "duplicate": "Дуплирај",
"archive": "Архивирај",
"markAsPlanned": "Означи како планирана",
"delete": "Избриши..."
diff --git a/i18n/nl-NL.json b/i18n/nl-NL.json
index cda333a75..5711b60d8 100644
--- a/i18n/nl-NL.json
+++ b/i18n/nl-NL.json
@@ -2185,6 +2185,11 @@
"success": "Taak succesvol verwijderd",
"error": "Verwijderen taak mislukt"
},
+ "duplicate": {
+ "titleSuffix": "{{title}} (kopie)",
+ "success": "Taak succesvol gedupliceerd",
+ "error": "Dupliceren taak mislukt"
+ },
"archive": {
"success": "{{count}} taken gearchiveerd"
},
@@ -2229,6 +2234,7 @@
"copyLinkSuccess": "Taaklink gekopieerd!"
},
"actions": {
+ "duplicate": "Dupliceren",
"archive": "Archiveren",
"markAsPlanned": "Markeren als gepland",
"delete": "Verwijderen..."
diff --git a/i18n/pl-PL.json b/i18n/pl-PL.json
index d06dbdea2..f7acd459a 100644
--- a/i18n/pl-PL.json
+++ b/i18n/pl-PL.json
@@ -2060,7 +2060,8 @@
"actions": {
"archive": "Archiwizuj",
"delete": "Usuń...",
- "markAsPlanned": "Oznacz jako zaplanowane"
+ "markAsPlanned": "Oznacz jako zaplanowane",
+ "duplicate": "Duplicate"
},
"archive": {
"success": "Zarchiwizowano zadań: {{count}}"
@@ -2502,7 +2503,12 @@
"descriptionSearchError": "Description search failed. Results may be incomplete.",
"descriptionRetry": "Retry",
"descriptionLoading": "Loading description…",
- "descriptionLoadError": "The description could not be loaded. Retry to load the current version."
+ "descriptionLoadError": "The description could not be loaded. Retry to load the current version.",
+ "duplicate": {
+ "error": "Failed to duplicate task",
+ "success": "Task duplicated successfully",
+ "titleSuffix": "{{title}} (copy)"
+ }
},
"press": {
"title": "Press kit",
diff --git a/i18n/pt-BR.json b/i18n/pt-BR.json
index afc3dffc2..f94b34940 100644
--- a/i18n/pt-BR.json
+++ b/i18n/pt-BR.json
@@ -2203,6 +2203,11 @@
"success": "Tarefa excluída com sucesso",
"error": "Falha ao excluir tarefa"
},
+ "duplicate": {
+ "titleSuffix": "{{title}} (cópia)",
+ "success": "Tarefa duplicada com sucesso",
+ "error": "Falha ao duplicar tarefa"
+ },
"archive": {
"success": "{{count}} tarefas arquivadas"
},
@@ -2248,6 +2253,7 @@
"copyLinkSuccess": "Link da tarefa copiado!"
},
"actions": {
+ "duplicate": "Duplicar",
"archive": "Arquivar",
"markAsPlanned": "Marcar como planejado",
"delete": "Excluir..."
diff --git a/i18n/ru-RU.json b/i18n/ru-RU.json
index f55f8a29f..451141be3 100644
--- a/i18n/ru-RU.json
+++ b/i18n/ru-RU.json
@@ -2226,6 +2226,11 @@
"success": "Задача успешно удалена",
"error": "Не удалось удалить задачу"
},
+ "duplicate": {
+ "titleSuffix": "{{title}} (копия)",
+ "success": "Задача успешно дублирована",
+ "error": "Не удалось дублировать задачу"
+ },
"archive": {
"success_one": "{{count}} задача архивирована",
"success_few": "{{count}} задачи архивированы",
@@ -2276,6 +2281,7 @@
"copyLinkSuccess": "Ссылка на задачу скопирована!"
},
"actions": {
+ "duplicate": "Дублировать",
"archive": "Архивировать",
"markAsPlanned": "Отметить как запланированную",
"delete": "Удалить..."
diff --git a/i18n/schema.json b/i18n/schema.json
index 406c8e02d..a93343dee 100644
--- a/i18n/schema.json
+++ b/i18n/schema.json
@@ -8910,6 +8910,22 @@
},
"required": ["title", "description", "action", "success", "error"]
},
+ "duplicate": {
+ "type": "object",
+ "additionalProperties": false,
+ "properties": {
+ "titleSuffix": {
+ "type": "string"
+ },
+ "success": {
+ "type": "string"
+ },
+ "error": {
+ "type": "string"
+ }
+ },
+ "required": ["titleSuffix", "success", "error"]
+ },
"archive": {
"type": "object",
"additionalProperties": false,
@@ -9089,6 +9105,9 @@
"type": "object",
"additionalProperties": false,
"properties": {
+ "duplicate": {
+ "type": "string"
+ },
"archive": {
"type": "string"
},
@@ -9099,7 +9118,7 @@
"type": "string"
}
},
- "required": ["archive", "markAsPlanned", "delete"]
+ "required": ["duplicate", "archive", "markAsPlanned", "delete"]
},
"bulk": {
"type": "object",
@@ -9461,6 +9480,7 @@
"calendar",
"gantt",
"delete",
+ "duplicate",
"archive",
"listView",
"kanban",
diff --git a/i18n/tr-TR.json b/i18n/tr-TR.json
index 3d1beb82f..696a8d027 100644
--- a/i18n/tr-TR.json
+++ b/i18n/tr-TR.json
@@ -2196,6 +2196,11 @@
"success": "Talep başarıyla silindi",
"error": "Talep silinemedi"
},
+ "duplicate": {
+ "titleSuffix": "{{title}} (kopya)",
+ "success": "Talep başarıyla çoğaltıldı",
+ "error": "Talep çoğaltılamadı"
+ },
"archive": {
"success": "{{count}} talep arşivlendi"
},
@@ -2240,6 +2245,7 @@
"copyLinkSuccess": "Talep bağlantısı kopyalandı!"
},
"actions": {
+ "duplicate": "Çoğalt",
"archive": "Arşivle",
"markAsPlanned": "Planlandı olarak işaretle",
"delete": "Sil..."
diff --git a/i18n/uk-UA.json b/i18n/uk-UA.json
index d053e99a1..16ea44c2d 100644
--- a/i18n/uk-UA.json
+++ b/i18n/uk-UA.json
@@ -2210,6 +2210,11 @@
"success": "Завдання успішно видалено",
"error": "Не вдалося видалити завдання"
},
+ "duplicate": {
+ "titleSuffix": "{{title}} (копія)",
+ "success": "Завдання успішно дубльовано",
+ "error": "Не вдалося дублювати завдання"
+ },
"archive": {
"success": "Архівовано {{count}} завдань"
},
@@ -2256,6 +2261,7 @@
"copyLinkSuccess": "Посилання на завдання скопійовано!"
},
"actions": {
+ "duplicate": "Дублювати",
"archive": "Архівувати",
"markAsPlanned": "Позначити як заплановане",
"delete": "Видалити..."
diff --git a/i18n/vi-VN.json b/i18n/vi-VN.json
index ed6e1c8bd..b6e2ef6e1 100644
--- a/i18n/vi-VN.json
+++ b/i18n/vi-VN.json
@@ -2189,6 +2189,11 @@
"success": "Xóa công việc thành công",
"error": "Không thể xóa công việc"
},
+ "duplicate": {
+ "titleSuffix": "{{title}} (bản sao)",
+ "success": "Nhân bản công việc thành công",
+ "error": "Không thể nhân bản công việc"
+ },
"archive": {
"success": "Đã lưu trữ {{count}} công việc"
},
@@ -2232,6 +2237,7 @@
"copyLinkSuccess": "Đã sao chép liên kết công việc!"
},
"actions": {
+ "duplicate": "Nhân bản",
"archive": "Lưu trữ",
"markAsPlanned": "Đánh dấu đã lên kế hoạch",
"delete": "Xóa..."
diff --git a/i18n/zh-CN.json b/i18n/zh-CN.json
index 77e093e6e..316e7541d 100644
--- a/i18n/zh-CN.json
+++ b/i18n/zh-CN.json
@@ -2202,6 +2202,11 @@
"success": "任务已删除",
"error": "删除任务失败"
},
+ "duplicate": {
+ "titleSuffix": "{{title}}(副本)",
+ "success": "已创建任务副本",
+ "error": "创建任务副本失败"
+ },
"archive": {
"success": "已归档 {{count}} 个任务"
},
@@ -2245,6 +2250,7 @@
"copyLinkSuccess": "任务链接已复制!"
},
"actions": {
+ "duplicate": "创建副本",
"archive": "归档",
"markAsPlanned": "标记为已计划",
"delete": "删除…"
diff --git a/packages/mcp/src/tools/register.ts b/packages/mcp/src/tools/register.ts
index 306e0b95e..4665f0578 100644
--- a/packages/mcp/src/tools/register.ts
+++ b/packages/mcp/src/tools/register.ts
@@ -282,6 +282,30 @@ export function registerTools(
},
);
+ server.registerTool(
+ "duplicate_task",
+ {
+ description:
+ "Duplicate a task in the same project, copying its fields and labels. Pass title to rename the copy.",
+ inputSchema: z.object({
+ taskId: nonEmptyString,
+ title: optionalNonEmptyString,
+ }),
+ },
+ async (args) => {
+ const body: Record<string, string> = {};
+ if (args.title !== undefined) {
+ body.title = args.title;
+ }
+ return run(() =>
+ client.json(`/api/task/duplicate/${encodeURIComponent(args.taskId)}`, {
+ method: "POST",
+ body: JSON.stringify(body),
+ }),
+ );
+ },
+ );
+
const updateTaskSchema = z.object({
taskId: nonEmptyString,
title: optionalNonEmptyString,
diff --git a/tests/api-integration/task-duplicate.test.ts b/tests/api-integration/task-duplicate.test.ts
new file mode 100644
index 000000000..9a0d38fa8
--- /dev/null
+++ b/tests/api-integration/task-duplicate.test.ts
@@ -0,0 +1,707 @@
+import { randomUUID } from "node:crypto";
+import { and, eq } from "drizzle-orm";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const { copyTaskAssetObject, deleteS3Object, publishEvent } = vi.hoisted(
+ () => ({
+ deleteS3Object: vi.fn(async () => undefined),
+ publishEvent: vi.fn(async () => undefined),
+ copyTaskAssetObject: vi.fn(),
+ }),
+);
+
+vi.mock("../../apps/api/src/storage/s3", async (importOriginal) => {
+ const actual =
+ await importOriginal<typeof import("../../apps/api/src/storage/s3")>();
+ return { ...actual, copyTaskAssetObject, deleteS3Object };
+});
+
+vi.mock("../../apps/api/src/events", async (original) => ({
+ ...(await original<object>()),
+ publishEvent,
+}));
+
+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 {
+ createProjectFixture,
+ createWorkspaceMember,
+} from "./helpers/fixtures";
+
+const DUPLICATED_OBJECT_KEY =
+ "workspace/ws/project/pj/task/copy/descriptions/diagram-1-copy.png";
+
+async function seedTask({
+ projectId,
+ columnId,
+ userId,
+ overrides,
+}: {
+ projectId: string;
+ columnId: string | null;
+ userId?: string;
+ overrides?: Partial<typeof schema.taskTable.$inferInsert>;
+}) {
+ const [task] = await db
+ .insert(schema.taskTable)
+ .values({
+ projectId,
+ columnId,
+ title: "Release checklist",
+ description: "Steps to cut a release",
+ status: "to-do",
+ priority: "high",
+ number: 1,
+ position: 1,
+ ...(userId ? { userId } : {}),
+ ...overrides,
+ })
+ .returning();
+
+ if (!task) {
+ throw new Error("Failed to seed task");
+ }
+
+ await db
+ .update(schema.projectTable)
+ .set({ lastTaskNumber: task.number ?? 1 })
+ .where(eq(schema.projectTable.id, projectId));
+
+ return task;
+}
+
+function requestDuplicate(
+ app: ReturnType<typeof createApp>["app"],
+ taskId: string,
+ body: { title?: string } = {},
+) {
+ return app.request(`/api/task/duplicate/${taskId}`, {
+ method: "POST",
+ headers: {
+ "content-type": "application/json",
+ },
+ body: JSON.stringify(body),
+ });
+}
+
+describe("API integration: task duplication", () => {
+ beforeEach(async () => {
+ await resetTestDatabase();
+ vi.clearAllMocks();
+ copyTaskAssetObject.mockReset();
+ copyTaskAssetObject.mockImplementation(async () => DUPLICATED_OBJECT_KEY);
+ });
+
+ it("rejects unauthenticated task duplication requests", async () => {
+ const member = await createWorkspaceMember();
+ const { project, columns } = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ });
+ const task = await seedTask({
+ projectId: project.id,
+ columnId: columns.todo.id,
+ });
+
+ mockAnonymousSession();
+ const { app } = createApp();
+
+ const response = await requestDuplicate(app, task.id);
+
+ expect(response.status).toBe(401);
+ await expect(response.text()).resolves.toBe("Unauthorized");
+ });
+
+ it("blocks a viewer from duplicating a task (viewer role lacks task:create)", async () => {
+ const viewer = await createWorkspaceMember({ role: "viewer" });
+ const { project, columns } = await createProjectFixture({
+ workspaceId: viewer.workspace.id,
+ });
+ const task = await seedTask({
+ projectId: project.id,
+ columnId: columns.todo.id,
+ });
+
+ mockAuthenticatedSession(viewer.user);
+ const { app } = createApp();
+
+ const response = await requestDuplicate(app, task.id);
+
+ expect(response.status).toBe(403);
+ await expect(response.text()).resolves.toBe("Insufficient permissions");
+
+ const tasks = await db.query.taskTable.findMany({
+ where: eq(schema.taskTable.projectId, project.id),
+ });
+
+ expect(tasks).toHaveLength(1);
+ });
+
+ it("rejects duplication for users outside the project workspace", async () => {
+ const member = await createWorkspaceMember();
+ const { project, columns } = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ });
+ const task = await seedTask({
+ projectId: project.id,
+ columnId: columns.todo.id,
+ });
+
+ const outsiderId = `user-${randomUUID()}`;
+ const [outsider] = await db
+ .insert(schema.userTable)
+ .values({
+ id: outsiderId,
+ email: `${outsiderId}@example.com`,
+ emailVerified: true,
+ name: "Duplicate Outsider",
+ })
+ .returning();
+
+ mockAuthenticatedSession(outsider);
+ const { app } = createApp();
+
+ const response = await requestDuplicate(app, task.id);
+
+ expect(response.status).toBe(403);
+ await expect(response.text()).resolves.toBe(
+ "You don't have access to this workspace",
+ );
+
+ const tasks = await db.query.taskTable.findMany({
+ where: eq(schema.taskTable.projectId, project.id),
+ });
+
+ expect(tasks).toHaveLength(1);
+ });
+
+ it("copies the task fields and labels into a new task at the end of the column", async () => {
+ const member = await createWorkspaceMember();
+ const { project, columns } = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ });
+ const task = await seedTask({
+ projectId: project.id,
+ columnId: columns.inProgress.id,
+ userId: member.user.id,
+ overrides: {
+ status: "in-progress",
+ startDate: new Date("2026-04-01T09:00:00.000Z"),
+ dueDate: new Date("2026-04-05T17:00:00.000Z"),
+ },
+ });
+
+ await db.insert(schema.labelTable).values([
+ {
+ name: "backend",
+ color: "#FF6600",
+ taskId: task.id,
+ workspaceId: member.workspace.id,
+ },
+ {
+ name: "release",
+ color: "#00AAFF",
+ taskId: task.id,
+ workspaceId: member.workspace.id,
+ },
+ ]);
+
+ mockAuthenticatedSession(member.user);
+ const { app } = createApp();
+
+ const response = await requestDuplicate(app, task.id, {
+ title: "Release checklist (copy)",
+ });
+
+ expect(response.status).toBe(200);
+ const payload = (await response.json()) as {
+ id: string;
+ title: string;
+ number: number | null;
+ position: number | null;
+ assigneeName?: string;
+ };
+
+ expect(payload.id).not.toBe(task.id);
+ expect(payload).toMatchObject({
+ title: "Release checklist (copy)",
+ number: 2,
+ position: 2,
+ assigneeName: member.user.name,
+ });
+
+ const duplicatedTask = await db.query.taskTable.findFirst({
+ where: eq(schema.taskTable.id, payload.id),
+ });
+
+ expect(duplicatedTask).toMatchObject({
+ projectId: project.id,
+ columnId: columns.inProgress.id,
+ userId: member.user.id,
+ title: "Release checklist (copy)",
+ description: task.description,
+ status: "in-progress",
+ priority: "high",
+ number: 2,
+ position: 2,
+ });
+ expect(duplicatedTask?.startDate?.toISOString()).toBe(
+ "2026-04-01T09:00:00.000Z",
+ );
+ expect(duplicatedTask?.dueDate?.toISOString()).toBe(
+ "2026-04-05T17:00:00.000Z",
+ );
+
+ const duplicatedLabels = await db
+ .select({
+ name: schema.labelTable.name,
+ color: schema.labelTable.color,
+ workspaceId: schema.labelTable.workspaceId,
+ })
+ .from(schema.labelTable)
+ .where(eq(schema.labelTable.taskId, payload.id));
+
+ expect(duplicatedLabels).toEqual(
+ expect.arrayContaining([
+ {
+ name: "backend",
+ color: "#FF6600",
+ workspaceId: member.workspace.id,
+ },
+ {
+ name: "release",
+ color: "#00AAFF",
+ workspaceId: member.workspace.id,
+ },
+ ]),
+ );
+ expect(duplicatedLabels).toHaveLength(2);
+
+ const sourceTask = await db.query.taskTable.findFirst({
+ where: eq(schema.taskTable.id, task.id),
+ });
+
+ expect(sourceTask).toMatchObject({
+ title: "Release checklist",
+ number: 1,
+ position: 1,
+ });
+ });
+
+ it("keeps a duplicated subtask under the same parent without copying its own subtasks", async () => {
+ const member = await createWorkspaceMember();
+ const { project, columns } = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ });
+ const parent = await seedTask({
+ projectId: project.id,
+ columnId: columns.todo.id,
+ overrides: { title: "Release epic", number: 1, position: 1 },
+ });
+ const subtask = await seedTask({
+ projectId: project.id,
+ columnId: columns.todo.id,
+ overrides: { title: "Bump version", number: 2, position: 2 },
+ });
+ const grandchild = await seedTask({
+ projectId: project.id,
+ columnId: columns.todo.id,
+ overrides: { title: "Update changelog", number: 3, position: 3 },
+ });
+
+ await db.insert(schema.taskRelationTable).values([
+ {
+ sourceTaskId: parent.id,
+ targetTaskId: subtask.id,
+ relationType: "subtask",
+ },
+ {
+ sourceTaskId: subtask.id,
+ targetTaskId: grandchild.id,
+ relationType: "subtask",
+ },
+ ]);
+
+ mockAuthenticatedSession(member.user);
+ const { app } = createApp();
+
+ const response = await requestDuplicate(app, subtask.id);
+
+ expect(response.status).toBe(200);
+ const payload = (await response.json()) as { id: string };
+
+ const parentsOfCopy = await db
+ .select({
+ sourceTaskId: schema.taskRelationTable.sourceTaskId,
+ relationType: schema.taskRelationTable.relationType,
+ })
+ .from(schema.taskRelationTable)
+ .where(eq(schema.taskRelationTable.targetTaskId, payload.id));
+
+ expect(parentsOfCopy).toEqual([
+ { sourceTaskId: parent.id, relationType: "subtask" },
+ ]);
+
+ const childrenOfCopy = await db
+ .select({ id: schema.taskRelationTable.id })
+ .from(schema.taskRelationTable)
+ .where(eq(schema.taskRelationTable.sourceTaskId, payload.id));
+
+ expect(childrenOfCopy).toEqual([]);
+ });
+
+ it("copies the description assets and repoints the copy at them", async () => {
+ const member = await createWorkspaceMember();
+ const { project, columns } = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ });
+ const sourceAssetId = "asset1sourcekey000000001";
+ const task = await seedTask({
+ projectId: project.id,
+ columnId: columns.todo.id,
+ overrides: {
+ description: `<p>Before</p><img src="http://localhost:1337/api/asset/${sourceAssetId}" alt="Diagram" /><p>After</p>`,
+ },
+ });
+
+ await db.insert(schema.assetTable).values({
+ id: sourceAssetId,
+ workspaceId: member.workspace.id,
+ projectId: project.id,
+ taskId: task.id,
+ objectKey:
+ "workspace/ws/project/pj/task/source/descriptions/diagram-1.png",
+ filename: "diagram-1.png",
+ mimeType: "image/png",
+ size: 2048,
+ kind: "image",
+ surface: "description",
+ createdBy: member.user.id,
+ });
+
+ mockAuthenticatedSession(member.user);
+ const { app } = createApp();
+
+ const response = await requestDuplicate(app, task.id);
+
+ expect(response.status).toBe(200);
+ const payload = (await response.json()) as {
+ id: string;
+ description: string;
+ };
+
+ expect(copyTaskAssetObject).toHaveBeenCalledTimes(1);
+ expect(copyTaskAssetObject).toHaveBeenCalledWith({
+ sourceKey:
+ "workspace/ws/project/pj/task/source/descriptions/diagram-1.png",
+ destination: {
+ workspaceId: member.workspace.id,
+ projectId: project.id,
+ taskId: payload.id,
+ surface: "description",
+ filename: "diagram-1.png",
+ contentType: "image/png",
+ },
+ });
+
+ const [duplicatedAsset] = await db
+ .select()
+ .from(schema.assetTable)
+ .where(eq(schema.assetTable.taskId, payload.id));
+
+ expect(duplicatedAsset).toMatchObject({
+ workspaceId: member.workspace.id,
+ projectId: project.id,
+ objectKey: DUPLICATED_OBJECT_KEY,
+ filename: "diagram-1.png",
+ mimeType: "image/png",
+ size: 2048,
+ kind: "image",
+ surface: "description",
+ createdBy: member.user.id,
+ });
+ expect(duplicatedAsset?.id).not.toBe(sourceAssetId);
+
+ expect(payload.description).toContain(`/api/asset/${duplicatedAsset?.id}`);
+ expect(payload.description).not.toContain(sourceAssetId);
+
+ const sourceTask = await db.query.taskTable.findFirst({
+ where: eq(schema.taskTable.id, task.id),
+ });
+
+ expect(sourceTask?.description).toContain(`/api/asset/${sourceAssetId}`);
+ });
+
+ it("keeps the source title when no title override is provided", async () => {
+ const member = await createWorkspaceMember();
+ const { project, columns } = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ });
+ const task = await seedTask({
+ projectId: project.id,
+ columnId: columns.todo.id,
+ });
+
+ mockAuthenticatedSession(member.user);
+ const { app } = createApp();
+
+ const response = await requestDuplicate(app, task.id);
+
+ expect(response.status).toBe(200);
+ const payload = (await response.json()) as { id: string; title: string };
+
+ expect(payload.title).toBe("Release checklist");
+
+ const duplicatedTask = await db.query.taskTable.findFirst({
+ where: and(
+ eq(schema.taskTable.id, payload.id),
+ eq(schema.taskTable.projectId, project.id),
+ ),
+ });
+
+ expect(duplicatedTask?.title).toBe("Release checklist");
+ });
+
+ async function fixture() {
+ const member = await createWorkspaceMember();
+ const { project, columns } = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ });
+ const task = await seedTask({
+ projectId: project.id,
+ columnId: columns.todo.id,
+ });
+ mockAuthenticatedSession(member.user);
+ return { ...member, project, columns, task, app: createApp().app };
+ }
+
+ it("copies project custom fields and fills missing required defaults", async () => {
+ const own = await fixture();
+ const definitions = await db
+ .insert(schema.customFieldDefinitionTable)
+ .values([
+ {
+ projectId: own.project.id,
+ name: "Estimate",
+ type: "number",
+ required: true,
+ },
+ { projectId: own.project.id, name: "Approved", type: "boolean" },
+ { projectId: own.project.id, name: "Note", type: "text" },
+ {
+ projectId: own.project.id,
+ name: "Category",
+ type: "dropdown",
+ required: true,
+ defaultValue: "Work",
+ options: ["Work", "Personal"],
+ },
+ ])
+ .returning();
+ await db.insert(schema.customFieldValueTable).values([
+ { taskId: own.task.id, fieldId: definitions[0].id, value: "5" },
+ { taskId: own.task.id, fieldId: definitions[1].id, value: "false" },
+ { taskId: own.task.id, fieldId: definitions[2].id, value: null },
+ ]);
+ const { project: otherProject } = await createProjectFixture({
+ workspaceId: own.workspace.id,
+ });
+ const [foreignField] = await db
+ .insert(schema.customFieldDefinitionTable)
+ .values({ projectId: otherProject.id, name: "Foreign", type: "text" })
+ .returning();
+ await db.insert(schema.customFieldValueTable).values({
+ taskId: own.task.id,
+ fieldId: foreignField.id,
+ value: "do not copy",
+ });
+ const response = await requestDuplicate(own.app, own.task.id);
+ expect(response.status).toBe(200);
+ const copy = (await response.json()) as { id: string };
+ const values = await db.query.customFieldValueTable.findMany({
+ where: eq(schema.customFieldValueTable.taskId, copy.id),
+ });
+ expect(new Map(values.map((v) => [v.fieldId, v.value]))).toEqual(
+ new Map([
+ [definitions[0].id, "5"],
+ [definitions[1].id, "false"],
+ [definitions[2].id, ""],
+ [definitions[3].id, "Work"],
+ ]),
+ );
+ await db
+ .delete(schema.taskTable)
+ .where(eq(schema.taskTable.id, own.task.id));
+ expect(
+ await db.query.customFieldValueTable.findMany({
+ where: eq(schema.customFieldValueTable.taskId, copy.id),
+ }),
+ ).toHaveLength(4);
+ });
+
+ it("rejects missing required fields before creating a task or copying storage", async () => {
+ const own = await fixture();
+ await db.insert(schema.customFieldDefinitionTable).values({
+ projectId: own.project.id,
+ name: "Required",
+ type: "text",
+ required: true,
+ });
+ const response = await requestDuplicate(own.app, own.task.id);
+ expect(response.status).toBe(400);
+ expect(await response.text()).toContain("required");
+ expect(await db.query.taskTable.findMany()).toHaveLength(1);
+ expect(copyTaskAssetObject).not.toHaveBeenCalled();
+ expect(publishEvent).not.toHaveBeenCalled();
+ });
+
+ it("rejects an obsolete custom-field dropdown value", async () => {
+ const own = await fixture();
+ const [field] = await db
+ .insert(schema.customFieldDefinitionTable)
+ .values({
+ projectId: own.project.id,
+ name: "Category",
+ type: "dropdown",
+ options: ["new"],
+ })
+ .returning();
+ await db
+ .insert(schema.customFieldValueTable)
+ .values({ taskId: own.task.id, fieldId: field.id, value: "old" });
+ expect((await requestDuplicate(own.app, own.task.id)).status).toBe(400);
+ expect(await db.query.taskTable.findMany()).toHaveLength(1);
+ });
+
+ it("copies only same-workspace parents and labels from legacy mixed data", async () => {
+ const own = await fixture();
+ const other = await createWorkspaceMember();
+ const { project: foreignProject, columns: foreignColumns } =
+ await createProjectFixture({ workspaceId: other.workspace.id });
+ const foreignParent = await seedTask({
+ projectId: foreignProject.id,
+ columnId: foreignColumns.todo.id,
+ });
+ const { project: siblingProject, columns: siblingColumns } =
+ await createProjectFixture({ workspaceId: own.workspace.id });
+ const parent = await seedTask({
+ projectId: siblingProject.id,
+ columnId: siblingColumns.todo.id,
+ });
+ await db.insert(schema.taskRelationTable).values(
+ [parent, foreignParent].map((p) => ({
+ sourceTaskId: p.id,
+ targetTaskId: own.task.id,
+ relationType: "subtask",
+ })),
+ );
+ await db.insert(schema.labelTable).values([
+ {
+ taskId: own.task.id,
+ workspaceId: own.workspace.id,
+ name: "Local",
+ color: "blue",
+ },
+ {
+ taskId: own.task.id,
+ workspaceId: other.workspace.id,
+ name: "Foreign",
+ color: "red",
+ },
+ ]);
+ const response = await requestDuplicate(own.app, own.task.id);
+ expect(response.status).toBe(200);
+ const copy = (await response.json()) as { id: string };
+ expect(
+ await db.query.taskRelationTable.findMany({
+ where: eq(schema.taskRelationTable.targetTaskId, copy.id),
+ }),
+ ).toMatchObject([{ sourceTaskId: parent.id }]);
+ const labels = await db.query.labelTable.findMany({
+ where: eq(schema.labelTable.taskId, copy.id),
+ });
+ expect(labels).toHaveLength(1);
+ expect(labels[0].name).toBe("Local");
+ const relationEvents = publishEvent.mock.calls.filter(
+ ([name]) => name === "task-relation.created",
+ );
+ expect(relationEvents).toHaveLength(1);
+ expect(relationEvents[0][1]).toMatchObject({
+ sourceTaskId: parent.id,
+ projectId: siblingProject.id,
+ });
+ });
+
+ it("allocates distinct task numbers and positions for simultaneous copies", async () => {
+ const own = await fixture();
+ const responses = await Promise.all([
+ requestDuplicate(own.app, own.task.id),
+ requestDuplicate(own.app, own.task.id),
+ ]);
+ expect(responses.map((r) => r.status)).toEqual([200, 200]);
+ const copies = (await Promise.all(responses.map((r) => r.json()))) as {
+ number: number;
+ position: number;
+ }[];
+ expect(copies.map((c) => c.number).sort()).toEqual([2, 3]);
+ expect(copies.map((c) => c.position).sort()).toEqual([2, 3]);
+ });
+
+ it("repairs a full position range before appending the copy", async () => {
+ const own = await fixture();
+ await db
+ .update(schema.taskTable)
+ .set({ position: 2147483647 })
+ .where(eq(schema.taskTable.id, own.task.id));
+ const response = await requestDuplicate(own.app, own.task.id);
+ expect(response.status).toBe(200);
+ expect(await response.json()).toMatchObject({ position: 2 });
+ });
+
+ it("does not carry a foreign assignee into a new task", async () => {
+ const own = await fixture();
+ const other = await createWorkspaceMember();
+ await db
+ .update(schema.taskTable)
+ .set({ userId: other.user.id })
+ .where(eq(schema.taskTable.id, own.task.id));
+ expect((await requestDuplicate(own.app, own.task.id)).status).toBe(403);
+ expect(await db.query.taskTable.findMany()).toHaveLength(1);
+ });
+
+ it("cleans up partial asset copies and returns a safe error", async () => {
+ const own = await fixture();
+ const ids = ["firstasset", "secondasset"];
+ await db
+ .update(schema.taskTable)
+ .set({
+ description: ids.map((id) => `![Image](/api/asset/${id})`).join("\n"),
+ })
+ .where(eq(schema.taskTable.id, own.task.id));
+ await db.insert(schema.assetTable).values(
+ ids.map((id) => ({
+ id,
+ taskId: own.task.id,
+ projectId: own.project.id,
+ workspaceId: own.workspace.id,
+ objectKey: id,
+ filename: "image.png",
+ mimeType: "image/png",
+ size: 10,
+ kind: "image",
+ surface: "description",
+ createdBy: own.user.id,
+ })),
+ );
+ copyTaskAssetObject
+ .mockResolvedValueOnce("copied-first")
+ .mockRejectedValueOnce(new Error("private bucket details"));
+ const response = await requestDuplicate(own.app, own.task.id);
+ expect(response.status).toBe(503);
+ expect(await response.text()).toBe("Failed to copy the task attachments");
+ expect(deleteS3Object).toHaveBeenCalledWith("copied-first");
+ expect(await db.query.taskTable.findMany()).toHaveLength(1);
+ expect(publishEvent).not.toHaveBeenCalled();
+ });
+});
diff --git a/tests/api/mcp-tools.test.ts b/tests/api/mcp-tools.test.ts
index 27be87004..e567ff884 100644
--- a/tests/api/mcp-tools.test.ts
+++ b/tests/api/mcp-tools.test.ts
@@ -100,6 +100,19 @@ describe("MCP tool catalog", () => {
});
});
+ it("duplicates a task and only sends a title when one is given", async () => {
+ await call("duplicate_task", { taskId: "t 1" });
+
+ expect(lastRequest()).toMatchObject({
+ url: "http://api.test/api/task/duplicate/t%201",
+ method: "POST",
+ body: {},
+ });
+
+ await call("duplicate_task", { taskId: "t1", title: "Checklist (copy)" });
+ expect(lastRequest().body).toEqual({ title: "Checklist (copy)" });
+ });
+
it("assigns and unassigns a task", async () => {
await call("update_task_assignee", { taskId: "t1", userId: "u1" });
expect(lastRequest()).toMatchObject({
diff --git a/tests/api/storage/s3.test.ts b/tests/api/storage/s3.test.ts
index bdc3a1f26..a3e1438d2 100644
--- a/tests/api/storage/s3.test.ts
+++ b/tests/api/storage/s3.test.ts
@@ -1,3 +1,4 @@
+import { S3Client } from "@aws-sdk/client-s3";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
applyKeyPrefix,
@@ -5,6 +6,7 @@ import {
assertTaskImageKeyMatchesContext,
buildObjectKey,
buildObjectKeyPrefix,
+ copyTaskAssetObject,
createTaskImageUploadUrl,
getFileExtension,
isImageContentType,
@@ -267,6 +269,45 @@ describe("S3 helpers", () => {
expect(searchParams.has("x-amz-sdk-checksum-algorithm")).toBe(false);
});
+ it("copies a stored object into the destination task prefix", async () => {
+ process.env.S3_ENDPOINT = "https://storage.example.test";
+ process.env.S3_BUCKET = "kaneo";
+ process.env.S3_ACCESS_KEY_ID = "test-access-key";
+ process.env.S3_SECRET_ACCESS_KEY = "test-secret-key";
+ process.env.S3_KEY_PREFIX = "kaneo-assets";
+
+ const send = vi
+ .spyOn(S3Client.prototype, "send")
+ .mockResolvedValue(undefined as never);
+
+ const key = await copyTaskAssetObject({
+ sourceKey: "workspace/w1/project/p1/task/t1/descriptions/report.png",
+ destination: {
+ workspaceId: "workspace-1",
+ projectId: "project-1",
+ taskId: "task-2",
+ surface: "description",
+ filename: "report.png",
+ contentType: "image/png",
+ },
+ });
+
+ expect(key).toMatch(
+ /^kaneo-assets\/workspace\/workspace-1\/project\/project-1\/task\/task-2\/descriptions\/report-\d+-[a-z0-9]+\.png$/,
+ );
+
+ const command = send.mock.calls[0]?.[0] as {
+ input: Record<string, string>;
+ };
+
+ expect(command.input).toMatchObject({
+ Bucket: "kaneo",
+ CopySource:
+ "kaneo/workspace/w1/project/p1/task/t1/descriptions/report.png",
+ Key: key,
+ });
+ });
+
it("resolveS3Credentials returns explicit credentials when both keys are set", () => {
expect(resolveS3Credentials("AKIA", "secret")).toEqual({
accessKeyId: "AKIA",
diff --git a/tests/storage-integration/presigned-upload.test.ts b/tests/storage-integration/presigned-upload.test.ts
index 0e3c7a1fd..e269a2087 100644
--- a/tests/storage-integration/presigned-upload.test.ts
+++ b/tests/storage-integration/presigned-upload.test.ts
@@ -3,12 +3,14 @@ import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import {
CreateBucketCommand,
DeleteBucketCommand,
+ GetObjectCommand,
HeadObjectCommand,
ListObjectsV2Command,
PutObjectCommand,
S3Client,
} from "../../apps/api/node_modules/@aws-sdk/client-s3";
import {
+ copyTaskAssetObject,
createTaskImageUploadUrl,
deleteS3Object,
verifyTaskAssetUpload,
@@ -79,6 +81,39 @@ function head(key: string) {
}
describe("presigned uploads against real local S3 storage", () => {
+ it("copies an attachment with reserved characters and survives source deletion", async () => {
+ const sourceKey = "source/report #1%.png";
+ const body = Buffer.from("independent attachment");
+ await client.send(
+ new PutObjectCommand({
+ Bucket: bucket,
+ Key: sourceKey,
+ Body: body,
+ ContentType: "image/png",
+ }),
+ );
+ const copiedKey = await copyTaskAssetObject({
+ sourceKey,
+ destination: {
+ workspaceId: "local",
+ projectId: "local",
+ taskId: "duplicate",
+ surface: "description",
+ filename: "report.png",
+ contentType: "image/png",
+ },
+ });
+ expect(copiedKey).toContain("/task/duplicate/");
+ await deleteS3Object(sourceKey);
+ const copied = await client.send(
+ new GetObjectCommand({ Bucket: bucket, Key: copiedKey }),
+ );
+ expect(copied.ContentType).toBe("image/png");
+ expect(await copied.Body?.transformToByteArray()).toEqual(
+ new Uint8Array(body),
+ );
+ });
+
it("accepts an exact-size File upload and verifies stored metadata", async () => {
const upload = await presign(64);
const response = await fetch(upload.uploadUrl, {