⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
fix(board): reconcile page boundaries and remote label edits
Tin25d5a12e21ff
diff --git a/apps/api/src/label/controllers/update-label.ts b/apps/api/src/label/controllers/update-label.tsindex cd465ec33..1586ee247 100644--- a/apps/api/src/label/controllers/update-label.ts+++ b/apps/api/src/label/controllers/update-label.ts@@ -1,10 +1,12 @@import { and, eq, isNotNull, isNull } from "drizzle-orm";import { HTTPException } from "hono/http-exception";import db from "../../database";-import { labelTable } from "../../database/schema";+import { labelTable, projectTable, taskTable } from "../../database/schema";++import { publishEvent } from "../../events";async function updateLabel(id: string, name: string, color: string) {- return db.transaction(async (tx) => {+ const result = await db.transaction(async (tx) => {const label = await tx.query.labelTable.findFirst({where: (label, { eq }) => eq(label.id, id),});@@ -44,8 +46,29 @@ async function updateLabel(id: string, name: string, color: string) {);}- return updatedLabel;+ // Find boards with the updated label. Publish only project IDs within+ // this workspace after the cascade commits.+ const projects = await tx+ .selectDistinct({ projectId: taskTable.projectId })+ .from(labelTable)+ .innerJoin(taskTable, eq(labelTable.taskId, taskTable.id))+ .innerJoin(projectTable, eq(taskTable.projectId, projectTable.id))+ .where(+ and(+ label.taskId+ ? eq(labelTable.id, id)+ : and(+ eq(labelTable.workspaceId, label.workspaceId ?? ""),+ eq(labelTable.name, name),+ ),+ eq(projectTable.workspaceId, label.workspaceId ?? ""),+ ),+ );+ return { updatedLabel, projects };});+ for (const { projectId } of result.projects)+ await publishEvent("project.updated", { projectId });+ return result.updatedLabel;}export default updateLabel;diff --git a/apps/web/src/hooks/use-project-websocket-cache.test.tsx b/apps/web/src/hooks/use-project-websocket-cache.test.tsxindex 8553e7531..b4ec76e64 100644--- a/apps/web/src/hooks/use-project-websocket-cache.test.tsx+++ b/apps/web/src/hooks/use-project-websocket-cache.test.tsx@@ -77,7 +77,7 @@ beforeEach(() => {mocks.client.setQueryData.mockImplementation((_key, value) => {mocks.board = typeof value === "function" ? value(mocks.board) : value;});- mocks.client.invalidateQueries.mockClear();+ mocks.client.invalidateQueries.mockReset();mocks.client.getQueryState.mockReset();mocks.subscribe.mockClear();});@@ -374,3 +374,43 @@ it("applies a remote reorder across virtual buckets without waiting for HTTP", (expect.objectContaining({ id: "a", status: "archived", columnId: null }),);});++it.each(["TASK_CREATED", "TASK_DELETED", "TASK_MOVED", "TASKS_REORDERED"])(+ "reconciles page boundaries after %s arrives during pagination",+ async (type) => {+ mocks.client.getQueryState.mockReturnValue({ fetchStatus: "fetching" });+ mocks.getTask.mockReset();+ renderHook(() => useProjectWebSocket("p"));+ Socket.current.message(type, {+ taskId: "a",+ tasks: [{ id: "a", position: 2 }],+ });+ Socket.current.message(type, {+ taskId: "b",+ tasks: [{ id: "b", position: 0 }],+ });+ expect(mocks.client.invalidateQueries).not.toHaveBeenCalledWith({+ queryKey: ["tasks", "p"],+ });+ mocks.client.getQueryState.mockReturnValue({ fetchStatus: "idle" });+ mocks.client.invalidateQueries.mockImplementation(({ queryKey }) => {+ if (queryKey[0] === "tasks")+ mocks.client.getQueryState.mockReturnValue({ fetchStatus: "fetching" });+ });+ const idle = () =>+ mocks.subscribe.mock.calls[0][0]({+ query: { queryKey: ["tasks", "p"], state: { fetchStatus: "idle" } },+ });+ idle();+ await Promise.resolve();+ mocks.client.getQueryState.mockReturnValue({ fetchStatus: "idle" });+ idle();+ await Promise.resolve();+ expect(+ mocks.client.invalidateQueries.mock.calls.filter(+ ([options]) => options.queryKey[0] === "tasks",+ ),+ ).toHaveLength(1);+ expect(mocks.getTask).not.toHaveBeenCalled();+ },+);diff --git a/apps/web/src/hooks/use-project-websocket.ts b/apps/web/src/hooks/use-project-websocket.tsindex 5076f1340..618b76516 100644--- a/apps/web/src/hooks/use-project-websocket.ts+++ b/apps/web/src/hooks/use-project-websocket.ts@@ -121,19 +121,38 @@ export function useProjectWebSocket(projectId: string) {"fetching";if (boardIsLoading) {if (- message.type === "TASKS_REORDERED" &&- Array.isArray(message.tasks)+ [+ "TASK_CREATED",+ "TASK_DELETED",+ "TASK_MOVED",+ "TASKS_REORDERED",+ ].includes(message.type)) {- 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,- );+ // Offset pages can skip unrelated boundary tasks when membership+ // or positions change. Reconcile after this fetch completes.+ needsReconcile = true;+ markBoardCacheChanged(queryClient, projectId);+ const ids =+ message.type === "TASKS_REORDERED"+ ? Array.isArray(message.tasks)+ ? message.tasks.map((task: { id: string }) => task.id)+ : []+ : message.taskId+ ? [message.taskId]+ : [];+ for (const id of ids) {+ queryClient.invalidateQueries({ queryKey: ["task", id] });+ if (message.type === "TASK_MOVED")+ queryClient.invalidateQueries({+ queryKey: ["external-links", id],+ });+ }+ return;+ }+ pendingMessages.set(+ `${message.type}:${message.taskId ?? ""}:${message.sourceTaskId ?? ""}:${message.targetTaskId ?? ""}`,+ event.data,+ );return;}if (message.type === "TASKS_REORDERED") {diff --git a/tests/api-integration/label-live-updates.test.ts b/tests/api-integration/label-live-updates.test.tsnew file mode 100644index 000000000..99d3735e5--- /dev/null+++ b/tests/api-integration/label-live-updates.test.ts@@ -0,0 +1,98 @@+import { beforeEach, expect, it, vi } from "vite-plus/test";+import db, { schema } from "../../apps/api/src/database";+import updateLabel from "../../apps/api/src/label/controllers/update-label";+import { resetTestDatabase } from "./helpers/database";+import {+ createWorkspaceMember,+ createProjectFixture,+} from "./helpers/fixtures";+const publish = vi.hoisted(() => vi.fn(async () => {}));+vi.mock("../../apps/api/src/events", () => ({ publishEvent: publish }));+beforeEach(async () => {+ await resetTestDatabase();+ publish.mockReset();+});+async function task(projectId: string, number: number) {+ const [row] = await db+ .insert(schema.taskTable)+ .values({ projectId, number, title: `Task ${number}`, status: "to-do" })+ .returning();+ return row;+}+it("announces committed workspace label edits once per affected board", async () => {+ const { workspace } = await createWorkspaceMember();+ const { project: first } = await createProjectFixture({+ workspaceId: workspace.id,+ });+ const { project: second } = await createProjectFixture({+ workspaceId: workspace.id,+ });+ const { workspace: otherWorkspace } = await createWorkspaceMember();+ const { project: foreign } = await createProjectFixture({+ workspaceId: otherWorkspace.id,+ });+ const [a, b, c, privateTask] = await Promise.all([+ task(first.id, 1),+ task(first.id, 2),+ task(second.id, 1),+ task(foreign.id, 1),+ ]);+ const [root] = await db+ .insert(schema.labelTable)+ .values({ workspaceId: workspace.id, name: "Old", color: "#000000" })+ .returning();+ await db.insert(schema.labelTable).values(+ [a, b, c].map((row) => ({+ taskId: row.id,+ workspaceId: workspace.id,+ name: "Old",+ color: "#000000",+ })),+ );+ await db.insert(schema.labelTable).values({+ taskId: privateTask.id,+ workspaceId: otherWorkspace.id,+ name: "Old",+ color: "#000000",+ });+ await updateLabel(root.id, "Renamed", "#123456");+ expect(publish.mock.calls.map((call) => call)).toEqual(+ expect.arrayContaining([+ ["project.updated", { projectId: first.id }],+ ["project.updated", { projectId: second.id }],+ ]),+ );+ expect(publish).toHaveBeenCalledTimes(2);+ const labels = await db.query.labelTable.findMany();+ expect(+ labels+ .filter((label) => label.workspaceId === workspace.id)+ .every((label) => label.name === "Renamed" && label.color === "#123456"),+ ).toBe(true);+ expect(labels.find((label) => label.taskId === privateTask.id)?.name).toBe(+ "Old",+ );+});+it("announces a direct task label recolor and emits nothing for a failed edit", async () => {+ const { workspace } = await createWorkspaceMember();+ const { project } = await createProjectFixture({ workspaceId: workspace.id });+ const row = await task(project.id, 1);+ const [label] = await db+ .insert(schema.labelTable)+ .values({+ taskId: row.id,+ workspaceId: workspace.id,+ name: "Bug",+ color: "#000000",+ })+ .returning();+ await updateLabel(label.id, "Bug", "#123456");+ expect(publish.mock.calls).toEqual([+ ["project.updated", { projectId: project.id }],+ ]);+ publish.mockClear();+ await expect(updateLabel("missing", "Name", "#000000")).rejects.toThrow(+ "Label not found",+ );+ expect(publish).not.toHaveBeenCalled();+});