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.

Preserve remote board changes during live local mutations

Tin0c46a5cdbb49
diff --cc apps/api/src/column/controllers/create-column.ts
index 5a608be6f,5a608be6f..35be40e35
--- a/apps/api/src/column/controllers/create-column.ts
+++ b/apps/api/src/column/controllers/create-column.ts
@@@ -1,3 -1,3 +1,4 @@@
++import { publishEvent } from "../../events";
import { eq, sql } from "drizzle-orm";
import { HTTPException } from "hono/http-exception";
import db from "../../database";
@@@ -81,6 -81,6 +82,8 @@@ async function createColumn(
throw new HTTPException(500, { message: "Failed to create column" });
}
++ await publishEvent("project.updated", { projectId: created.projectId });
++
return created;
}
diff --cc apps/api/src/column/controllers/delete-column.ts
index a14fd0c38,a14fd0c38..5570a7aaf
--- a/apps/api/src/column/controllers/delete-column.ts
+++ b/apps/api/src/column/controllers/delete-column.ts
@@@ -1,3 -1,3 +1,4 @@@
++import { publishEvent } from "../../events";
import { eq, sql } from "drizzle-orm";
import { HTTPException } from "hono/http-exception";
import db from "../../database";
@@@ -26,6 -26,6 +27,8 @@@ async function deleteColumn(id: string
await db.delete(columnTable).where(eq(columnTable.id, id));
++ await publishEvent("project.updated", { projectId: existing.projectId });
++
return existing;
}
diff --cc apps/api/src/column/controllers/reorder-columns.ts
index c8f10281e,c8f10281e..4533d082f
--- a/apps/api/src/column/controllers/reorder-columns.ts
+++ b/apps/api/src/column/controllers/reorder-columns.ts
@@@ -1,3 -1,3 +1,4 @@@
++import { publishEvent } from "../../events";
import { and, eq } from "drizzle-orm";
import { HTTPException } from "hono/http-exception";
import db from "../../database";
@@@ -28,6 -28,6 +29,8 @@@ async function reorderColumns
orderBy: (columns, { asc }) => [asc(columns.position)],
});
++ await publishEvent("project.updated", { projectId: projectId });
++
return updated;
}
diff --cc apps/api/src/column/controllers/update-column.ts
index 6c93c5e39,6c93c5e39..f42ebbeb1
--- a/apps/api/src/column/controllers/update-column.ts
+++ b/apps/api/src/column/controllers/update-column.ts
@@@ -50,6 -50,6 +50,8 @@@ async function updateColumn
});
}
++ await publishEvent("project.updated", { projectId: updated.projectId });
++
return updated;
}
diff --cc apps/web/src/hooks/use-project-websocket-cache.test.tsx
index 3174d879d,000000000..0db816552
mode 100644,000000..100644
--- a/apps/web/src/hooks/use-project-websocket-cache.test.tsx
+++ b/apps/web/src/hooks/use-project-websocket-cache.test.tsx
@@@ -1,299 -1,0 +1,343 @@@
+import { cleanup, renderHook } from "@testing-library/react";
+import {
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from "vite-plus/test";
+import { useProjectWebSocket } from "./use-project-websocket";
+
+const mocks = vi.hoisted(() => ({
+ board: null as unknown,
+ getTask: vi.fn(),
+ subscribe: vi.fn(),
+ client: {
+ getQueryCache: () => ({
+ subscribe: (listener: unknown) => {
+ mocks.subscribe(listener);
+ return () => {};
+ },
+ }),
+ getQueryState: vi.fn(),
+ getQueryData: vi.fn(),
+ setQueryData: vi.fn(),
+ invalidateQueries: vi.fn(),
+ cancelQueries: vi.fn().mockResolvedValue(undefined),
+ },
+}));
+vi.mock("@tanstack/react-query", () => ({
+ useQueryClient: () => mocks.client,
+}));
+vi.mock("@kaneo/libs", () => ({ windowId: "test" }));
+vi.mock("@/lib/auth-client", () => ({
+ authClient: { useSession: () => ({ data: { user: { id: "u" } } }) },
+}));
+vi.mock("@/fetchers/task/get-task", () => ({ default: mocks.getTask }));
+vi.mock("@/fetchers/label/get-labels-by-task", () => ({
+ default: () => Promise.resolve([]),
+}));
+vi.mock("@/fetchers/external-link/get-external-links", () => ({
+ default: () => Promise.resolve([]),
+}));
+
+class Socket {
+ static current: Socket;
+ onopen: (() => void) | null = null;
+ onclose: (() => void) | null = null;
+ onmessage: ((event: { data: string }) => void) | null = null;
+ close = vi.fn();
+ constructor() {
+ Socket.current = this;
+ }
+ message(type: string, rest: Record<string, unknown>) {
+ this.onmessage?.({
+ data: JSON.stringify({ type, projectId: "p", ...rest }),
+ });
+ }
+}
+
+beforeEach(() => {
+ vi.stubGlobal("WebSocket", Socket);
+ mocks.board = {
+ id: "p",
+ columns: [
+ {
+ id: "todo",
+ slug: "todo",
+ tasks: [{ id: "a", projectId: "p", status: "todo", position: 0 }],
+ },
+ { id: "doing", slug: "doing", tasks: [] },
+ ],
+ plannedTasks: [],
+ archivedTasks: [],
+ };
+ mocks.client.getQueryData.mockImplementation(() => mocks.board);
+ mocks.client.setQueryData.mockImplementation((_key, value) => {
+ mocks.board = typeof value === "function" ? value(mocks.board) : value;
+ });
+ mocks.client.invalidateQueries.mockClear();
+ mocks.client.getQueryState.mockReset();
+ mocks.subscribe.mockClear();
+});
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
+
+describe("board realtime races", () => {
+ it.each(["TASKS_REORDERED", "PROJECT_UPDATED", "TASK_RELATION_UPDATED"])(
+ "discards a task refresh started before %s",
+ async (type) => {
+ let finish!: (value: unknown) => void;
+ mocks.getTask.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ renderHook(() => useProjectWebSocket("p"));
+ Socket.current.message("TASK_UPDATED", { taskId: "a" });
+ Socket.current.message(type, {
+ tasks: [{ id: "a", position: 2, status: "doing" }],
+ });
+ const afterEvent = mocks.board;
+ finish({ id: "a", projectId: "p", status: "todo", position: 0 });
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(mocks.board).toBe(afterEvent);
+ if (type === "TASKS_REORDERED")
+ expect(
+ (mocks.board as { columns: { tasks: { id: string }[] }[] }).columns[1]
+ .tasks[0].id,
+ ).toBe("a");
+ },
+ );
+
+ it("coalesces updates while pagination finishes without restarting page one", async () => {
+ mocks.client.getQueryState.mockReturnValue({ fetchStatus: "fetching" });
+ mocks.getTask.mockReset();
+ mocks.getTask.mockResolvedValue({
+ id: "a",
+ projectId: "p",
+ status: "doing",
+ position: 2,
+ });
+ renderHook(() => useProjectWebSocket("p"));
+ Socket.current.message("TASK_UPDATED", { taskId: "a" });
+ Socket.current.message("TASK_UPDATED", { taskId: "a" });
+ expect(mocks.getTask).not.toHaveBeenCalled();
+ expect(mocks.client.invalidateQueries).not.toHaveBeenCalled();
+ mocks.client.getQueryState.mockReturnValue({ fetchStatus: "idle" });
+ mocks.subscribe.mock.calls[0][0]({
+ query: { queryKey: ["tasks", "p"], state: { fetchStatus: "idle" } },
+ });
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(mocks.getTask).toHaveBeenCalledExactlyOnceWith("a", "board");
+ expect(mocks.client.invalidateQueries).not.toHaveBeenCalledWith({
+ queryKey: ["tasks", "p"],
+ });
+ });
+
+ it("refreshes a project-wide task update with no task id", () => {
+ renderHook(() => useProjectWebSocket("p"));
+ Socket.current.message("TASK_UPDATED", { taskId: "" });
+ expect(mocks.client.invalidateQueries).toHaveBeenCalledWith({
+ queryKey: ["tasks", "p"],
+ });
+ });
+});
+
+it("reconciles the initial handshake after active pagination completes", async () => {
+ mocks.client.getQueryState.mockReturnValue({ fetchStatus: "fetching" });
+ renderHook(() => useProjectWebSocket("p"));
+ Socket.current.onopen?.();
+ await Promise.resolve();
+ expect(mocks.client.invalidateQueries).not.toHaveBeenCalled();
+ mocks.client.getQueryState.mockReturnValue({ fetchStatus: "idle" });
+ mocks.subscribe.mock.calls[0][0]({
+ query: { queryKey: ["tasks", "p"], state: { fetchStatus: "idle" } },
+ });
+ await Promise.resolve();
+ expect(mocks.client.invalidateQueries).toHaveBeenCalledExactlyOnceWith({
+ queryKey: ["tasks", "p"],
+ });
+});
+it("preserves distinct task effects across pagination and a disconnect before replay", async () => {
+ vi.useFakeTimers();
+ try {
+ mocks.client.getQueryState.mockReturnValue({ fetchStatus: "fetching" });
+ mocks.getTask.mockResolvedValue({
+ id: "a",
+ projectId: "p",
+ status: "todo",
+ });
+ renderHook(() => useProjectWebSocket("p"));
+ Socket.current.message("COMMENT_UPDATED", { taskId: "a" });
+ Socket.current.message("TASK_LABEL_UPDATED", { taskId: "a" });
+ mocks.client.getQueryState.mockReturnValue({ fetchStatus: "idle" });
+ mocks.subscribe.mock.calls[0][0]({
+ query: { queryKey: ["tasks", "p"], state: { fetchStatus: "idle" } },
+ });
+ Socket.current.onclose?.();
+ await Promise.resolve();
+ await vi.advanceTimersByTimeAsync(1000);
+ Socket.current.onopen?.();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(mocks.client.invalidateQueries).toHaveBeenCalledWith({
+ queryKey: ["comments", "a"],
+ });
+ expect(mocks.client.invalidateQueries).toHaveBeenCalledWith({
+ queryKey: ["labels", "a"],
+ });
+ } finally {
+ vi.useRealTimers();
+ }
+});
+
+it("does not overwrite a parent's newer progress with an older child's response", async () => {
+ let finish!: (value: unknown) => void;
+ mocks.getTask
+ .mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ )
+ .mockResolvedValueOnce({
+ id: "b",
+ projectId: "p",
+ status: "todo",
+ parentSubtaskCounts: [{ taskId: "a", completed: 2, total: 2 }],
+ });
+ renderHook(() => useProjectWebSocket("p"));
+ Socket.current.message("TASK_UPDATED", { taskId: "old-child" });
+ Socket.current.message("TASK_UPDATED", { taskId: "b" });
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+ finish({
+ id: "old-child",
+ projectId: "p",
+ status: "todo",
+ parentSubtaskCounts: [{ taskId: "a", completed: 1, total: 2 }],
+ });
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+ const task = (
+ mocks.board as {
+ columns: { tasks: { id: string; subtaskCounts?: unknown }[] }[];
+ }
+ ).columns[0].tasks.find((task) => task.id === "a");
+ expect(task?.subtaskCounts).toEqual({ completed: 2, total: 2 });
+ expect(mocks.client.invalidateQueries).toHaveBeenCalledWith({
+ queryKey: ["tasks", "p"],
+ });
+});
+
+it("preserves newer parent progress when an earlier parent refresh finishes last", async () => {
+ let finish!: (value: unknown) => void;
+ mocks.getTask
+ .mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ )
+ .mockResolvedValueOnce({
+ id: "b",
+ projectId: "p",
+ status: "todo",
+ parentSubtaskCounts: [{ taskId: "a", completed: 2, total: 2 }],
+ });
+ renderHook(() => useProjectWebSocket("p"));
+ Socket.current.message("TASK_UPDATED", { taskId: "a" });
+ Socket.current.message("TASK_UPDATED", { taskId: "b" });
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+ finish({
+ id: "a",
+ projectId: "p",
+ status: "todo",
+ subtaskCounts: { completed: 1, total: 2 },
+ });
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+ const task = (
+ mocks.board as {
+ columns: { tasks: { id: string; subtaskCounts?: unknown }[] }[];
+ }
+ ).columns[0].tasks.find((task) => task.id === "a");
+ expect(task?.subtaskCounts).toEqual({ completed: 2, total: 2 });
+});
+
+it("bounds per-task reads during a thousand-event burst and reconciles once", async () => {
+ vi.useFakeTimers();
+ try {
+ mocks.getTask.mockReset().mockImplementation(() => new Promise(() => {}));
+ renderHook(() => useProjectWebSocket("p"));
+ for (let i = 0; i < 1000; i++)
+ Socket.current.message("TASK_UPDATED", { taskId: `task-${i}` });
+ expect(mocks.getTask).toHaveBeenCalledTimes(4);
+ await vi.advanceTimersByTimeAsync(200);
+ expect(
+ mocks.client.invalidateQueries.mock.calls.filter(
+ ([options]) => options.queryKey[0] === "tasks",
+ ),
+ ).toHaveLength(1);
+ expect(mocks.getTask).toHaveBeenCalledTimes(4);
+ } finally {
+ vi.useRealTimers();
+ }
+});
++
++it("applies remote reorders to virtual task buckets", () => {
++ const board = mocks.board as {
++ plannedTasks: unknown[];
++ archivedTasks: unknown[];
++ };
++ board.plannedTasks = [
++ { id: "p1", projectId: "p", status: "planned", position: 0 },
++ { id: "p2", projectId: "p", status: "planned", position: 1 },
++ ];
++ renderHook(() => useProjectWebSocket("p"));
++ Socket.current.message("TASKS_REORDERED", {
++ tasks: [
++ { id: "p1", position: 1 },
++ { id: "p2", position: 0 },
++ ],
++ });
++ expect(
++ (mocks.board as { plannedTasks: { id: string }[] }).plannedTasks.map(
++ (task) => task.id,
++ ),
++ ).toEqual(["p2", "p1"]);
++});
++
++it("reconciles a remote read superseded by a narrow local mutation", async () => {
++ const { markBoardCacheChanged } = await import("@/lib/board-cache-version");
++ let finish!: (value: unknown) => void;
++ mocks.getTask.mockImplementationOnce(
++ () =>
++ new Promise((resolve) => {
++ finish = resolve;
++ }),
++ );
++ renderHook(() => useProjectWebSocket("p"));
++ Socket.current.message("TASK_UPDATED", { taskId: "a" });
++ markBoardCacheChanged(mocks.client as never, "p", "a");
++ finish({ id: "a", projectId: "p", status: "todo", dueDate: "2026-10-01" });
++ await Promise.resolve();
++ await Promise.resolve();
++ await Promise.resolve();
++ expect(mocks.client.invalidateQueries).toHaveBeenCalledWith({
++ queryKey: ["tasks", "p"],
++ });
++});
diff --cc apps/web/src/hooks/use-project-websocket.ts
index 475fc5fea,f52da8eb3..4882c9ff2
--- a/apps/web/src/hooks/use-project-websocket.ts
+++ b/apps/web/src/hooks/use-project-websocket.ts
@@@ -115,66 -86,6 +115,68 @@@ export function useProjectWebSocket(pro
}
return;
}
+ const boardIsLoading =
+ queryClient.getQueryState(["tasks", projectId])?.fetchStatus ===
+ "fetching";
+ if (boardIsLoading) {
+ if (
+ message.type === "TASKS_REORDERED" &&
+ Array.isArray(message.tasks)
+ ) {
+ for (const change of message.tasks)
+ pendingMessages.set(
+ `TASKS_REORDERED:${change.id}`,
+ JSON.stringify({ ...message, tasks: [change] }),
+ );
+ } else
+ pendingMessages.set(
+ `${message.type}:${message.taskId ?? ""}:${message.sourceTaskId ?? ""}:${message.targetTaskId ?? ""}`,
+ event.data,
+ );
+ return;
+ }
+ if (message.type === "TASKS_REORDERED") {
+ for (const change of Array.isArray(message.tasks)
+ ? message.tasks
+ : []) {
+ queryClient.invalidateQueries({ queryKey: ["task", change.id] });
+ taskVersions.set(
+ change.id,
+ (taskVersions.get(change.id) ?? 0) + 1,
+ );
+ markBoardCacheChanged(queryClient, projectId, change.id);
+ }
+ const board = queryClient.getQueryData<ProjectWithTasks>([
+ "tasks",
+ projectId,
+ ]);
+ if (!board || !Array.isArray(message.tasks)) {
+ void queryClient.invalidateQueries({
+ queryKey: ["tasks", projectId],
+ });
+ return;
+ }
+ let updated = board;
+ for (const change of message.tasks) {
- const task = updated.columns
- .flatMap((column) => column.tasks)
- .find((task) => task.id === change.id);
++ const task = [
++ ...updated.columns.flatMap((column) => column.tasks),
++ ...updated.plannedTasks,
++ ...updated.archivedTasks,
++ ].find((task) => task.id === change.id);
+ if (!task) {
+ markBoardCacheChanged(queryClient, projectId);
+ void queryClient.invalidateQueries({
+ queryKey: ["tasks", projectId],
+ });
+ }
+ if (task)
+ updated =
+ patchBoardTask(updated, task.id, { ...task, ...change }) ??
+ updated;
+ }
+ queryClient.setQueryData(["tasks", projectId], updated);
+ return;
+ }
if (
message.type === "TASK_UPDATED" ||
message.type === "TASK_CREATED" ||
@@@ -185,125 -96,9 +187,132 @@@
message.type === "COMMENT_UPDATED" ||
message.type === "PROJECT_UPDATED"
) {
- queryClient.invalidateQueries({
- queryKey: ["tasks", message.projectId],
- });
+ if (
+ message.type === "PROJECT_UPDATED" ||
+ message.type === "TASK_RELATION_UPDATED"
+ ) {
+ markBoardCacheChanged(queryClient, projectId);
+ void queryClient.invalidateQueries({
+ queryKey: ["tasks", projectId],
+ });
+ } else if (!message.taskId && message.type !== "COMMENT_UPDATED") {
+ markBoardCacheChanged(queryClient, projectId);
+ void queryClient.invalidateQueries({
+ queryKey: ["tasks", projectId],
+ });
+ } else if (message.taskId && message.type !== "COMMENT_UPDATED") {
+ const taskId = message.taskId as string;
+ const sequence = ++requestSequence;
+ const version = (taskVersions.get(taskId) ?? 0) + 1;
+ taskVersions.set(taskId, version);
+ markBoardCacheChanged(queryClient, projectId, taskId);
+ const boardVersion = getBoardCacheVersion(
+ queryClient,
+ projectId,
+ taskId,
+ );
+ if (message.type === "TASK_DELETED") {
+ queryClient.setQueryData<ProjectWithTasks>(
+ ["tasks", projectId],
+ (board) =>
+ board ? (patchBoardTask(board, taskId) ?? board) : board,
+ );
+ } else if (
+ refreshingTasks.size >= 4 ||
+ refreshingTasks.has(taskId) ||
+ burstReconcileTimer !== null
+ ) {
+ reconcileBurst();
+ } else {
+ refreshingTasks.add(taskId);
+ void Promise.all([
+ getTask(taskId, "board"),
+ getLabelsByTask({ taskId }),
+ getExternalLinks(taskId),
+ ])
+ .then(([task, labels, externalLinks]) => {
+ if (
+ disposed ||
+ activeSocket !== ws ||
- taskVersions.get(taskId) !== version ||
- getBoardCacheVersion(queryClient, projectId, taskId) !==
- boardVersion
++ taskVersions.get(taskId) !== version
+ )
+ return;
++ if (
++ getBoardCacheVersion(queryClient, projectId, taskId) !==
++ boardVersion
++ ) {
++ void queryClient.invalidateQueries({
++ queryKey: ["tasks", projectId],
++ });
++ return;
++ }
+ const staleOwnCounts =
+ (parentCountVersions.get(taskId) ?? 0) > sequence;
+ const { subtaskCounts, ...taskFields } = task;
+ if (staleOwnCounts)
+ void queryClient.invalidateQueries({
+ queryKey: ["tasks", projectId],
+ });
+ else parentCountVersions.set(taskId, sequence);
+ queryClient.setQueryData<ProjectWithTasks>(
+ ["tasks", projectId],
+ (board) =>
+ board
+ ? (patchBoardTask(board, taskId, {
+ ...taskFields,
+ ...(!staleOwnCounts ? { subtaskCounts } : {}),
+ labels,
+ externalLinks: externalLinks.map((link) => ({
+ ...link,
+ metadata:
+ link.metadata &&
+ typeof link.metadata === "object" &&
+ !Array.isArray(link.metadata)
+ ? link.metadata
+ : null,
+ })),
+ }) ?? board)
+ : board,
+ );
+ for (const progress of task.parentSubtaskCounts ?? []) {
+ if (
+ (parentCountVersions.get(progress.taskId) ?? 0) >
+ sequence
+ ) {
+ void queryClient.invalidateQueries({
+ queryKey: ["tasks", projectId],
+ });
+ continue;
+ }
+ parentCountVersions.set(progress.taskId, sequence);
+ queryClient.setQueryData<ProjectWithTasks>(
+ ["tasks", projectId],
+ (board) =>
+ board
+ ? (patchBoardTask(board, progress.taskId, {
+ projectId,
+ subtaskCounts: {
+ completed: progress.completed,
+ total: progress.total,
+ },
+ }) ?? board)
+ : board,
+ );
+ }
+ })
+ .catch(() => {
+ if (
+ !disposed &&
+ activeSocket === ws &&
+ taskVersions.get(taskId) === version
+ )
+ void queryClient.invalidateQueries({
+ queryKey: ["tasks", projectId],
+ });
+ })
+ .finally(() => refreshingTasks.delete(taskId));
+ }
+ }
if (message.type === "PROJECT_UPDATED") {
queryClient.invalidateQueries({ queryKey: ["projects"] });