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): preserve bounded cache updates across pagination races

Tindd614c1e9200
diff --cc apps/api/src/task/controllers/get-task.ts
index 0c33c9d39,0c33c9d39..e742e216f
--- a/apps/api/src/task/controllers/get-task.ts
+++ b/apps/api/src/task/controllers/get-task.ts
@@@ -1,15 -1,15 +1,30 @@@
--import { eq } from "drizzle-orm";
++import { boundedTaskRead } from "../bounded-read";
++import { alias } from "drizzle-orm/pg-core";
++import { boardDescription, descriptionDeferred } from "../description-pages";
++import { getSubtaskCounts } from "../get-subtask-counts";
++import { and, eq, sql } from "drizzle-orm";
import { HTTPException } from "hono/http-exception";
import db from "../../database";
--import { taskTable, userTable } from "../../database/schema";
++import {
++ taskTable,
++ userTable,
++ projectTable,
++ taskRelationTable,
++} from "../../database/schema";
--async function getTask(taskId: string) {
++async function getTask(taskId: string, board = false) {
const task = await db
.select({
id: taskTable.id,
title: taskTable.title,
number: taskTable.number,
-- description: taskTable.description,
++ description: board ? boardDescription : taskTable.description,
++ ...(board
++ ? {
++ descriptionDeferred,
++ workspaceId: sql<string>`(select ${projectTable.workspaceId} from ${projectTable} where ${projectTable.id} = ${taskTable.projectId})`,
++ }
++ : {}),
status: taskTable.status,
priority: taskTable.priority,
startDate: taskTable.startDate,
@@@ -32,7 -32,7 +47,36 @@@
});
}
-- return task[0];
++ const { workspaceId, ...result } = task[0];
++ if (!board || !workspaceId) return result;
++ const parent = alias(taskTable, "parent");
++ const parents = await db
++ .selectDistinct({ id: parent.id })
++ .from(taskRelationTable)
++ .innerJoin(parent, eq(taskRelationTable.sourceTaskId, parent.id))
++ .where(
++ and(
++ eq(taskRelationTable.targetTaskId, taskId),
++ eq(taskRelationTable.relationType, "subtask"),
++ eq(parent.projectId, result.projectId),
++ ),
++ );
++ const counts = await boundedTaskRead((tx) =>
++ getSubtaskCounts(
++ tx,
++ [taskId, ...parents.map((task) => task.id)],
++ workspaceId,
++ false,
++ ),
++ );
++ return {
++ ...result,
++ subtaskCounts: counts.get(taskId) ?? { completed: 0, total: 0 },
++ parentSubtaskCounts: parents.map(({ id }) => ({
++ taskId: id,
++ ...(counts.get(id) ?? { completed: 0, total: 0 }),
++ })),
++ };
}
export default getTask;
diff --cc apps/api/src/task/index.ts
index a11c754a9,966fa9dec..08f8c21e9
--- a/apps/api/src/task/index.ts
+++ b/apps/api/src/task/index.ts
@@@ -244,9 -251,9 +251,13 @@@ const getTaskRoute = createRoute(
path: "/{id}",
tags: ["Tasks"],
summary: "Get task",
-- description: "Get a single task by ID, with its assignee's name resolved.",
++ description:
++ "Get a single task by ID, with its assignee name. The board view omits descriptions above 64 KiB and includes task and same-project parent subtask progress.",
middleware: [workspaceAccess.fromTask()] as const,
-- request: { params: taskParam },
++ request: {
++ params: taskParam,
++ query: z.object({ view: z.enum(["detail", "board"]).optional() }),
++ },
responses: {
200: jsonResponse("Task details", taskWithAssigneeSchema),
400: errorResponse(
@@@ -799,7 -806,7 +810,7 @@@ const task = apiRouter<BaseVariables &
.openapi(getTaskRoute, async (c) => {
const { id } = c.req.valid("param");
-- const task = await getTask(id);
++ const task = await getTask(id, c.req.valid("query").view === "board");
return c.json(task, 200);
})
diff --cc apps/api/src/task/response.ts
index 839318660,839318660..bb21e9e3a
--- a/apps/api/src/task/response.ts
+++ b/apps/api/src/task/response.ts
@@@ -37,6 -37,6 +37,18 @@@ export const taskSchema =
export const taskWithAssigneeSchema = taskSchema
.extend({
++ subtaskCounts: z
++ .object({ completed: z.number(), total: z.number() })
++ .optional(),
++ parentSubtaskCounts: z
++ .array(
++ z.object({
++ taskId: z.string(),
++ completed: z.number(),
++ total: z.number(),
++ }),
++ )
++ .optional(),
assigneeName: z.string().nullable(),
assigneeId: z.string().nullable(),
})
diff --cc apps/docs/openapi.json
index 7367c34f0,539904536..f562fbf31
--- a/apps/docs/openapi.json
+++ b/apps/docs/openapi.json
@@@ -1024,6 -1024,6 +1024,43 @@@
{
"type": "object",
"properties": {
++ "subtaskCounts": {
++ "type": "object",
++ "properties": {
++ "completed": {
++ "type": "number"
++ },
++ "total": {
++ "type": "number"
++ }
++ },
++ "required": [
++ "completed",
++ "total"
++ ]
++ },
++ "parentSubtaskCounts": {
++ "type": "array",
++ "items": {
++ "type": "object",
++ "properties": {
++ "taskId": {
++ "type": "string"
++ },
++ "completed": {
++ "type": "number"
++ },
++ "total": {
++ "type": "number"
++ }
++ },
++ "required": [
++ "taskId",
++ "completed",
++ "total"
++ ]
++ }
++ },
"assigneeName": {
"type": [
"string",
@@@ -8987,7 -9012,7 +9049,7 @@@
"Tasks"
],
"summary": "Get task",
-- "description": "Get a single task by ID, with its assignee's name resolved.",
++ "description": "Get a single task by ID, with its assignee name. The board view omits descriptions above 64 KiB and includes task and same-project parent subtask progress.",
"parameters": [
{
"schema": {
@@@ -8996,6 -9021,6 +9058,18 @@@
"required": true,
"name": "id",
"in": "path"
++ },
++ {
++ "schema": {
++ "type": "string",
++ "enum": [
++ "detail",
++ "board"
++ ]
++ },
++ "required": false,
++ "name": "view",
++ "in": "query"
}
],
"responses": {
diff --cc apps/web/src/components/kanban-board/index.tsx
index b3d2a0c5a,6eb8bee02..8dbe059cb
--- a/apps/web/src/components/kanban-board/index.tsx
+++ b/apps/web/src/components/kanban-board/index.tsx
@@@ -160,18 -166,14 +167,21 @@@ 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;
+ 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;
+ 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 --cc apps/web/src/fetchers/project/get-public-project.ts
index 94bc4a5bb,bd3050d40..c6e077fc7
--- a/apps/web/src/fetchers/project/get-public-project.ts
+++ b/apps/web/src/fetchers/project/get-public-project.ts
@@@ -1,6 -1,5 +1,5 @@@
- import type { ProjectWithTasks } from "@/types/project";
import { client } from "@kaneo/libs";
--import type { InferRequestType } from "hono/client";
++import type { InferRequestType, InferResponseType } from "hono/client";
import { loadBoardPages } from "@/fetchers/task/load-board-pages";
import { HttpError } from "@/lib/http-error";
export type GetPublicProjectRequest = InferRequestType<
@@@ -9,28 -8,23 +8,33 @@@
async function getPublicProject(
{ id }: GetPublicProjectRequest,
signal?: AbortSignal,
- onProgress?: (board: ProjectWithTasks) => void,
++ onProgress?: (
++ board: Omit<
++ InferResponseType<(typeof client)["public-project"][":id"]["$get"], 200>,
++ "pagination"
++ >,
++ ) => 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 --cc apps/web/src/fetchers/task/get-task.ts
index 13c42d35e,13c42d35e..949256acd
--- a/apps/web/src/fetchers/task/get-task.ts
+++ b/apps/web/src/fetchers/task/get-task.ts
@@@ -6,8 -6,8 +6,11 @@@ export type GetTaskRequest = InferReque
(typeof client)["task"][":id"]["$get"]
>["param"];
--async function getTask(taskId: string) {
-- const response = await client.task[":id"].$get({ param: { id: taskId } });
++async function getTask(taskId: string, view: "detail" | "board" = "detail") {
++ const response = await client.task[":id"].$get({
++ param: { id: taskId },
++ query: { view },
++ });
if (!response.ok) {
throw new HttpError(response.status, await response.text());
diff --cc apps/web/src/fetchers/task/get-tasks.ts
index db8063d18,0f4a1c4e8..943169525
--- a/apps/web/src/fetchers/task/get-tasks.ts
+++ b/apps/web/src/fetchers/task/get-tasks.ts
@@@ -1,32 -1,23 +1,37 @@@
import { client } from "@kaneo/libs";
- import type { ProjectWithTasks } from "@/types/project";
++import type { InferResponseType } from "hono/client";
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,
++ onProgress?: (
++ board: InferResponseType<
++ (typeof client)["task"]["tasks"][":projectId"]["$get"],
++ 200
++ >["data"],
++ ) => 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 --cc apps/web/src/hooks/mutations/task/use-update-task-description.ts
index a6c1de81f,baae2acd0..0fedec11c
--- 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,3 -1,3 +1,7 @@@
++import {
++ getBoardCacheVersion,
++ markBoardCacheChanged,
++} from "@/lib/board-cache-version";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import updateTaskDescription from "@/fetchers/task/update-task-description";
import type Task from "@/types/task";
@@@ -8,13 -7,13 +12,25 @@@ export function useUpdateTaskDescriptio
return useMutation({
mutationFn: (task: Task) => updateTaskDescription(task.id, task),
- onSuccess: (updated, variables) => {
- onSuccess: (_, variables) => {
++ onMutate: (task: Task) => {
++ markBoardCacheChanged(queryClient, task.projectId, task.id);
++ return {
++ version: getBoardCacheVersion(queryClient, task.projectId, task.id),
++ };
++ },
++ onSuccess: (updated, variables, context) => {
queryClient.invalidateQueries({
queryKey: ["task", variables.id],
});
- updateBoardTaskCache(queryClient, variables.projectId, variables.id, {
- description: updated.description,
- queryClient.invalidateQueries({
- queryKey: ["tasks", variables.projectId],
-- });
++ updateBoardTaskCache(
++ queryClient,
++ variables.projectId,
++ variables.id,
++ {
++ description: updated.description,
++ },
++ context?.version,
++ );
queryClient.invalidateQueries({
queryKey: ["notifications"],
});
diff --cc apps/web/src/hooks/mutations/task/use-update-task-due-date.ts
index 066a0d440,1a0e6d924..702991da0
--- 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,3 -1,3 +1,7 @@@
++import {
++ getBoardCacheVersion,
++ markBoardCacheChanged,
++} from "@/lib/board-cache-version";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import updateTaskDueDate from "@/fetchers/task/update-task-due-date";
import type Task from "@/types/task";
@@@ -8,13 -7,13 +12,25 @@@ export function useUpdateTaskDueDate()
return useMutation({
mutationFn: (task: Task) => updateTaskDueDate(task.id, task),
- onSuccess: (updated, variables) => {
- onSuccess: (_, variables) => {
++ onMutate: (task: Task) => {
++ markBoardCacheChanged(queryClient, task.projectId, task.id);
++ return {
++ version: getBoardCacheVersion(queryClient, task.projectId, task.id),
++ };
++ },
++ onSuccess: (updated, variables, context) => {
queryClient.invalidateQueries({
queryKey: ["task", variables.id],
});
- updateBoardTaskCache(queryClient, variables.projectId, variables.id, {
- dueDate: updated.dueDate,
- queryClient.invalidateQueries({
- queryKey: ["tasks", variables.projectId],
-- });
++ updateBoardTaskCache(
++ queryClient,
++ variables.projectId,
++ variables.id,
++ {
++ dueDate: updated.dueDate,
++ },
++ context?.version,
++ );
queryClient.invalidateQueries({
queryKey: ["notifications"],
});
diff --cc apps/web/src/hooks/mutations/task/use-update-task-status-priority.ts
index b0c279143,fb1523351..fed1edd2b
--- 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,3 -1,3 +1,7 @@@
++import {
++ getBoardCacheVersion,
++ markBoardCacheChanged,
++} from "@/lib/board-cache-version";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import updateTaskPriority from "@/fetchers/task/update-task-priority";
import type Task from "@/types/task";
@@@ -8,13 -7,13 +12,25 @@@ export function useUpdateTaskPriority(
return useMutation({
mutationFn: (task: Task) => updateTaskPriority(task.id, task),
- onSuccess: (updated, variables) => {
- onSuccess: (_, variables) => {
++ onMutate: (task: Task) => {
++ markBoardCacheChanged(queryClient, task.projectId, task.id);
++ return {
++ version: getBoardCacheVersion(queryClient, task.projectId, task.id),
++ };
++ },
++ onSuccess: (updated, variables, context) => {
queryClient.invalidateQueries({
queryKey: ["task", variables.id],
});
- updateBoardTaskCache(queryClient, variables.projectId, variables.id, {
- priority: updated.priority,
- queryClient.invalidateQueries({
- queryKey: ["tasks", variables.projectId],
-- });
++ updateBoardTaskCache(
++ queryClient,
++ variables.projectId,
++ variables.id,
++ {
++ priority: updated.priority,
++ },
++ context?.version,
++ );
queryClient.invalidateQueries({
queryKey: ["notifications"],
});
diff --cc apps/web/src/hooks/mutations/task/use-update-task-title.ts
index 2f421b6da,20f90d0eb..a38f0eac1
--- 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,3 -1,3 +1,7 @@@
++import {
++ getBoardCacheVersion,
++ markBoardCacheChanged,
++} from "@/lib/board-cache-version";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import updateTaskTitle from "@/fetchers/task/update-task-title";
import type Task from "@/types/task";
@@@ -8,13 -7,13 +12,25 @@@ export function useUpdateTaskTitle()
return useMutation({
mutationFn: (task: Task) => updateTaskTitle(task.id, task),
- onSuccess: (updated, variables) => {
- onSuccess: (_, variables) => {
++ onMutate: (task: Task) => {
++ markBoardCacheChanged(queryClient, task.projectId, task.id);
++ return {
++ version: getBoardCacheVersion(queryClient, task.projectId, task.id),
++ };
++ },
++ onSuccess: (updated, variables, context) => {
queryClient.invalidateQueries({
queryKey: ["task", variables.id],
});
- updateBoardTaskCache(queryClient, variables.projectId, variables.id, {
- title: updated.title,
- queryClient.invalidateQueries({
- queryKey: ["tasks", variables.projectId],
-- });
++ updateBoardTaskCache(
++ queryClient,
++ variables.projectId,
++ variables.id,
++ {
++ title: updated.title,
++ },
++ context?.version,
++ );
queryClient.invalidateQueries({
queryKey: ["notifications"],
});
diff --cc apps/web/src/hooks/queries/project/use-get-public-project.ts
index 44dedea16,3327c4f3a..21d93d6b0
--- 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,19 -1,12 +1,31 @@@
-import { useQuery } from "@tanstack/react-query";
++import { useState } from "react";
++import type getPublicProjectType from "@/fetchers/project/get-public-project";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
import getPublicProject from "@/fetchers/project/get-public-project";
function useGetPublicProject(id: string) {
- return useQuery({
+ const queryClient = useQueryClient();
- return useQuery({
++ const [progress, setProgress] =
++ useState<Awaited<ReturnType<typeof getPublicProjectType>>>();
++ const query = useQuery({
queryKey: ["public-project", id],
- queryFn: ({ signal }) => {
- queryFn: ({ signal }) => getPublicProject({ id }, signal),
++ queryFn: async ({ signal }) => {
++ setProgress(undefined);
+ const hasCachedBoard = !!queryClient.getQueryData(["public-project", id]);
- return getPublicProject({ id }, signal, (board) => {
- if (!hasCachedBoard)
- queryClient.setQueryData(["public-project", id], board);
- });
++ try {
++ return await getPublicProject({ id }, signal, (board) => {
++ if (!hasCachedBoard) setProgress(board);
++ });
++ } finally {
++ setProgress(undefined);
++ }
+ },
refetchOnMount: true,
});
++ return {
++ ...query,
++ data: query.data ?? (query.isFetching ? progress : undefined),
++ };
}
export default useGetPublicProject;
diff --cc apps/web/src/hooks/queries/task/use-get-tasks.test.tsx
index d0dd536c8,b9662d8f9..aca2840e5
--- a/apps/web/src/hooks/queries/task/use-get-tasks.test.tsx
+++ b/apps/web/src/hooks/queries/task/use-get-tasks.test.tsx
@@@ -85,3 -84,3 +85,34 @@@ describe("useGetTasks", () =>
expect(getTasks).toHaveBeenCalledTimes(2);
});
});
++
++it.each(["private", "public"])(
++ "does not cache incomplete %s pagination after failure and supports retry",
++ async (kind) => {
++ const key =
++ kind === "private" ? ["tasks", "failed"] : ["public-project", "failed"];
++ queryClient.setQueryDefaults(key, { retry: false });
++ const fetcher = kind === "private" ? getTasks : getPublicProject;
++ fetcher.mockImplementationOnce(async (...args) => {
++ args[2]({ id: "failed", columns: [{ tasks: [{ id: "partial" }] }] });
++ throw new Error("second page failed");
++ });
++ const { result } = renderHook(
++ () =>
++ kind === "private"
++ ? useGetTasks("failed")
++ : useGetPublicProject("failed"),
++ { wrapper: Wrapper },
++ );
++ await waitFor(() => expect(result.current.isError).toBe(true));
++ expect(result.current.data).toBeUndefined();
++ expect(queryClient.getQueryData(key)).toBeUndefined();
++ const completed = {
++ id: "failed",
++ columns: [{ tasks: [{ id: "partial" }, { id: "page-two" }] }],
++ };
++ fetcher.mockResolvedValue(completed);
++ await result.current.refetch();
++ await waitFor(() => expect(result.current.data).toEqual(completed));
++ },
++);
diff --cc apps/web/src/hooks/queries/task/use-get-tasks.ts
index 5dd97c625,4861dc978..7f9622af8
--- a/apps/web/src/hooks/queries/task/use-get-tasks.ts
+++ b/apps/web/src/hooks/queries/task/use-get-tasks.ts
@@@ -1,21 -1,14 +1,32 @@@
-import { useQuery } from "@tanstack/react-query";
++import { useState } from "react";
+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) {
- return useQuery({
+ const queryClient = useQueryClient();
- return useQuery({
++ const [progress, setProgress] =
++ useState<Awaited<ReturnType<typeof getTasks>>>();
++ const query = useQuery({
queryKey: ["tasks", projectId],
- queryFn: ({ signal }) => {
- queryFn: ({ signal }) => getTasks(projectId, signal),
++ queryFn: async ({ signal }) => {
++ setProgress(undefined);
+ markBoardCacheChanged(queryClient, projectId);
+ const hasCachedBoard = !!queryClient.getQueryData(["tasks", projectId]);
- return getTasks(projectId, signal, (board) => {
- if (!hasCachedBoard)
- queryClient.setQueryData(["tasks", projectId], board);
- });
++ try {
++ return await getTasks(projectId, signal, (board) => {
++ if (!hasCachedBoard) setProgress(board);
++ });
++ } finally {
++ setProgress(undefined);
++ }
+ },
refetchOnMount: true,
- refetchInterval: (query) =>
- isUnauthorizedError(query.state.error) ? false : 30000,
+ refetchOnWindowFocus: true,
enabled: !!projectId,
});
++ return {
++ ...query,
++ data: query.data ?? (query.isFetching ? progress : undefined),
++ };
}
diff --cc apps/web/src/hooks/use-project-websocket-cache.test.tsx
index fc16c84b6,000000000..206f7a2c2
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,151 -1,0 +1,200 @@@
+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");
++ 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();
++ }
++});
diff --cc apps/web/src/hooks/use-project-websocket.ts
index a2ea6022f,f52da8eb3..c09aad8fe
--- a/apps/web/src/hooks/use-project-websocket.ts
+++ b/apps/web/src/hooks/use-project-websocket.ts
@@@ -36,9 -29,6 +36,10 @@@ export function useProjectWebSocket(pro
// 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;
++ let needsReconcile = false;
++ let flushQueued = 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;
@@@ -61,16 -50,6 +62,12 @@@
ws.onopen = () => {
if (disposed || activeSocket !== ws) return;
- if (hasConnected) markBoardCacheChanged(queryClient, projectId);
- if (hasConnected)
- void queryClient.invalidateQueries({
- queryKey: ["tasks", projectId],
- });
++ needsReconcile = true;
++ flushPending();
+ 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();
@@@ -98,62 -86,6 +95,66 @@@
}
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,
++ `TASKS_REORDERED:${change.id}`,
+ JSON.stringify({ ...message, tasks: [change] }),
+ );
+ } else
- pendingMessages.set(message.taskId || message.type, event.data);
++ 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);
+ 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" ||
@@@ -164,81 -96,9 +165,97 @@@
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);
++ 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 {
+ void Promise.all([
- getTask(taskId),
++ getTask(taskId, "board"),
+ 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,
+ );
++ for (const progress of task.parentSubtaskCounts ?? []) {
++ 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],
+ });
+ });
+ }
+ }
if (message.type === "PROJECT_UPDATED") {
queryClient.invalidateQueries({ queryKey: ["projects"] });
@@@ -279,7 -139,7 +296,11 @@@
});
}
-- if (message.type === "TASK_UPDATED" && message.taskId) {
++ if (
++ (message.type === "TASK_UPDATED" ||
++ message.type === "TASK_MOVED") &&
++ message.taskId
++ ) {
queryClient.invalidateQueries({
queryKey: ["external-links", message.taskId],
});
@@@ -319,29 -172,10 +340,52 @@@
};
}
connect();
- const unsubscribe = queryClient.getQueryCache().subscribe(({ query }) => {
++ function flushPending() {
+ if (
- query.queryKey[0] !== "tasks" ||
- query.queryKey[1] !== projectId ||
- query.state.fetchStatus !== "idle" ||
- !pendingMessages.size
++ disposed ||
++ flushQueued ||
++ queryClient.getQueryState(["tasks", projectId])?.fetchStatus ===
++ "fetching"
+ )
+ return;
- const messages = Array.from(pendingMessages.values());
- pendingMessages.clear();
++ flushQueued = true;
+ queueMicrotask(() => {
- if (disposed || !activeSocket) return;
++ flushQueued = false;
++ if (
++ disposed ||
++ !activeSocket ||
++ queryClient.getQueryState(["tasks", projectId])?.fetchStatus ===
++ "fetching"
++ )
++ return;
++ if (needsReconcile) {
++ needsReconcile = false;
++ markBoardCacheChanged(queryClient, projectId);
++ void queryClient.invalidateQueries({
++ queryKey: ["tasks", projectId],
++ });
++ }
++ const messages = Array.from(pendingMessages.values());
++ pendingMessages.clear();
+ for (const data of messages)
+ activeSocket.onmessage?.(new MessageEvent("message", { data }));
+ });
++ }
++ const unsubscribe = queryClient.getQueryCache().subscribe(({ query }) => {
++ if (
++ query.queryKey[0] === "tasks" &&
++ query.queryKey[1] === projectId &&
++ query.state.fetchStatus === "idle"
++ )
++ flushPending();
+ });
return () => {
+ unsubscribe();
+ pendingMessages.clear();
disposed = true;
clearPing();
+ if (fallbackInterval !== null) clearInterval(fallbackInterval);
if (retryTimeout !== null) {
clearTimeout(retryTimeout);
}
diff --cc apps/web/src/lib/patch-board-task.test.ts
index f2192a5b0,000000000..aac63759d
mode 100644,000000..100644
--- a/apps/web/src/lib/patch-board-task.test.ts
+++ b/apps/web/src/lib/patch-board-task.test.ts
@@@ -1,84 -1,0 +1,116 @@@
+import { QueryClient } from "@tanstack/react-query";
+import { describe, expect, it } from "vite-plus/test";
+import type { ProjectWithTasks } from "@/types/project";
++import {
++ getBoardCacheVersion,
++ markBoardCacheChanged,
++} from "./board-cache-version";
+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);
+ });
+});
++
++it("rejects a late mutation response after a newer socket patch", () => {
++ const client = new QueryClient();
++ client.setQueryData(["tasks", "p"], board());
++ markBoardCacheChanged(client, "p", "a");
++ const version = getBoardCacheVersion(client, "p", "a");
++ markBoardCacheChanged(client, "p", "a");
++ client.setQueryData(
++ ["tasks", "p"],
++ patchBoardTask(board(), "a", { projectId: "p", title: "remote" }),
++ );
++ updateBoardTaskCache(client, "p", "a", { title: "late response" }, version);
++ expect(
++ client.getQueryData<ProjectWithTasks>(["tasks", "p"])?.columns[0].tasks[0]
++ .title,
++ ).toBe("remote");
++ client.clear();
++});
++it("defers descriptions exceeding the UTF-8 board limit", () => {
++ const updated = patchBoardTask(board(), "a", {
++ projectId: "p",
++ description: "😀".repeat(20000),
++ });
++ expect(updated?.columns[0].tasks[0]).toMatchObject({
++ description: null,
++ descriptionDeferred: true,
++ });
++});
diff --cc apps/web/src/lib/patch-board-task.ts
index 07d71d83f,000000000..213cc5990
mode 100644,000000..100644
--- a/apps/web/src/lib/patch-board-task.ts
+++ b/apps/web/src/lib/patch-board-task.ts
@@@ -1,46 -1,0 +1,57 @@@
+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>,
+) {
++ let patch = update;
++ if (patch && "description" in patch) {
++ const deferred =
++ new TextEncoder().encode(patch.description ?? "").byteLength > 64 * 1024;
++ patch = {
++ ...patch,
++ description: deferred ? null : patch.description,
++ descriptionDeferred: patch.descriptionDeferred ?? deferred,
++ };
++ }
+ 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 belongs = patch && patch.projectId === board.id;
++ const task =
++ belongs && patch
++ ? ({
++ ...existing,
++ ...patch,
++ assigneeId:
++ "userId" in patch
++ ? (patch.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 --cc apps/web/src/lib/update-board-task-cache.ts
index 3f710525e,000000000..c68abd78e
mode 100644,000000..100644
--- a/apps/web/src/lib/update-board-task-cache.ts
+++ b/apps/web/src/lib/update-board-task-cache.ts
@@@ -1,40 -1,0 +1,43 @@@
+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>,
++ expectedVersion?: string,
+) {
- markBoardCacheChanged(queryClient, projectId, taskId);
- const version = getBoardCacheVersion(queryClient, projectId, taskId);
++ if (expectedVersion === undefined)
++ markBoardCacheChanged(queryClient, projectId, taskId);
++ const version =
++ expectedVersion ?? 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();
+}
diff --cc apps/web/src/routes/_layout/_authenticated/dashboard/workspace/$workspaceId/project/$projectId/board.tsx
index 00190d305,00190d305..e929f9917
--- a/apps/web/src/routes/_layout/_authenticated/dashboard/workspace/$workspaceId/project/$projectId/board.tsx
+++ b/apps/web/src/routes/_layout/_authenticated/dashboard/workspace/$workspaceId/project/$projectId/board.tsx
@@@ -85,7 -85,7 +85,12 @@@ function RouteComponent()
const { projectId, workspaceId } = Route.useParams();
const { taskId } = Route.useSearch();
const navigate = useNavigate();
-- const { data } = useGetTasks(projectId);
++ const {
++ data,
++ isError: boardError,
++ isFetching: boardFetching,
++ refetch: retryBoard,
++ } = useGetTasks(projectId);
const { project, setProject } = useProjectStore();
const { viewMode, setViewMode } = useUserPreferencesStore();
const [isTaskModalOpen, setIsTaskModalOpen] = useState(false);
@@@ -305,19 -305,19 +310,31 @@@
"bg-background": !background,
})}
>
-- {sortedProject ? (
++ {boardError ? (
++ <p role="alert" className="p-4 text-destructive">
++ {t("tasks:calendar.loadError")}{" "}
++ <button
++ type="button"
++ className="underline"
++ onClick={() => void retryBoard()}
++ >
++ {t("tasks:descriptionRetry")}
++ </button>
++ </p>
++ ) : sortedProject ? (
viewMode === "board" ? (
<KanbanBoard
project={sortedProject}
disableDragDrop={
-- sort.field !== "position" && sort.field !== "number"
++ boardFetching ||
++ (sort.field !== "position" && sort.field !== "number")
}
sortedByNumber={sort.field === "number"}
/>
) : (
<ListView
project={sortedProject}
-- disableDragDrop={sort.field !== "position"}
++ disableDragDrop={boardFetching || sort.field !== "position"}
/>
)
) : (
diff --cc tests/api-integration/subtask-counts.test.ts
index ce6426577,ce6426577..6c7b144b6
--- a/tests/api-integration/subtask-counts.test.ts
+++ b/tests/api-integration/subtask-counts.test.ts
@@@ -519,3 -519,3 +519,31 @@@ describe("subtask counter mutation path
}
});
});
++
++it("returns bounded board refresh descriptions and current parent progress", async () => {
++ await resetTestDatabase();
++ const member = await createWorkspaceMember();
++ const { project } = await createProjectFixture({
++ workspaceId: member.workspace.id,
++ });
++ const parent = await addTask(project.id);
++ const child = await addTask(project.id, "done");
++ await relate(parent.id, child.id);
++ await db
++ .update(schema.taskTable)
++ .set({ description: "😀".repeat(20000) })
++ .where(eq(schema.taskTable.id, child.id));
++ mockAuthenticatedSession(member.user);
++ const response = await createApp().app.request(
++ `/api/task/${child.id}?view=board`,
++ );
++ expect(response.status).toBe(200);
++ const body = await response.json();
++ expect(body).toMatchObject({
++ description: null,
++ descriptionDeferred: true,
++ subtaskCounts: { completed: 0, total: 0 },
++ parentSubtaskCounts: [{ taskId: parent.id, completed: 1, total: 1 }],
++ });
++ expect(body).not.toHaveProperty("workspaceId");
++});