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.

perf(board): load pages incrementally and patch live changes

Tin95478d813841
diff --git a/apps/web/src/components/kanban-board/index.tsx b/apps/web/src/components/kanban-board/index.tsx
index 1946a24cf..b3d2a0c5a 100644
--- a/apps/web/src/components/kanban-board/index.tsx
+++ b/apps/web/src/components/kanban-board/index.tsx
@@ -1,3 +1,4 @@
+import { markBoardCacheChanged } from "@/lib/board-cache-version";
import {
closestCorners,
DndContext,
@@ -159,11 +160,18 @@ function KanbanBoard({
const activeId = active.id.toString();
const overId = over.id.toString();
- if (isReordering) return;
+ if (
+ isReordering ||
+ queryClient.getQueryState(["tasks", project.id])?.fetchStatus ===
+ "fetching"
+ )
+ return;
const canonical =
storedProject?.id === project.id ? storedProject : project;
const moved = moveBoardTask(canonical, activeId, overId, sortedByNumber);
if (!moved || !moved.tasks.length) return;
+ for (const task of moved.tasks)
+ markBoardCacheChanged(queryClient, project.id, task.id);
setProject(moved.project);
queryClient.setQueryData(["tasks", project.id], moved.project);
reorder({ projectId: project.id, tasks: moved.tasks });
diff --git a/apps/web/src/fetchers/project/get-public-project.ts b/apps/web/src/fetchers/project/get-public-project.ts
index bd3050d40..94bc4a5bb 100644
--- a/apps/web/src/fetchers/project/get-public-project.ts
+++ b/apps/web/src/fetchers/project/get-public-project.ts
@@ -1,3 +1,4 @@
+import type { ProjectWithTasks } from "@/types/project";
import { client } from "@kaneo/libs";
import type { InferRequestType } from "hono/client";
import { loadBoardPages } from "@/fetchers/task/load-board-pages";
@@ -8,23 +9,28 @@ export type GetPublicProjectRequest = InferRequestType<
async function getPublicProject(
{ id }: GetPublicProjectRequest,
signal?: AbortSignal,
+ onProgress?: (board: ProjectWithTasks) => void,
) {
- return loadBoardPages(async (page, relatedPage) => {
- const response = await client["public-project"][":id"].$get(
- {
- param: { id },
- query: {
- page: String(page),
- limit: "100",
- ...(relatedPage ? { relatedPage: String(relatedPage) } : {}),
+ return loadBoardPages(
+ async (page, relatedPage) => {
+ const response = await client["public-project"][":id"].$get(
+ {
+ param: { id },
+ query: {
+ page: String(page),
+ limit: "100",
+ ...(relatedPage ? { relatedPage: String(relatedPage) } : {}),
+ },
},
- },
- { init: { signal } },
- );
- if (!response.ok)
- throw new HttpError(response.status, await response.text());
- const { pagination, ...data } = await response.json();
- return { data, pagination };
- }, signal);
+ { init: { signal } },
+ );
+ if (!response.ok)
+ throw new HttpError(response.status, await response.text());
+ const { pagination, ...data } = await response.json();
+ return { data, pagination };
+ },
+ signal,
+ onProgress,
+ );
}
export default getPublicProject;
diff --git a/apps/web/src/fetchers/task/get-tasks.ts b/apps/web/src/fetchers/task/get-tasks.ts
index 0f4a1c4e8..db8063d18 100644
--- a/apps/web/src/fetchers/task/get-tasks.ts
+++ b/apps/web/src/fetchers/task/get-tasks.ts
@@ -1,23 +1,32 @@
import { client } from "@kaneo/libs";
+import type { ProjectWithTasks } from "@/types/project";
import { HttpError } from "@/lib/http-error";
import { loadBoardPages } from "./load-board-pages";
-async function getTasks(projectId: string, signal?: AbortSignal) {
- return loadBoardPages(async (page, relatedPage) => {
- const response = await client.task.tasks[":projectId"].$get(
- {
- param: { projectId },
- query: {
- page: String(page),
- limit: "100",
- ...(relatedPage ? { relatedPage: String(relatedPage) } : {}),
+async function getTasks(
+ projectId: string,
+ signal?: AbortSignal,
+ onProgress?: (board: ProjectWithTasks) => void,
+) {
+ return loadBoardPages(
+ async (page, relatedPage) => {
+ const response = await client.task.tasks[":projectId"].$get(
+ {
+ param: { projectId },
+ query: {
+ page: String(page),
+ limit: "100",
+ ...(relatedPage ? { relatedPage: String(relatedPage) } : {}),
+ },
},
- },
- { init: { signal } },
- );
- if (!response.ok)
- throw new HttpError(response.status, "Failed to fetch tasks");
- return response.json();
- }, signal);
+ { init: { signal } },
+ );
+ if (!response.ok)
+ throw new HttpError(response.status, "Failed to fetch tasks");
+ return response.json();
+ },
+ signal,
+ onProgress,
+ );
}
export default getTasks;
diff --git a/apps/web/src/fetchers/task/load-board-pages.test.ts b/apps/web/src/fetchers/task/load-board-pages.test.ts
index ef82c2962..fd2b4c7a6 100644
--- a/apps/web/src/fetchers/task/load-board-pages.test.ts
+++ b/apps/web/src/fetchers/task/load-board-pages.test.ts
@@ -58,6 +58,32 @@ function page(number: number, totalPages = 3) {
};
}
describe("complete board loading through bounded pages", () => {
+ it("publishes the first page before a slow continuation and keeps snapshots immutable", async () => {
+ let finish!: (value: ReturnType<typeof page>) => void;
+ const snapshots: ProjectWithTasks[] = [];
+ const load = vi
+ .fn()
+ .mockResolvedValueOnce(page(1, 2))
+ .mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const loading = loadBoardPages(load, undefined, (board) =>
+ snapshots.push(board),
+ );
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(snapshots[0].columns[0].tasks.map((task) => task.id)).toEqual(["1"]);
+ finish(page(2, 2));
+ await loading;
+ expect(snapshots.at(-1)?.columns[0].tasks.map((task) => task.id)).toEqual([
+ "1",
+ "2",
+ ]);
+ expect(snapshots[0].columns[0].tasks).toHaveLength(1);
+ });
it("loads sequentially and merges every column, planned and archived task with its complete fields", async () => {
let active = 0;
let peak = 0;
diff --git a/apps/web/src/fetchers/task/load-board-pages.ts b/apps/web/src/fetchers/task/load-board-pages.ts
index 563944139..ccfd4afc3 100644
--- a/apps/web/src/fetchers/task/load-board-pages.ts
+++ b/apps/web/src/fetchers/task/load-board-pages.ts
@@ -11,14 +11,23 @@ export type BoardPage<T extends ProjectWithTasks> = {
};
};
-/** Keep the existing board cache shape, but fetch one bounded page at a time. */
+/** Publish immutable snapshots as bounded pages arrive. */
export async function loadBoardPages<T extends ProjectWithTasks>(
load: (page: number, relatedPage?: number) => Promise<BoardPage<T>>,
signal?: AbortSignal,
+ onProgress?: (board: T) => void,
): Promise<T> {
signal?.throwIfAborted();
const first = await load(1);
const result = first.data;
+ const reportProgress = () => {
+ signal?.throwIfAborted();
+ result.columns.sort(
+ (left, right) => (left.position ?? 0) - (right.position ?? 0),
+ );
+ onProgress?.(structuredClone(result));
+ };
+ reportProgress();
const columns = new Map(result.columns.map((column) => [column.id, column]));
const seen = new Map(
[
@@ -74,6 +83,7 @@ export async function loadBoardPages<T extends ProjectWithTasks>(
for (let relatedPage = 2; relatedPage <= total; relatedPage++) {
signal?.throwIfAborted();
merge(await load(page, relatedPage));
+ reportProgress();
}
};
await loadRelated(1, first);
@@ -81,6 +91,7 @@ export async function loadBoardPages<T extends ProjectWithTasks>(
signal?.throwIfAborted();
const next = await load(page);
merge(next);
+ reportProgress();
await loadRelated(page, next);
}
result.columns.sort(
diff --git a/apps/web/src/hooks/mutations/task/use-update-task-description.ts b/apps/web/src/hooks/mutations/task/use-update-task-description.ts
index baae2acd0..a6c1de81f 100644
--- a/apps/web/src/hooks/mutations/task/use-update-task-description.ts
+++ b/apps/web/src/hooks/mutations/task/use-update-task-description.ts
@@ -1,18 +1,19 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import updateTaskDescription from "@/fetchers/task/update-task-description";
import type Task from "@/types/task";
+import { updateBoardTaskCache } from "@/lib/update-board-task-cache";
export function useUpdateTaskDescription() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (task: Task) => updateTaskDescription(task.id, task),
- onSuccess: (_, variables) => {
+ onSuccess: (updated, variables) => {
queryClient.invalidateQueries({
queryKey: ["task", variables.id],
});
- queryClient.invalidateQueries({
- queryKey: ["tasks", variables.projectId],
+ updateBoardTaskCache(queryClient, variables.projectId, variables.id, {
+ description: updated.description,
});
queryClient.invalidateQueries({
queryKey: ["notifications"],
diff --git a/apps/web/src/hooks/mutations/task/use-update-task-due-date.ts b/apps/web/src/hooks/mutations/task/use-update-task-due-date.ts
index 1a0e6d924..066a0d440 100644
--- a/apps/web/src/hooks/mutations/task/use-update-task-due-date.ts
+++ b/apps/web/src/hooks/mutations/task/use-update-task-due-date.ts
@@ -1,18 +1,19 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import updateTaskDueDate from "@/fetchers/task/update-task-due-date";
import type Task from "@/types/task";
+import { updateBoardTaskCache } from "@/lib/update-board-task-cache";
export function useUpdateTaskDueDate() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (task: Task) => updateTaskDueDate(task.id, task),
- onSuccess: (_, variables) => {
+ onSuccess: (updated, variables) => {
queryClient.invalidateQueries({
queryKey: ["task", variables.id],
});
- queryClient.invalidateQueries({
- queryKey: ["tasks", variables.projectId],
+ updateBoardTaskCache(queryClient, variables.projectId, variables.id, {
+ dueDate: updated.dueDate,
});
queryClient.invalidateQueries({
queryKey: ["notifications"],
diff --git a/apps/web/src/hooks/mutations/task/use-update-task-status-priority.ts b/apps/web/src/hooks/mutations/task/use-update-task-status-priority.ts
index fb1523351..b0c279143 100644
--- a/apps/web/src/hooks/mutations/task/use-update-task-status-priority.ts
+++ b/apps/web/src/hooks/mutations/task/use-update-task-status-priority.ts
@@ -1,18 +1,19 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import updateTaskPriority from "@/fetchers/task/update-task-priority";
import type Task from "@/types/task";
+import { updateBoardTaskCache } from "@/lib/update-board-task-cache";
export function useUpdateTaskPriority() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (task: Task) => updateTaskPriority(task.id, task),
- onSuccess: (_, variables) => {
+ onSuccess: (updated, variables) => {
queryClient.invalidateQueries({
queryKey: ["task", variables.id],
});
- queryClient.invalidateQueries({
- queryKey: ["tasks", variables.projectId],
+ updateBoardTaskCache(queryClient, variables.projectId, variables.id, {
+ priority: updated.priority,
});
queryClient.invalidateQueries({
queryKey: ["notifications"],
diff --git a/apps/web/src/hooks/mutations/task/use-update-task-title.ts b/apps/web/src/hooks/mutations/task/use-update-task-title.ts
index 20f90d0eb..2f421b6da 100644
--- a/apps/web/src/hooks/mutations/task/use-update-task-title.ts
+++ b/apps/web/src/hooks/mutations/task/use-update-task-title.ts
@@ -1,18 +1,19 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import updateTaskTitle from "@/fetchers/task/update-task-title";
import type Task from "@/types/task";
+import { updateBoardTaskCache } from "@/lib/update-board-task-cache";
export function useUpdateTaskTitle() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (task: Task) => updateTaskTitle(task.id, task),
- onSuccess: (_, variables) => {
+ onSuccess: (updated, variables) => {
queryClient.invalidateQueries({
queryKey: ["task", variables.id],
});
- queryClient.invalidateQueries({
- queryKey: ["tasks", variables.projectId],
+ updateBoardTaskCache(queryClient, variables.projectId, variables.id, {
+ title: updated.title,
});
queryClient.invalidateQueries({
queryKey: ["notifications"],
diff --git a/apps/web/src/hooks/queries/project/use-get-public-project.ts b/apps/web/src/hooks/queries/project/use-get-public-project.ts
index 3327c4f3a..44dedea16 100644
--- a/apps/web/src/hooks/queries/project/use-get-public-project.ts
+++ b/apps/web/src/hooks/queries/project/use-get-public-project.ts
@@ -1,10 +1,17 @@
-import { useQuery } from "@tanstack/react-query";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
import getPublicProject from "@/fetchers/project/get-public-project";
function useGetPublicProject(id: string) {
+ const queryClient = useQueryClient();
return useQuery({
queryKey: ["public-project", id],
- queryFn: ({ signal }) => getPublicProject({ id }, signal),
+ queryFn: ({ signal }) => {
+ const hasCachedBoard = !!queryClient.getQueryData(["public-project", id]);
+ return getPublicProject({ id }, signal, (board) => {
+ if (!hasCachedBoard)
+ queryClient.setQueryData(["public-project", id], board);
+ });
+ },
refetchOnMount: true,
});
}
diff --git a/apps/web/src/hooks/queries/task/use-get-tasks.test.tsx b/apps/web/src/hooks/queries/task/use-get-tasks.test.tsx
index b9662d8f9..d0dd536c8 100644
--- a/apps/web/src/hooks/queries/task/use-get-tasks.test.tsx
+++ b/apps/web/src/hooks/queries/task/use-get-tasks.test.tsx
@@ -42,6 +42,7 @@ describe("useGetTasks", () => {
expect(getPublicProject).toHaveBeenCalledWith(
{ id: "public-parent" },
expect.any(AbortSignal),
+ expect.any(Function),
);
});
diff --git a/apps/web/src/hooks/queries/task/use-get-tasks.ts b/apps/web/src/hooks/queries/task/use-get-tasks.ts
index 4861dc978..5dd97c625 100644
--- a/apps/web/src/hooks/queries/task/use-get-tasks.ts
+++ b/apps/web/src/hooks/queries/task/use-get-tasks.ts
@@ -1,14 +1,21 @@
-import { useQuery } from "@tanstack/react-query";
+import { markBoardCacheChanged } from "@/lib/board-cache-version";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
import getTasks from "@/fetchers/task/get-tasks";
-import { isUnauthorizedError } from "@/lib/http-error";
export function useGetTasks(projectId: string) {
+ const queryClient = useQueryClient();
return useQuery({
queryKey: ["tasks", projectId],
- queryFn: ({ signal }) => getTasks(projectId, signal),
+ queryFn: ({ signal }) => {
+ markBoardCacheChanged(queryClient, projectId);
+ const hasCachedBoard = !!queryClient.getQueryData(["tasks", projectId]);
+ return getTasks(projectId, signal, (board) => {
+ if (!hasCachedBoard)
+ queryClient.setQueryData(["tasks", projectId], board);
+ });
+ },
refetchOnMount: true,
- refetchInterval: (query) =>
- isUnauthorizedError(query.state.error) ? false : 30000,
+ refetchOnWindowFocus: true,
enabled: !!projectId,
});
}
diff --git a/apps/web/src/hooks/use-project-websocket-cache.test.tsx b/apps/web/src/hooks/use-project-websocket-cache.test.tsx
new file mode 100644
index 000000000..fc16c84b6
--- /dev/null
+++ b/apps/web/src/hooks/use-project-websocket-cache.test.tsx
@@ -0,0 +1,151 @@
+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;
+ 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");
+ 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"],
+ });
+ });
+});
diff --git a/apps/web/src/hooks/use-project-websocket-lifecycle.test.tsx b/apps/web/src/hooks/use-project-websocket-lifecycle.test.tsx
index ae642ab48..77cb673a8 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,14 @@ import {
import { useProjectWebSocket } from "./use-project-websocket";
const { client, auth } = vi.hoisted(() => ({
- client: { invalidateQueries: vi.fn() },
+ client: {
+ getQueryCache: () => ({ subscribe: () => () => {} }),
+ getQueryState: vi.fn(),
+ cancelQueries: vi.fn().mockResolvedValue(undefined),
+ invalidateQueries: vi.fn(),
+ setQueryData: vi.fn(),
+ getQueryData: vi.fn(),
+ },
auth: { userId: "user-a" as string | null },
}));
vi.mock("@tanstack/react-query", () => ({ useQueryClient: () => client }));
diff --git a/apps/web/src/hooks/use-project-websocket.test.ts b/apps/web/src/hooks/use-project-websocket.test.ts
index 343a744fd..e5c876a15 100644
--- a/apps/web/src/hooks/use-project-websocket.test.ts
+++ b/apps/web/src/hooks/use-project-websocket.test.ts
@@ -15,8 +15,15 @@ vi.mock("@kaneo/libs", () => ({
import { getWsUrl, useProjectWebSocket } from "./use-project-websocket";
const invalidateQueries = vi.fn();
+const getQueryState = vi.fn();
+const cancelQueries = vi.fn().mockResolvedValue(undefined);
vi.mock("@tanstack/react-query", () => ({
- useQueryClient: () => ({ invalidateQueries }),
+ useQueryClient: () => ({
+ invalidateQueries,
+ getQueryCache: () => ({ subscribe: () => () => {} }),
+ getQueryState,
+ cancelQueries,
+ }),
}));
vi.mock("@/lib/auth-client", () => ({
authClient: { useSession: () => ({ data: { user: { id: "user-1" } } }) },
diff --git a/apps/web/src/hooks/use-project-websocket.ts b/apps/web/src/hooks/use-project-websocket.ts
index bb4ea6e4a..a2ea6022f 100644
--- a/apps/web/src/hooks/use-project-websocket.ts
+++ b/apps/web/src/hooks/use-project-websocket.ts
@@ -1,8 +1,17 @@
+import {
+ getBoardCacheVersion,
+ markBoardCacheChanged,
+} from "@/lib/board-cache-version";
import { windowId } from "@kaneo/libs";
import { useQueryClient } from "@tanstack/react-query";
import { useEffect } from "react";
import { getApiUrl } from "@/fetchers/get-api-url";
import { authClient } from "@/lib/auth-client";
+import getTask from "@/fetchers/task/get-task";
+import getLabelsByTask from "@/fetchers/label/get-labels-by-task";
+import getExternalLinks from "@/fetchers/external-link/get-external-links";
+import { patchBoardTask } from "@/lib/patch-board-task";
+import type { ProjectWithTasks } from "@/types/project";
export function getWsUrl(projectId: string) {
const base = getApiUrl("ws");
@@ -27,10 +36,14 @@ export function useProjectWebSocket(projectId: string) {
// Each effect owns its sockets and timers. Late events from an old project
// or session must not alter the next effect's connection or reconnect it.
let disposed = false;
+ let hasConnected = false;
+ const taskVersions = new Map<string, number>();
+ const pendingMessages = new Map<string, string>();
let activeSocket: WebSocket | null = null;
let retries = 0;
let retryTimeout: ReturnType<typeof setTimeout> | null = null;
let pingInterval: ReturnType<typeof setInterval> | null = null;
+ let fallbackInterval: ReturnType<typeof setInterval> | null = null;
function clearPing() {
if (pingInterval !== null) {
@@ -48,6 +61,16 @@ export function useProjectWebSocket(projectId: string) {
ws.onopen = () => {
if (disposed || activeSocket !== ws) return;
+ if (hasConnected) markBoardCacheChanged(queryClient, projectId);
+ if (hasConnected)
+ void queryClient.invalidateQueries({
+ queryKey: ["tasks", projectId],
+ });
+ if (fallbackInterval !== null) {
+ clearInterval(fallbackInterval);
+ fallbackInterval = null;
+ }
+ hasConnected = true;
retries = 0; // Reset retries on successful connection
// Start keepalive pings to prevent Cloudflare idle timeout (100s)
clearPing();
@@ -63,6 +86,7 @@ export function useProjectWebSocket(projectId: string) {
try {
const message = JSON.parse(event.data);
if (message.type === "PROJECT_MOVED") {
+ markBoardCacheChanged(queryClient, projectId);
for (const queryKey of [
["projects"],
["project", projectId],
@@ -74,8 +98,63 @@ export function useProjectWebSocket(projectId: string) {
}
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(
+ change.id,
+ JSON.stringify({ ...message, tasks: [change] }),
+ );
+ } else
+ pendingMessages.set(message.taskId || message.type, event.data);
+ return;
+ }
+ if (message.type === "TASKS_REORDERED") {
+ for (const change of Array.isArray(message.tasks)
+ ? message.tasks
+ : []) {
+ 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);
+ 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 === "TASKS_REORDERED" ||
message.type === "TASK_UPDATED" ||
message.type === "TASK_CREATED" ||
message.type === "TASK_DELETED" ||
@@ -85,9 +164,81 @@ export function useProjectWebSocket(projectId: string) {
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 version = (taskVersions.get(taskId) ?? 0) + 1;
+ taskVersions.set(taskId, version);
+ const boardVersion = getBoardCacheVersion(
+ queryClient,
+ projectId,
+ taskId,
+ );
+ if (message.type === "TASK_DELETED") {
+ queryClient.setQueryData<ProjectWithTasks>(
+ ["tasks", projectId],
+ (board) =>
+ board ? (patchBoardTask(board, taskId) ?? board) : board,
+ );
+ } else {
+ void Promise.all([
+ getTask(taskId),
+ getLabelsByTask({ taskId }),
+ getExternalLinks(taskId),
+ ])
+ .then(([task, labels, externalLinks]) => {
+ if (
+ disposed ||
+ activeSocket !== ws ||
+ taskVersions.get(taskId) !== version ||
+ getBoardCacheVersion(queryClient, projectId, taskId) !==
+ boardVersion
+ )
+ return;
+ queryClient.setQueryData<ProjectWithTasks>(
+ ["tasks", projectId],
+ (board) =>
+ board
+ ? (patchBoardTask(board, taskId, {
+ ...task,
+ labels,
+ externalLinks: externalLinks.map((link) => ({
+ ...link,
+ metadata:
+ link.metadata &&
+ typeof link.metadata === "object" &&
+ !Array.isArray(link.metadata)
+ ? link.metadata
+ : null,
+ })),
+ }) ?? board)
+ : board,
+ );
+ })
+ .catch(() => {
+ if (
+ !disposed &&
+ activeSocket === ws &&
+ taskVersions.get(taskId) === version
+ )
+ void queryClient.invalidateQueries({
+ queryKey: ["tasks", projectId],
+ });
+ });
+ }
+ }
if (message.type === "PROJECT_UPDATED") {
queryClient.invalidateQueries({ queryKey: ["projects"] });
@@ -157,14 +308,40 @@ export function useProjectWebSocket(projectId: string) {
const delay = BASE_DELAY * 2 ** retries; // 1s, 2s, 4s, 8s, 16s
retries += 1;
retryTimeout = setTimeout(connect, delay);
+ } else if (fallbackInterval === null) {
+ // Refresh only when realtime delivery could not reconnect.
+ fallbackInterval = setInterval(() => {
+ void queryClient.invalidateQueries({
+ queryKey: ["tasks", projectId],
+ });
+ }, 30_000);
}
};
}
connect();
+ const unsubscribe = queryClient.getQueryCache().subscribe(({ query }) => {
+ if (
+ query.queryKey[0] !== "tasks" ||
+ query.queryKey[1] !== projectId ||
+ query.state.fetchStatus !== "idle" ||
+ !pendingMessages.size
+ )
+ return;
+ const messages = Array.from(pendingMessages.values());
+ pendingMessages.clear();
+ queueMicrotask(() => {
+ if (disposed || !activeSocket) return;
+ for (const data of messages)
+ activeSocket.onmessage?.(new MessageEvent("message", { data }));
+ });
+ });
return () => {
+ unsubscribe();
+ pendingMessages.clear();
disposed = true;
clearPing();
+ if (fallbackInterval !== null) clearInterval(fallbackInterval);
if (retryTimeout !== null) {
clearTimeout(retryTimeout);
}
diff --git a/apps/web/src/lib/board-cache-version.ts b/apps/web/src/lib/board-cache-version.ts
new file mode 100644
index 000000000..c52fcafb0
--- /dev/null
+++ b/apps/web/src/lib/board-cache-version.ts
@@ -0,0 +1,21 @@
+import type { QueryClient } from "@tanstack/react-query";
+
+const versions = new WeakMap<QueryClient, Map<string, number>>();
+export function markBoardCacheChanged(
+ client: QueryClient,
+ projectId: string,
+ taskId?: string,
+) {
+ const cache = versions.get(client) ?? new Map<string, number>();
+ versions.set(client, cache);
+ const key = taskId ? `${projectId}:${taskId}` : projectId;
+ cache.set(key, (cache.get(key) ?? 0) + 1);
+}
+export function getBoardCacheVersion(
+ client: QueryClient,
+ projectId: string,
+ taskId: string,
+) {
+ const cache = versions.get(client);
+ return `${cache?.get(projectId) ?? 0}:${cache?.get(`${projectId}:${taskId}`) ?? 0}`;
+}
diff --git a/apps/web/src/lib/patch-board-task.test.ts b/apps/web/src/lib/patch-board-task.test.ts
new file mode 100644
index 000000000..f2192a5b0
--- /dev/null
+++ b/apps/web/src/lib/patch-board-task.test.ts
@@ -0,0 +1,84 @@
+import { QueryClient } from "@tanstack/react-query";
+import { describe, expect, it } from "vite-plus/test";
+import type { ProjectWithTasks } from "@/types/project";
+import { patchBoardTask } from "./patch-board-task";
+import { updateBoardTaskCache } from "./update-board-task-cache";
+
+function board() {
+ return {
+ id: "p",
+ columns: [
+ {
+ id: "todo",
+ slug: "todo",
+ tasks: [
+ {
+ id: "a",
+ projectId: "p",
+ status: "todo",
+ title: "old",
+ userId: "u",
+ assigneeId: "u",
+ labels: [{ id: "label" }],
+ subtaskCounts: { completed: 1, total: 3 },
+ },
+ ],
+ },
+ { id: "doing", slug: "doing", tasks: [] },
+ ],
+ archivedTasks: [],
+ plannedTasks: [],
+ } as unknown as ProjectWithTasks;
+}
+
+describe("bounded board cache updates", () => {
+ it("preserves metadata and the assignee when updating a single field", () => {
+ const client = new QueryClient();
+ client.setQueryData(["tasks", "p"], board());
+ updateBoardTaskCache(client, "p", "a", { title: "new" });
+ expect(
+ client.getQueryData<ProjectWithTasks>(["tasks", "p"])?.columns[0]
+ .tasks[0],
+ ).toMatchObject({
+ title: "new",
+ assigneeId: "u",
+ labels: [{ id: "label" }],
+ subtaskCounts: { completed: 1, total: 3 },
+ });
+ client.clear();
+ });
+
+ it("lets a pending board load finish and applies only the newest local edit afterward", async () => {
+ const client = new QueryClient();
+ let finish!: (value: ProjectWithTasks) => void;
+ const loading = client.fetchQuery({
+ queryKey: ["tasks", "p"],
+ queryFn: () =>
+ new Promise<ProjectWithTasks>((resolve) => {
+ finish = resolve;
+ }),
+ });
+ updateBoardTaskCache(client, "p", "a", { title: "first" });
+ updateBoardTaskCache(client, "p", "a", { title: "latest" });
+ expect(client.getQueryState(["tasks", "p"])?.fetchStatus).toBe("fetching");
+ finish(board());
+ await loading;
+ expect(
+ client.getQueryData<ProjectWithTasks>(["tasks", "p"])?.columns[0].tasks[0]
+ .title,
+ ).toBe("latest");
+ client.clear();
+ });
+
+ it("moves a refreshed task by column slug and removes tasks moved out of the project", () => {
+ const moved = patchBoardTask(board(), "a", {
+ projectId: "p",
+ status: "doing",
+ })!;
+ expect(moved.columns[0].tasks).toHaveLength(0);
+ expect(moved.columns[1].tasks.map((task) => task.id)).toEqual(["a"]);
+ expect(
+ patchBoardTask(moved, "a", { projectId: "other" })?.columns[1].tasks,
+ ).toHaveLength(0);
+ });
+});
diff --git a/apps/web/src/lib/patch-board-task.ts b/apps/web/src/lib/patch-board-task.ts
new file mode 100644
index 000000000..07d71d83f
--- /dev/null
+++ b/apps/web/src/lib/patch-board-task.ts
@@ -0,0 +1,46 @@
+import type { ProjectWithTasks } from "@/types/project";
+import type Task from "@/types/task";
+
+/** Preserve board-only metadata while applying a bounded task refresh. */
+export function patchBoardTask(
+ board: ProjectWithTasks,
+ taskId: string,
+ update?: Partial<Task>,
+) {
+ const existing = [
+ ...board.columns.flatMap((column) => column.tasks),
+ ...board.plannedTasks,
+ ...board.archivedTasks,
+ ].find((task) => task.id === taskId);
+ const belongs = update && update.projectId === board.id;
+ const task = belongs
+ ? ({
+ ...existing,
+ ...update,
+ assigneeId:
+ "userId" in update
+ ? (update.userId ?? null)
+ : (existing?.assigneeId ?? null),
+ } as Task)
+ : undefined;
+ const columns = board.columns.map((column) => ({
+ ...column,
+ tasks: column.tasks.filter((task) => task.id !== taskId),
+ }));
+ const plannedTasks = board.plannedTasks.filter((task) => task.id !== taskId);
+ const archivedTasks = board.archivedTasks.filter(
+ (task) => task.id !== taskId,
+ );
+ if (task) {
+ const target =
+ task.status === "planned"
+ ? plannedTasks
+ : task.status === "archived"
+ ? archivedTasks
+ : columns.find((column) => column.slug === task.status)?.tasks;
+ if (!target) return null;
+ target.push(task);
+ target.sort((left, right) => (left.position ?? 0) - (right.position ?? 0));
+ }
+ return { ...board, columns, plannedTasks, archivedTasks };
+}
diff --git a/apps/web/src/lib/update-board-task-cache.ts b/apps/web/src/lib/update-board-task-cache.ts
new file mode 100644
index 000000000..3f710525e
--- /dev/null
+++ b/apps/web/src/lib/update-board-task-cache.ts
@@ -0,0 +1,40 @@
+import type { QueryClient } from "@tanstack/react-query";
+import type { ProjectWithTasks } from "@/types/project";
+import type Task from "@/types/task";
+import {
+ getBoardCacheVersion,
+ markBoardCacheChanged,
+} from "./board-cache-version";
+import { patchBoardTask } from "./patch-board-task";
+
+export function updateBoardTaskCache(
+ queryClient: QueryClient,
+ projectId: string,
+ taskId: string,
+ fields: Partial<Task>,
+) {
+ markBoardCacheChanged(queryClient, projectId, taskId);
+ const version = getBoardCacheVersion(queryClient, projectId, taskId);
+ const queryKey = ["tasks", projectId];
+ const apply = () => {
+ if (getBoardCacheVersion(queryClient, projectId, taskId) !== version)
+ return;
+ queryClient.setQueryData<ProjectWithTasks>(queryKey, (board) =>
+ board
+ ? (patchBoardTask(board, taskId, { ...fields, projectId }) ?? board)
+ : board,
+ );
+ };
+ if (queryClient.getQueryState(queryKey)?.fetchStatus === "fetching") {
+ const unsubscribe = queryClient
+ .getQueryCache()
+ .subscribe(({ query, type }) => {
+ if (query.queryKey[0] !== "tasks" || query.queryKey[1] !== projectId)
+ return;
+ if (type === "removed" || query.state.fetchStatus === "idle") {
+ unsubscribe();
+ if (type !== "removed") apply();
+ }
+ });
+ } else apply();
+}