⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
fix(board): reconcile full boards and deliver compact reorders
Tinafdcad33a627
diff --git a/apps/api/src/task/controllers/reorder-tasks.ts b/apps/api/src/task/controllers/reorder-tasks.tsindex 5aae0ebd0..1a3bf115c 100644--- a/apps/api/src/task/controllers/reorder-tasks.ts+++ b/apps/api/src/task/controllers/reorder-tasks.ts@@ -1,4 +1,4 @@-import { and, eq, getTableColumns, inArray, sql } from "drizzle-orm";+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";@@ -36,7 +36,7 @@ export default async function reorderTasks(// 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({ ...getTableColumns(taskTable), description: sql<null>`null` })+ .select({ id: taskTable.id, status: taskTable.status }).from(taskTable).where(and(@@ -47,48 +47,43 @@ export default async function reorderTasks(),),)+ .orderBy(asc(taskTable.id)).for("update");if (before.length !== tasks.length)throw new HTTPException(404, {message: "Tasks must belong to the requested project",});- const statusChanges = tasks.filter(- (task): task is Reorder & { status: string } => task.status !== undefined,- );- const position = sql<number>`case ${taskTable.id} ${sql.join(- tasks.map((task) => sql`when ${task.id} then ${task.position}::integer`),- sql` `,- )} else ${taskTable.position} end`;- const status = statusChanges.length- ? sql<string>`case ${taskTable.id} ${sql.join(- statusChanges.map((task) => sql`when ${task.id} then ${task.status}`),- sql` `,- )} else ${taskTable.status} end`- : undefined;- const columnId = statusChanges.length- ? sql<string | null>`case ${taskTable.id} ${sql.join(- statusChanges.map(- (task) =>- sql`when ${task.id} then ${columns.get(task.status) ?? null}`,- ),- sql` `,- )} else ${taskTable.columnId} end`- : undefined;+ 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, ...(statusChanges.length ? { status, columnId } : {}) })+ .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),- inArray(- taskTable.id,- tasks.map((task) => task.id),- ),+ sql`${taskTable.id} = changes.id`,),).returning({- ...getTableColumns(taskTable),- description: sql<null>`null`,+ 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, {@@ -96,19 +91,26 @@ export default async function reorderTasks(});return { before, after };});- for (const updated of after)- await publishTaskMutation(- {- ...before.find((task) => task.id === updated.id)!,- description: undefined,- },- updated,- userId,- );+ 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((task) => ({ ...task, descriptionDeferred: true }));+ return after.map(({ id, position, status }) => ({+ id,+ position: position ?? 0,+ status,+ }));}diff --git a/apps/api/src/task/index.ts b/apps/api/src/task/index.tsindex c6ed6caa3..966fa9dec 100644--- a/apps/api/src/task/index.ts+++ b/apps/api/src/task/index.ts@@ -14,6 +14,7 @@ import {createRoute,errorResponse,jsonResponse,+ z,} from "../openapi";import {assertTaskImageKeyMatchesContext,@@ -170,7 +171,12 @@ const reorderTasksRoute = createRoute({},},responses: {- 200: jsonResponse("Updated cards", taskSchema.array()),+ 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"),diff --git a/apps/api/src/task/schema.ts b/apps/api/src/task/schema.tsindex ea1922fec..76ef4d91d 100644--- a/apps/api/src/task/schema.ts+++ b/apps/api/src/task/schema.ts@@ -168,6 +168,5 @@ export const reorderTasksBody = z.object({status: z.string().optional(),}),)- .min(1)- .max(1000),+ .min(1),});diff --git a/apps/docs/openapi.json b/apps/docs/openapi.jsonindex bd4519ddc..539904536 100644--- a/apps/docs/openapi.json+++ b/apps/docs/openapi.json@@ -8600,8 +8600,7 @@"position"]},- "minItems": 1,- "maxItems": 1000+ "minItems": 1}},"required": [@@ -8614,13 +8613,29 @@},"responses": {"200": {- "description": "Updated cards",+ "description": "Updated card positions and statuses","content": {"application/json": {"schema": {"type": "array","items": {- "$ref": "#/components/schemas/Task"+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "position": {+ "type": "number"+ },+ "status": {+ "type": "string"+ }+ },+ "required": [+ "id",+ "position",+ "status"+ ]}}}diff --git a/apps/web/src/components/kanban-board/apply-reorder.ts b/apps/web/src/components/kanban-board/apply-reorder.tsnew file mode 100644index 000000000..0ac95c06c--- /dev/null+++ b/apps/web/src/components/kanban-board/apply-reorder.ts@@ -0,0 +1,38 @@+import { produce } from "immer";+import type { ProjectWithTasks } from "@/types/project";++export function applyBoardReorder(+ project: ProjectWithTasks,+ tasks: Array<{ id: string; position: number; 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));+ });+}diff --git a/apps/web/src/components/kanban-board/index.tsx b/apps/web/src/components/kanban-board/index.tsxindex 19e58bd74..a5d20c866 100644--- a/apps/web/src/components/kanban-board/index.tsx+++ b/apps/web/src/components/kanban-board/index.tsx@@ -56,6 +56,13 @@ function KanbanBoard({const { t } = useTranslation();const { mutate: reorder, isPending: isReordering } = useMutation({mutationFn: reorderTasks,+ onSuccess: (_result, variables) => {+ void queryClient.invalidateQueries({+ queryKey: ["tasks", variables.projectId],+ });+ for (const task of variables.tasks)+ void queryClient.invalidateQueries({ queryKey: ["task", task.id] });+ },onError: () => {toast.error(t("tasks:board.reorderFailed"));void queryClient.invalidateQueries({ queryKey: ["tasks", project.id] });@@ -161,9 +168,9 @@ function KanbanBoard({if (isReordering) return;const canonical =- sortedByNumber && storedProject?.id === project.id- ? storedProject- : project;+ 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);diff --git a/apps/web/src/components/kanban-board/move-task.test.ts b/apps/web/src/components/kanban-board/move-task.test.tsindex 74e303d58..da3e97555 100644--- a/apps/web/src/components/kanban-board/move-task.test.ts+++ b/apps/web/src/components/kanban-board/move-task.test.ts@@ -1,3 +1,4 @@+import { applyBoardReorder } from "./apply-reorder";import { describe, expect, it } from "vite-plus/test";import type { ProjectWithTasks } from "@/types/project";import { moveBoardTask } from "./move-task";@@ -74,3 +75,19 @@ describe("board moves", () => {]);});});++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);+});diff --git a/apps/web/src/hooks/use-project-websocket-lifecycle.test.tsx b/apps/web/src/hooks/use-project-websocket-lifecycle.test.tsxindex ae642ab48..6acbf54aa 100644--- a/apps/web/src/hooks/use-project-websocket-lifecycle.test.tsx+++ b/apps/web/src/hooks/use-project-websocket-lifecycle.test.tsx@@ -10,7 +10,7 @@ import {import { useProjectWebSocket } from "./use-project-websocket";const { client, auth } = vi.hoisted(() => ({- client: { invalidateQueries: vi.fn() },+ client: { invalidateQueries: vi.fn(), setQueryData: vi.fn() },auth: { userId: "user-a" as string | null },}));vi.mock("@tanstack/react-query", () => ({ useQueryClient: () => client }));@@ -52,6 +52,7 @@ describe("project WebSocket lifecycle", () => {TestSocket.instances = [];auth.userId = "user-a";client.invalidateQueries.mockClear();+ client.setQueryData.mockClear();});afterEach(() => {cleanup();@@ -60,6 +61,31 @@ describe("project WebSocket lifecycle", () => {vi.unstubAllEnvs();});+ it("patches a reordered batch and invalidates each task detail without reloading the board", () => {+ renderHook(() => useProjectWebSocket("project-a"));+ const tasks = [+ { id: "one", position: 1 },+ { id: "two", position: 0 },+ ];+ act(() => {+ TestSocket.instances[0].onmessage?.({+ data: JSON.stringify({+ type: "TASKS_REORDERED",+ projectId: "project-a",+ tasks,+ }),+ });+ });+ expect(client.setQueryData).toHaveBeenCalledWith(+ ["tasks", "project-a"],+ expect.any(Function),+ );+ expect(client.invalidateQueries.mock.calls).toEqual([+ [{ queryKey: ["task", "one"] }],+ [{ queryKey: ["task", "two"] }],+ ]);+ });+it("ignores late old-project events without stopping the new project's keepalive", () => {const { rerender, unmount } = renderHook(({ id }) => useProjectWebSocket(id),diff --git a/apps/web/src/hooks/use-project-websocket.ts b/apps/web/src/hooks/use-project-websocket.tsindex bb4ea6e4a..f52da8eb3 100644--- a/apps/web/src/hooks/use-project-websocket.ts+++ b/apps/web/src/hooks/use-project-websocket.ts@@ -1,3 +1,5 @@+import { applyBoardReorder } from "@/components/kanban-board/apply-reorder";+import type { ProjectWithTasks } from "@/types/project";import { windowId } from "@kaneo/libs";import { useQueryClient } from "@tanstack/react-query";import { useEffect } from "react";@@ -62,6 +64,16 @@ export function useProjectWebSocket(projectId: string) {if (disposed || activeSocket !== ws) return;try {const message = JSON.parse(event.data);+ if (message.type === "TASKS_REORDERED") {+ queryClient.setQueryData<ProjectWithTasks>(+ ["tasks", message.projectId],+ (project) =>+ project ? applyBoardReorder(project, message.tasks) : project,+ );+ for (const task of message.tasks)+ queryClient.invalidateQueries({ queryKey: ["task", task.id] });+ return;+ }if (message.type === "PROJECT_MOVED") {for (const queryKey of [["projects"],@@ -75,7 +87,6 @@ export function useProjectWebSocket(projectId: string) {return;}if (- message.type === "TASKS_REORDERED" ||message.type === "TASK_UPDATED" ||message.type === "TASK_CREATED" ||message.type === "TASK_DELETED" ||diff --git a/tests/api-integration/task-reorder.test.ts b/tests/api-integration/task-reorder.test.tsindex 9938e81c4..f2de96d2f 100644--- a/tests/api-integration/task-reorder.test.ts+++ b/tests/api-integration/task-reorder.test.ts@@ -30,11 +30,14 @@ describe("atomic card reordering", () => {position: 3,}).returning();- await reorderTasks(+ 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),@@ -78,3 +81,33 @@ describe("atomic card reordering", () => {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);+});diff --git a/tests/api/ws/reorder-delivery.test.ts b/tests/api/ws/reorder-delivery.test.tsnew file mode 100644index 000000000..b0d21235f--- /dev/null+++ b/tests/api/ws/reorder-delivery.test.ts@@ -0,0 +1,58 @@+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 },+ );+ 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);+ }+});