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.

fix: serialize position allocation and roll back failed drags

Tin543d999729b4
diff --cc apps/api/src/task/controllers/reorder-tasks.ts
index d449436eb,000000000..fa15b2748
mode 100644,000000..100644
--- a/apps/api/src/task/controllers/reorder-tasks.ts
+++ b/apps/api/src/task/controllers/reorder-tasks.ts
@@@ -1,151 -1,0 +1,155 @@@
+import { and, asc, eq, inArray, sql } from "drizzle-orm";
+import { HTTPException } from "hono/http-exception";
+import db from "../../database";
- import { columnTable, taskTable } from "../../database/schema";
++import { columnTable, projectTable, taskTable } from "../../database/schema";
+import { publishEvent } from "../../events";
+import { assertValidTaskStatus } from "../validate-task-fields";
+import { assertTaskPosition } from "./next-task-position";
+import { publishTaskMutation } from "./task-mutation-effects";
+
+type Reorder = { id: string; position: number; status?: string };
+export default async function reorderTasks(
+ projectId: string,
+ tasks: Reorder[],
+ userId: string,
+ expectedTasks?: { id: string; position: number | null; status: string }[],
+) {
+ if (new Set(tasks.map((task) => task.id)).size !== tasks.length)
+ throw new HTTPException(400, { message: "Task IDs must be unique" });
+ for (const task of tasks) assertTaskPosition(task.position);
+ const statuses = [
+ ...new Set(
+ tasks.flatMap((task) => (task.status === undefined ? [] : [task.status])),
+ ),
+ ];
+ const columns = new Map<string, string | null>();
+ for (const status of statuses) {
+ await assertValidTaskStatus(status, projectId);
+ const column = await db.query.columnTable.findFirst({
+ where: and(
+ eq(columnTable.projectId, projectId),
+ eq(columnTable.slug, status),
+ ),
+ });
+ columns.set(status, column?.id ?? null);
+ }
+ const { before, after } = await db.transaction(async (tx) => {
- // Serialize reorders before comparing the complete affected-column snapshot.
- await tx.execute(
- sql`select pg_advisory_xact_lock(hashtext(${projectId}), hashtext('task-reorder'))`,
- );
++ // Task creation, duplication and moves lock this same row while allocating positions.
++ const [project] = await tx
++ .select({ id: projectTable.id })
++ .from(projectTable)
++ .where(eq(projectTable.id, projectId))
++ .for("update");
++ if (!project)
++ throw new HTTPException(404, { message: "Project not found" });
+ // Lock all affected cards together; a concurrent move cannot escape the
+ // scope check between reading their current state and writing positions.
+ const before = await tx
+ .select({
+ id: taskTable.id,
+ status: taskTable.status,
+ position: taskTable.position,
+ })
+ .from(taskTable)
+ .where(
+ and(
+ eq(taskTable.projectId, projectId),
+ expectedTasks
+ ? inArray(taskTable.status, [
+ ...new Set([
+ ...expectedTasks.map((task) => task.status),
+ ...statuses,
+ ]),
+ ])
+ : inArray(
+ taskTable.id,
+ tasks.map((task) => task.id),
+ ),
+ ),
+ )
+ .orderBy(asc(taskTable.id))
+ .for("update");
+ if (expectedTasks) {
+ const expected = new Map(expectedTasks.map((task) => [task.id, task]));
+ if (
+ expected.size !== expectedTasks.length ||
+ before.length !== expectedTasks.length ||
+ before.some((task) => {
+ const old = expected.get(task.id);
+ return (
+ !old || old.status !== task.status || old.position !== task.position
+ );
+ })
+ )
+ throw new HTTPException(409, {
+ message: "Board changed; refresh before reordering",
+ });
+ }
+ const requestedIds = new Set(tasks.map((task) => task.id));
+ if (
+ before.filter((task) => requestedIds.has(task.id)).length !== tasks.length
+ )
+ throw new HTTPException(404, {
+ message: "Tasks must belong to the requested project",
+ });
+ const values = tasks.map((task) => ({
+ id: task.id,
+ position: task.position,
+ status: task.status ?? null,
+ column_id:
+ task.status === undefined ? null : (columns.get(task.status) ?? null),
+ }));
+ // One JSON parameter keeps large boards below PostgreSQL's bind limit.
+ const after = await tx
+ .update(taskTable)
+ .set({
+ position: sql`changes.position`,
+ status: sql`coalesce(changes.status, ${taskTable.status})`,
+ columnId: sql`case when changes.status is null then ${taskTable.columnId} else changes.column_id end`,
+ })
+ .from(
+ sql`jsonb_to_recordset(${JSON.stringify(values)}::jsonb) as changes(id text, position integer, status text, column_id text)`,
+ )
+ .where(
+ and(
+ eq(taskTable.projectId, projectId),
+ sql`${taskTable.id} = changes.id`,
+ ),
+ )
+ .returning({
+ id: taskTable.id,
+ position: taskTable.position,
+ status: taskTable.status,
+ projectId: taskTable.projectId,
+ title: taskTable.title,
+ userId: taskTable.userId,
+ });
+ if (after.length !== tasks.length)
+ throw new HTTPException(409, {
+ message: "Task changed projects; retry the move",
+ });
+ return { before, after };
+ });
+ const beforeById = new Map(before.map((task) => [task.id, task]));
+ let statusChanged = false;
+ for (const updated of after) {
+ const prior = beforeById.get(updated.id)!;
+ if (prior.status !== updated.status) statusChanged = true;
+ await publishTaskMutation(prior, updated, userId, {
+ fields: ["status"],
+ skipRelationRefresh: true,
+ });
+ }
+ if (statusChanged)
+ await publishEvent("task-relation.refresh", { projectId, userId });
+ await publishEvent("tasks.reordered", {
+ projectId,
+ userId,
+ tasks: after.map(({ id, position, status }) => ({ id, position, status })),
+ });
+ return after.map(({ id, position, status }) => ({
+ id,
+ position: position ?? 0,
+ status,
+ }));
+}
diff --cc apps/web/src/components/kanban-board/apply-reorder.ts
index 0ac95c06c,000000000..757cb12ef
mode 100644,000000..100644
--- a/apps/web/src/components/kanban-board/apply-reorder.ts
+++ b/apps/web/src/components/kanban-board/apply-reorder.ts
@@@ -1,38 -1,0 +1,79 @@@
+import { produce } from "immer";
+import type { ProjectWithTasks } from "@/types/project";
+
+export function applyBoardReorder(
+ project: ProjectWithTasks,
- tasks: Array<{ id: string; position: number; status?: string }>,
++ tasks: Array<{ id: string; position: number | null; status?: string }>,
+): ProjectWithTasks {
+ const changes = new Map(tasks.map((task) => [task.id, task]));
+ return produce(project, (draft) => {
+ const moved: Array<{
+ task: (typeof draft.columns)[number]["tasks"][number];
+ slug: string;
+ }> = [];
+ for (const column of draft.columns) {
+ column.tasks = column.tasks.filter((task) => {
+ const change = changes.get(task.id);
+ if (!change) return true;
+ task.position = change.position;
+ if (change.status && change.status !== column.slug) {
+ const destination = draft.columns.find(
+ (column) => column.slug === change.status,
+ );
+ if (destination) {
+ task.status = change.status;
+ task.columnId = destination.id;
+ moved.push({ task, slug: change.status });
+ return false;
+ }
+ }
+ return true;
+ });
+ }
+ for (const { task, slug } of moved)
+ draft.columns.find((column) => column.slug === slug)?.tasks.push(task);
+ for (const column of draft.columns)
+ column.tasks.sort((a, b) => (a.position ?? 0) - (b.position ?? 0));
+ });
+}
++
++export function rollbackBoardReorder(
++ current: ProjectWithTasks,
++ previous: ProjectWithTasks,
++ tasks: Array<{ id: string; position: number; status?: string }>,
++) {
++ const prior = new Map(
++ previous.columns
++ .flatMap((column) => column.tasks)
++ .map((task) => [task.id, task]),
++ );
++ const cards = new Map(
++ current.columns
++ .flatMap((column) => column.tasks)
++ .map((task) => [task.id, task]),
++ );
++ if (
++ !tasks.every(
++ (change) =>
++ cards.get(change.id)?.position === change.position &&
++ cards.get(change.id)?.status ===
++ (change.status ?? prior.get(change.id)?.status),
++ )
++ )
++ return null;
++ return applyBoardReorder(
++ current,
++ tasks.flatMap((change) => {
++ const task = prior.get(change.id);
++ return task
++ ? [
++ {
++ id: task.id,
++ position: task.position ?? null,
++ status: task.status,
++ },
++ ]
++ : [];
++ }),
++ );
++}
diff --cc apps/web/src/components/kanban-board/index.tsx
index 4802a0274,4b5f04b93..d999995b8
--- a/apps/web/src/components/kanban-board/index.tsx
+++ b/apps/web/src/components/kanban-board/index.tsx
@@@ -15,12 -15,9 +15,13 @@@ import
} from "@dnd-kit/core";
import { useQueryClient } from "@tanstack/react-query";
import { useNavigate } from "@tanstack/react-router";
-import { produce } from "immer";
+import { useMutation } from "@tanstack/react-query";
- import reorderTasks from "@/fetchers/task/reorder-tasks";
++import reorderTasks, { type TaskReorder } from "@/fetchers/task/reorder-tasks";
+import { toast } from "@/lib/toast";
+import { useTranslation } from "react-i18next";
++import { rollbackBoardReorder } from "./apply-reorder";
+import { moveBoardTask } from "./move-task";
import { useEffect, useState } from "react";
-import { useUpdateTask } from "@/hooks/mutations/task/use-update-task";
import { useRegisterShortcuts } from "@/hooks/use-keyboard-shortcuts";
import { useProjectBackground } from "@/hooks/use-project-background";
import { cn } from "@/lib/cn";
@@@ -53,21 -50,7 +54,41 @@@ function KanbanBoard(
clearFocus,
} = useBulkSelectionStore();
const [activeId, setActiveId] = useState<UniqueIdentifier | null>(null);
- const { mutate: updateTask } = useUpdateTask();
+ const { t } = useTranslation();
+ const { mutate: reorder, isPending: isReordering } = useMutation({
- mutationFn: reorderTasks,
++ mutationFn: ({
++ previousBoard: _previousBoard,
++ ...request
++ }: TaskReorder & { previousBoard: ProjectWithTasks }) =>
++ reorderTasks(request),
++ onMutate: (variables) => ({ previousBoard: variables.previousBoard }),
+ onSuccess: (_result, variables) => {
+ void queryClient.invalidateQueries({
+ queryKey: ["tasks", variables.projectId],
+ });
+ for (const task of variables.tasks)
+ void queryClient.invalidateQueries({ queryKey: ["task", task.id] });
+ },
- onError: () => {
++ onError: (_error, variables, context) => {
++ const previous = context?.previousBoard;
++ if (previous) {
++ const current = queryClient.getQueryData<ProjectWithTasks>([
++ "tasks",
++ variables.projectId,
++ ]);
++ const restored = current
++ ? rollbackBoardReorder(current, previous, variables.tasks)
++ : null;
++ if (restored) {
++ queryClient.setQueryData(["tasks", variables.projectId], restored);
++ if (useProjectStore.getState().project?.id === variables.projectId)
++ setProject(restored);
++ }
++ }
+ toast.error(t("tasks:board.reorderFailed"));
+ void queryClient.invalidateQueries({ queryKey: ["tasks", project.id] });
+ },
+ });
const background = useProjectBackground({
backgroundVersion: project.backgroundVersion,
projectId: project.id,
@@@ -166,20 -149,120 +187,21 @@@
const activeId = active.id.toString();
const overId = over.id.toString();
- if (sortedByNumber) {
- const sourceColumn = project.columns.find((column) =>
- column.tasks.some((task) => task.id === activeId),
- );
- const destinationColumn = project.columns.find(
- (column) =>
- column.id === overId ||
- column.tasks.some((task) => task.id === overId),
- );
-
- if (
- !sourceColumn ||
- !destinationColumn ||
- sourceColumn.id === destinationColumn.id
- ) {
- return;
- }
-
- const currentProject = storedProject ?? project;
- const currentDestination = currentProject.columns.find(
- (column) => column.id === destinationColumn.id,
- );
- const position =
- Math.max(
- -1,
- ...(currentDestination?.tasks.map((task) => task.position ?? -1) ??
- []),
- ) + 1;
- const updatedProject = produce(currentProject, (draft) => {
- const source = draft.columns.find((column) =>
- column.tasks.some((task) => task.id === activeId),
- );
- const destination = draft.columns.find(
- (column) => column.id === destinationColumn.id,
- );
- if (!source || !destination) return;
-
- const taskIndex = source.tasks.findIndex(
- (task) => task.id === activeId,
- );
- const [task] = source.tasks.splice(taskIndex, 1);
- task.status = destination.slug;
- task.position = position;
- destination.tasks.push(task);
- });
-
- const movedTask = updatedProject.columns
- .find((column) => column.id === destinationColumn.id)
- ?.tasks.find((task) => task.id === activeId);
- if (!movedTask) return;
-
- setProject(updatedProject);
- updateTask(movedTask);
- return;
- }
-
- const updatedProject = produce(project, (draft) => {
- const sourceColumn = draft?.columns?.find((col) =>
- col.tasks.some((task) => task.id === activeId),
- );
- const destinationColumn = draft?.columns?.find(
- (col) =>
- col.id === overId || col.tasks.some((task) => task.id === overId),
- );
-
- if (!sourceColumn || !destinationColumn) return;
-
- const sourceTaskIndex = sourceColumn.tasks.findIndex(
- (task) => task.id === activeId,
- );
- const task = sourceColumn.tasks[sourceTaskIndex];
-
- sourceColumn.tasks = sourceColumn.tasks.filter((t) => t.id !== activeId);
-
- if (sourceColumn.id === destinationColumn.id) {
- let destinationIndex = destinationColumn.tasks.findIndex(
- (t) => t.id === overId,
- );
- if (sourceTaskIndex <= destinationIndex) {
- destinationIndex += 1;
- }
- destinationColumn.tasks.splice(destinationIndex, 0, task);
-
- destinationColumn.tasks.forEach((t, index) => {
- updateTask({ ...t, position: index });
- });
-
- queryClient.invalidateQueries({
- queryKey: ["projects", project.workspaceId],
- });
- } else {
- // A task's status is a column slug. The column id is only the
- // droppable identity here, and the two are interchangeable only
- // because the tasks endpoint happens to return `id: column.slug`.
- task.status = destinationColumn.slug;
- const destinationIndex =
- overId === destinationColumn.id
- ? destinationColumn.tasks.length
- : destinationColumn.tasks.findIndex((t) => t.id === overId) + 1;
-
- destinationColumn.tasks.splice(destinationIndex, 0, task);
-
- destinationColumn.tasks.forEach((t, index) => {
- updateTask({ ...t, status: destinationColumn.slug, position: index });
- });
-
- sourceColumn.tasks.forEach((t, index) => {
- updateTask({ ...t, position: index });
- });
- }
+ if (isReordering) return;
+ const canonical =
+ queryClient.getQueryData<ProjectWithTasks>(["tasks", project.id]) ??
+ (storedProject?.id === project.id ? storedProject : undefined);
+ if (!canonical) return;
+ const moved = moveBoardTask(canonical, activeId, overId, sortedByNumber);
+ if (!moved || !moved.tasks.length) return;
+ setProject(moved.project);
+ queryClient.setQueryData(["tasks", project.id], moved.project);
+ reorder({
+ projectId: project.id,
+ tasks: moved.tasks,
+ expectedTasks: moved.expectedTasks,
++ previousBoard: canonical,
});
-
- setProject(updatedProject);
- setActiveId(null);
};
if (!project?.columns) {
diff --cc apps/web/src/components/kanban-board/move-task.test.ts
index da3e97555,000000000..85f51df78
mode 100644,000000..100644
--- a/apps/web/src/components/kanban-board/move-task.test.ts
+++ b/apps/web/src/components/kanban-board/move-task.test.ts
@@@ -1,93 -1,0 +1,121 @@@
- import { applyBoardReorder } from "./apply-reorder";
++import { applyBoardReorder, rollbackBoardReorder } from "./apply-reorder";
+import { describe, expect, it } from "vite-plus/test";
+import type { ProjectWithTasks } from "@/types/project";
+import { moveBoardTask } from "./move-task";
+
+function board() {
+ return {
+ id: "project",
+ columns: [
+ {
+ id: "todo",
+ slug: "todo",
+ tasks: [
+ { id: "a", status: "todo", position: 0, title: "keep a" },
+ { id: "hidden", status: "todo", position: 1, title: "keep hidden" },
+ { id: "b", status: "todo", position: 2, title: "keep b" },
+ ],
+ },
+ {
+ id: "doing",
+ slug: "doing",
+ tasks: [{ id: "c", status: "doing", position: 0 }],
+ },
+ ],
+ plannedTasks: [],
+ archivedTasks: [],
+ } as unknown as ProjectWithTasks;
+}
+
+describe("board moves", () => {
+ it("preserves hidden tasks while producing only focused ordering changes", () => {
+ const original = board();
+ const moved = moveBoardTask(original, "a", "b")!;
+ expect(moved.project.columns[0].tasks.map((task) => task.id)).toEqual([
+ "hidden",
+ "b",
+ "a",
+ ]);
+ expect(moved.project.columns[0].tasks.map((task) => task.title)).toEqual([
+ "keep hidden",
+ "keep b",
+ "keep a",
+ ]);
+ expect(moved.tasks).toEqual([
+ { id: "hidden", position: 0 },
+ { id: "b", position: 1 },
+ { id: "a", position: 2 },
+ ]);
+ expect(original.columns[0].tasks[0].id).toBe("a");
+ });
+
+ it("moves across columns without copying unrelated task fields", () => {
+ const moved = moveBoardTask(board(), "a", "doing")!;
+ expect(moved.tasks).toContainEqual({
+ id: "a",
+ position: 1,
+ status: "doing",
+ });
+ expect(
+ moved.tasks.every((task) =>
+ Object.keys(task).every((key) =>
+ ["id", "position", "status"].includes(key),
+ ),
+ ),
+ ).toBe(true);
+ expect(moved.project.columns[1].tasks.map((task) => task.id)).toEqual([
+ "c",
+ "a",
+ ]);
+ });
+
+ it("updates only the moved task on a board sorted by task number", () => {
+ expect(moveBoardTask(board(), "a", "doing", true)?.tasks).toEqual([
+ { id: "a", position: 1, status: "doing" },
+ ]);
+ });
+});
+
+it("patches a remote reorder without removing hidden cards or replacing concurrent fields", () => {
+ const current = board();
+ current.columns[0].tasks[0].title = "concurrent title";
+ const updated = applyBoardReorder(current, [
+ { id: "a", position: 1, status: "doing" },
+ { id: "b", position: 0 },
+ ]);
+ expect(updated.columns[0].tasks.map((task) => task.id)).toEqual([
+ "b",
+ "hidden",
+ ]);
+ expect(updated.columns[1].tasks.map((task) => task.id)).toEqual(["c", "a"]);
+ expect(updated.columns[1].tasks[1].title).toBe("concurrent title");
+ expect(current.columns[0].tasks).toHaveLength(3);
+});
++
++it("rolls back a failed drag while preserving a newer title edit", () => {
++ const previous = board();
++ const moved = moveBoardTask(previous, "a", "doing")!;
++ const current = structuredClone(moved.project);
++ const card = current.columns
++ .flatMap((column) => column.tasks)
++ .find((task) => task.id === "a")!;
++ card.title = "new title";
++ const restored = rollbackBoardReorder(current, previous, moved.tasks)!;
++ expect(
++ restored.columns[0].tasks.find((task) => task.id === "a"),
++ ).toMatchObject({
++ title: "new title",
++ status: "todo",
++ position: previous.columns[0].tasks.find((task) => task.id === "a")!
++ .position,
++ });
++});
++it("preserves a newer remote order instead of rolling it back", () => {
++ const previous = board();
++ const moved = moveBoardTask(previous, "a", "doing")!;
++ const current = structuredClone(moved.project);
++ current.columns
++ .flatMap((column) => column.tasks)
++ .find((task) => task.id === "a")!.position = 99;
++ expect(rollbackBoardReorder(current, previous, moved.tasks)).toBeNull();
++});