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(board): reject stale drag snapshots and retain reorder batches

Tin82f40d64ee16
diff --cc apps/api/src/task/controllers/reorder-tasks.ts
index 1a3bf115c,000000000..d449436eb
mode 100644,000000..100644
--- a/apps/api/src/task/controllers/reorder-tasks.ts
+++ b/apps/api/src/task/controllers/reorder-tasks.ts
@@@ -1,116 -1,0 +1,151 @@@
+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 { 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'))`,
++ );
+ // 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 })
++ .select({
++ id: taskTable.id,
++ status: taskTable.status,
++ position: taskTable.position,
++ })
+ .from(taskTable)
+ .where(
+ and(
+ eq(taskTable.projectId, projectId),
- inArray(
- taskTable.id,
- tasks.map((task) => task.id),
- ),
++ 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 (before.length !== tasks.length)
++ 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/api/src/task/index.ts
index 966fa9dec,c96540e0e..acb737dfa
--- a/apps/api/src/task/index.ts
+++ b/apps/api/src/task/index.ts
@@@ -151,38 -148,6 +151,40 @@@ const bulkUpdateTasksRoute = createRout
},
});
+const reorderTasksRoute = createRoute({
+ method: "post",
+ operationId: "reorderTasks",
+ path: "/reorder",
+ tags: ["Tasks"],
+ summary: "Reorder or move cards",
+ description:
+ "Atomically update positions and optional column status for cards in one project. Other task fields are preserved.",
+ middleware: [
+ workspaceAccess.fromProject("projectId"),
+ requireWorkspacePermission({ task: ["update"] }),
+ requireEntitlement,
+ ] as const,
+ request: {
+ body: {
+ required: true,
+ content: { "application/json": { schema: reorderTasksBody } },
+ },
+ },
+ responses: {
+ 200: jsonResponse(
+ "Updated card positions and statuses",
+ z
+ .object({ id: z.string(), position: z.number(), status: z.string() })
+ .array(),
+ ),
+ 400: errorResponse("Invalid positions or column"),
+ 403: errorResponse("Missing task:update permission"),
+ 404: errorResponse("Tasks do not belong to the project"),
- 409: errorResponse("Task moved concurrently"),
++ 409: errorResponse(
++ "Board changed or task moved; refresh before reordering",
++ ),
+ },
+});
const createTaskRoute = createRoute({
method: "post",
operationId: "createTask",
@@@ -734,10 -699,6 +736,13 @@@ const task = apiRouter<BaseVariables &
return c.json(result, 200);
})
+ .openapi(reorderTasksRoute, async (c) => {
- const { projectId, tasks } = c.req.valid("json");
- return c.json(await reorderTasks(projectId, tasks, c.get("userId")), 200);
++ const { projectId, tasks, expectedTasks } = c.req.valid("json");
++ return c.json(
++ await reorderTasks(projectId, tasks, c.get("userId"), expectedTasks),
++ 200,
++ );
+ })
.openapi(createTaskRoute, async (c) => {
const { projectId } = c.req.param();
const {
diff --cc apps/api/src/task/schema.ts
index 76ef4d91d,ab85f70ee..ffd9ed122
--- a/apps/api/src/task/schema.ts
+++ b/apps/api/src/task/schema.ts
@@@ -157,16 -157,3 +157,28 @@@ export const descriptionMatchesQuery =
});
export const duplicateTaskBody = z.object({ title: z.string().optional() });
+
+export const reorderTasksBody = z.object({
+ projectId: z.string(),
++ expectedTasks: z
++ .array(
++ z.object({
++ id: z.string(),
++ position: z.number().int().min(0).max(MAX_TASK_POSITION).nullable(),
++ status: z.string(),
++ }),
++ )
++ .optional()
++ .describe(
++ "Previous complete contents of the affected columns; stale snapshots return 409",
++ ),
+ tasks: z
+ .array(
+ z.object({
+ id: z.string(),
+ position: z.number().int().min(0).max(MAX_TASK_POSITION),
+ status: z.string().optional(),
+ }),
+ )
+ .min(1),
+});
diff --cc apps/api/src/ws/index.ts
index 7be140434,414db106c..276c4c235
--- a/apps/api/src/ws/index.ts
+++ b/apps/api/src/ws/index.ts
@@@ -297,7 -297,7 +297,7 @@@ export function broadcastToProject
projectBroadcastQueues.set(projectId, new Map());
}
-- const messageKey = `${message.type}:${message.taskId ?? ""}:${message.sourceTaskId ?? ""}:${message.targetTaskId ?? ""}`;
++ const messageKey = `${message.type === "TASKS_REORDERED" ? `${message.type}:${crypto.randomUUID()}` : message.type}:${message.taskId ?? ""}:${message.sourceTaskId ?? ""}:${message.targetTaskId ?? ""}`;
projectBroadcastQueues
.get(projectId)
?.set(messageKey, { message, excludeInitiatorId });
diff --cc apps/docs/openapi.json
index 539904536,c6b61c790..5e8717f2b
--- a/apps/docs/openapi.json
+++ b/apps/docs/openapi.json
@@@ -8556,133 -8556,6 +8556,161 @@@
}
}
}
+ }
+ }
+ }
+ },
+ "/task/reorder": {
+ "post": {
+ "operationId": "reorderTasks",
+ "tags": [
+ "Tasks"
+ ],
+ "summary": "Reorder or move cards",
+ "description": "Atomically update positions and optional column status for cards in one project. Other task fields are preserved.",
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object",
+ "properties": {
+ "projectId": {
+ "type": "string"
+ },
++ "expectedTasks": {
++ "type": "array",
++ "items": {
++ "type": "object",
++ "properties": {
++ "id": {
++ "type": "string"
++ },
++ "position": {
++ "type": [
++ "integer",
++ "null"
++ ],
++ "minimum": 0,
++ "maximum": 2147483646
++ },
++ "status": {
++ "type": "string"
++ }
++ },
++ "required": [
++ "id",
++ "position",
++ "status"
++ ]
++ },
++ "description": "Previous complete contents of the affected columns; stale snapshots return 409"
++ },
+ "tasks": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "position": {
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 2147483646
+ },
+ "status": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "id",
+ "position"
+ ]
+ },
+ "minItems": 1
+ }
+ },
+ "required": [
+ "projectId",
+ "tasks"
+ ]
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "Updated card positions and statuses",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "position": {
+ "type": "number"
+ },
+ "status": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "id",
+ "position",
+ "status"
+ ]
+ }
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid positions or column",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "Missing or invalid credentials"
+ },
+ "403": {
+ "description": "Missing task:update permission",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "Tasks do not belong to the project",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "409": {
- "description": "Task moved concurrently",
++ "description": "Board changed or task moved; refresh before reordering",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
}
}
}
diff --cc apps/web/src/components/kanban-board/index.tsx
index a5d20c866,4b5f04b93..4802a0274
--- a/apps/web/src/components/kanban-board/index.tsx
+++ b/apps/web/src/components/kanban-board/index.tsx
@@@ -166,16 -149,120 +166,20 @@@ function KanbanBoard(
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 });
++ reorder({
++ projectId: project.id,
++ tasks: moved.tasks,
++ expectedTasks: moved.expectedTasks,
+ });
-
- setProject(updatedProject);
- setActiveId(null);
};
if (!project?.columns) {
diff --cc apps/web/src/components/kanban-board/move-task.ts
index 3b4bd66dc,000000000..36ef926c2
mode 100644,000000..100644
--- a/apps/web/src/components/kanban-board/move-task.ts
+++ b/apps/web/src/components/kanban-board/move-task.ts
@@@ -1,67 -1,0 +1,76 @@@
+import { produce } from "immer";
+import type { ProjectWithTasks } from "@/types/project";
+
+export function moveBoardTask(
+ project: ProjectWithTasks,
+ activeId: string,
+ overId: string,
+ sortedByNumber = false,
+) {
+ const source = project.columns.find((column) =>
+ column.tasks.some((task) => task.id === activeId),
+ );
+ const destination = project.columns.find(
+ (column) =>
+ column.id === overId || column.tasks.some((task) => task.id === overId),
+ );
+ if (
+ !source ||
+ !destination ||
+ activeId === overId ||
+ (sortedByNumber && source.id === destination.id)
+ )
+ return null;
+ const next = produce(project, (draft) => {
+ const from = draft.columns.find((column) => column.id === source.id)!;
+ const to = draft.columns.find((column) => column.id === destination.id)!;
+ const sourceIndex = from.tasks.findIndex((task) => task.id === activeId);
+ const [task] = from.tasks.splice(sourceIndex, 1);
+ task.status = to.slug;
+ if (sortedByNumber) {
+ task.position =
+ Math.max(-1, ...to.tasks.map((task) => task.position ?? -1)) + 1;
+ to.tasks.push(task);
+ return;
+ }
+ let index =
+ overId === to.id
+ ? to.tasks.length
+ : to.tasks.findIndex((task) => task.id === overId);
+ if (from.id !== to.id || sourceIndex <= index)
+ index += overId === to.id ? 0 : 1;
+ to.tasks.splice(index, 0, task);
+ for (const column of new Set([from, to]))
+ column.tasks.forEach((task, position) => {
+ task.position = position;
+ });
+ });
+ const previous = new Map(
+ project.columns
+ .flatMap((column) => column.tasks)
+ .map((task) => [task.id, task]),
+ );
+ const tasks = next.columns
+ .flatMap((column) => column.tasks)
+ .filter((task) => {
+ const old = previous.get(task.id);
+ return old?.position !== task.position || old.status !== task.status;
+ })
+ .map((task) => ({
+ id: task.id,
+ position: task.position ?? 0,
+ ...(previous.get(task.id)?.status !== task.status
+ ? { status: task.status }
+ : {}),
+ }));
- return { project: next, tasks };
++ const expectedTasks = project.columns
++ .filter((column) => column.id === source.id || column.id === destination.id)
++ .flatMap((column) =>
++ column.tasks.map((task) => ({
++ id: task.id,
++ position: task.position ?? null,
++ status: task.status,
++ })),
++ );
++ return { project: next, tasks, expectedTasks };
+}
diff --cc apps/web/src/fetchers/task/reorder-tasks.ts
index 9f3df66c7,000000000..54ece9845
mode 100644,000000..100644
--- a/apps/web/src/fetchers/task/reorder-tasks.ts
+++ b/apps/web/src/fetchers/task/reorder-tasks.ts
@@@ -1,12 -1,0 +1,13 @@@
+import { client } from "@kaneo/libs";
+import { HttpError } from "@/lib/http-error";
+
+export type TaskReorder = {
+ projectId: string;
++ expectedTasks?: { id: string; position: number | null; status: string }[];
+ tasks: { id: string; position: number; status?: string }[];
+};
+export default async function reorderTasks(json: TaskReorder) {
+ const response = await client.task.reorder.$post({ json });
+ if (!response.ok) throw new HttpError(response.status, await response.text());
+ return response.json();
+}
diff --cc tests/api-integration/task-reorder.test.ts
index f2de96d2f,000000000..0bed1a798
mode 100644,000000..100644
--- a/tests/api-integration/task-reorder.test.ts
+++ b/tests/api-integration/task-reorder.test.ts
@@@ -1,113 -1,0 +1,159 @@@
+import { eq } from "drizzle-orm";
+import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
+import db, { schema } from "../../apps/api/src/database";
+import reorderTasks from "../../apps/api/src/task/controllers/reorder-tasks";
+import { resetTestDatabase } from "./helpers/database";
+import {
+ createProjectFixture,
+ createWorkspaceMember,
+} from "./helpers/fixtures";
+const publish = vi.hoisted(() => vi.fn(async () => undefined));
+vi.mock("../../apps/api/src/events", () => ({ publishEvent: publish }));
+beforeEach(async () => {
+ await resetTestDatabase();
+ vi.clearAllMocks();
+});
+describe("atomic card reordering", () => {
+ it("preserves fields edited since the board snapshot", async () => {
+ const { user, workspace } = await createWorkspaceMember();
+ const { project } = await createProjectFixture({
+ workspaceId: workspace.id,
+ });
+ const [task] = await db
+ .insert(schema.taskTable)
+ .values({
+ projectId: project.id,
+ title: "Another person's new title",
+ description: "latest text",
+ priority: "urgent",
+ status: "to-do",
+ position: 3,
+ })
+ .returning();
+ const result = await reorderTasks(
+ project.id,
+ [{ id: task.id, position: 1, status: "in-progress" }],
+ user.id,
+ );
+ expect(result).toEqual([
+ { id: task.id, position: 1, status: "in-progress" },
+ ]);
+ expect(
+ await db.query.taskTable.findFirst({
+ where: eq(schema.taskTable.id, task.id),
+ }),
+ ).toMatchObject({
+ title: task.title,
+ description: task.description,
+ priority: task.priority,
+ position: 1,
+ status: "in-progress",
+ });
+ expect(
+ publish.mock.calls.filter(([event]) => event === "tasks.reordered"),
+ ).toHaveLength(1);
+ });
+ it("rejects a card in another project without changing any positions", async () => {
+ const { user, workspace } = await createWorkspaceMember();
+ const a = await createProjectFixture({ workspaceId: workspace.id });
+ const b = await createProjectFixture({ workspaceId: workspace.id });
+ const tasks = await db
+ .insert(schema.taskTable)
+ .values([
+ { projectId: a.project.id, title: "a", status: "to-do", position: 3 },
+ { projectId: b.project.id, title: "b", status: "to-do", position: 4 },
+ ])
+ .returning();
+ await expect(
+ reorderTasks(
+ a.project.id,
+ tasks.map((task) => ({ id: task.id, position: 0 })),
+ user.id,
+ ),
+ ).rejects.toThrow("Tasks must belong");
+ expect(
+ (
+ await db.query.taskTable.findFirst({
+ where: eq(schema.taskTable.id, tasks[0].id),
+ })
+ )?.position,
+ ).toBe(3);
+ expect(publish).not.toHaveBeenCalled();
+ });
+});
+
+it("atomically reorders more than 1,000 supported cards", async () => {
+ const { user, workspace } = await createWorkspaceMember();
+ const { project } = await createProjectFixture({ workspaceId: workspace.id });
+ const tasks = await db
+ .insert(schema.taskTable)
+ .values(
+ Array.from({ length: 1001 }, (_, i) => ({
+ projectId: project.id,
+ title: `card-${i}`,
+ number: i + 1,
+ position: i,
+ status: "to-do",
+ })),
+ )
+ .returning({ id: schema.taskTable.id });
+ const result = await reorderTasks(
+ project.id,
+ tasks.map((task, i) => ({ id: task.id, position: 1000 - i })),
+ user.id,
+ );
+ expect(result).toHaveLength(1001);
+ expect(
+ (
+ await db.query.taskTable.findFirst({
+ where: eq(schema.taskTable.id, tasks[0].id),
+ })
+ )?.position,
+ ).toBe(1000);
+});
++
++it("rejects a second drag from a stale column snapshot without duplicating positions", async () => {
++ const { user, workspace } = await createWorkspaceMember();
++ const { project } = await createProjectFixture({ workspaceId: workspace.id });
++ const tasks = await db
++ .insert(schema.taskTable)
++ .values(
++ Array.from({ length: 4 }, (_, position) => ({
++ projectId: project.id,
++ title: `card-${position}`,
++ number: position + 1,
++ position,
++ status: "to-do",
++ })),
++ )
++ .returning();
++ const expected = tasks.map((task) => ({
++ id: task.id,
++ position: task.position,
++ status: task.status,
++ }));
++ await reorderTasks(
++ project.id,
++ tasks.map((task, index) => ({
++ id: task.id,
++ position: index === 0 ? 3 : index - 1,
++ })),
++ user.id,
++ expected,
++ );
++ publish.mockClear();
++ await expect(
++ reorderTasks(
++ project.id,
++ [{ id: tasks[1].id, position: 3 }],
++ user.id,
++ expected,
++ ),
++ ).rejects.toMatchObject({ status: 409 });
++ const current = await db
++ .select()
++ .from(schema.taskTable)
++ .where(eq(schema.taskTable.projectId, project.id));
++ expect(new Set(current.map((task) => task.position)).size).toBe(4);
++ expect(publish).not.toHaveBeenCalled();
++});
diff --cc tests/api/ws/reorder-delivery.test.ts
index b0d21235f,000000000..570adcae0
mode 100644,000000..100644
--- a/tests/api/ws/reorder-delivery.test.ts
+++ b/tests/api/ws/reorder-delivery.test.ts
@@@ -1,58 -1,0 +1,62 @@@
+import type { WSContext } from "hono/ws";
+import { afterEach, expect, it, vi } from "vite-plus/test";
+import { publishEvent } from "../../../apps/api/src/events";
+import {
+ addConnection,
+ initializeWebSocketAdapter,
+ removeConnection,
+ shutdownWebSocketAdapter,
+} from "../../../apps/api/src/ws";
+vi.mock("../../../apps/api/src/database", () => ({
+ default: {
+ select: () => ({
+ from: () => ({
+ where: () => ({ limit: async () => [{ workspaceId: "workspace" }] }),
+ }),
+ }),
+ },
+}));
+vi.mock("../../../apps/api/src/redis", () => ({
+ isRedisConfigured: () => false,
+ closeRedis: vi.fn(),
+}));
+afterEach(async () => {
+ await shutdownWebSocketAdapter();
+ vi.useRealTimers();
+});
- it("delivers the committed reorder batch through the real subscriber and local adapter", async () => {
- vi.useFakeTimers();
- await initializeWebSocketAdapter();
- const ws = { send: vi.fn(), close: vi.fn() };
- const connection = addConnection(
- "project",
- ws as unknown as WSContext,
- "observer",
- "window",
- "workspace",
- );
- const tasks = [
- { id: "one", position: 1, status: "to-do" },
- { id: "two", position: 0, status: "to-do" },
- ];
- try {
- await publishEvent(
- "tasks.reordered",
- { projectId: "project", userId: "actor", tasks },
- { waitForHandlers: true },
++it.each([1, 2])(
++ "delivers %i committed reorder batch through the real subscriber and local adapter",
++ async (batches) => {
++ vi.useFakeTimers();
++ await initializeWebSocketAdapter();
++ const ws = { send: vi.fn(), close: vi.fn() };
++ const connection = addConnection(
++ "project",
++ ws as unknown as WSContext,
++ "observer",
++ "window",
++ "workspace",
+ );
- await vi.advanceTimersByTimeAsync(100);
- expect(ws.send).toHaveBeenCalledOnce();
- expect(JSON.parse(ws.send.mock.calls[0][0])).toEqual({
- type: "TASKS_REORDERED",
- projectId: "project",
- tasks,
- });
- } finally {
- removeConnection("project", connection);
- }
- });
++ const tasks = [
++ { id: "one", position: 1, status: "to-do" },
++ { id: "two", position: 0, status: "to-do" },
++ ];
++ try {
++ for (let index = 0; index < batches; index++)
++ await publishEvent(
++ "tasks.reordered",
++ { projectId: "project", userId: "actor", tasks },
++ { waitForHandlers: true },
++ );
++ await vi.advanceTimersByTimeAsync(100);
++ expect(ws.send).toHaveBeenCalledTimes(batches);
++ expect(JSON.parse(ws.send.mock.calls[0][0])).toEqual({
++ type: "TASKS_REORDERED",
++ projectId: "project",
++ tasks,
++ });
++ } finally {
++ removeConnection("project", connection);
++ }
++ },
++);