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): reconcile status repairs and public page edits

Tin606886013d26
diff --git a/apps/api/src/task/controllers/bulk-update-tasks.ts b/apps/api/src/task/controllers/bulk-update-tasks.ts
index 0b209267a..0b8114226 100644
--- a/apps/api/src/task/controllers/bulk-update-tasks.ts
+++ b/apps/api/src/task/controllers/bulk-update-tasks.ts
@@ -445,11 +445,27 @@ async function bulkUpdateTasks({
const { updatedTasks, beforeById } = await db.transaction(async (tx) => {
const before = await tx
- .select({ id: taskTable.id, dueDate: taskTable.dueDate })
+ .select({
+ id: taskTable.id,
+ projectId: taskTable.projectId,
+ dueDate: taskTable.dueDate,
+ })
.from(taskTable)
.where(inArray(taskTable.id, foundIds))
.orderBy(asc(taskTable.id))
.for("update");
+ const originalProjects = new Map(
+ tasks.map((task) => [task.id, task.projectId]),
+ );
+ if (
+ before.length !== foundIds.length ||
+ before.some(
+ (task) => task.projectId !== originalProjects.get(task.id),
+ )
+ )
+ throw new HTTPException(409, {
+ message: "Tasks changed projects; retry the operation",
+ });
const beforeById = new Map(before.map((task) => [task.id, task]));
const changedIds = before
.filter((task) => task.dueDate?.getTime() !== parsedDate?.getTime())
diff --git a/apps/api/src/task/controllers/get-tasks.ts b/apps/api/src/task/controllers/get-tasks.ts
index fb60199a0..f606f3952 100644
--- a/apps/api/src/task/controllers/get-tasks.ts
+++ b/apps/api/src/task/controllers/get-tasks.ts
@@ -11,6 +11,7 @@ import {
type SQLWrapper,
sql,
} from "drizzle-orm";
+import { alias } from "drizzle-orm/pg-core";
import { HTTPException } from "hono/http-exception";
import {
columnTable,
@@ -18,6 +19,7 @@ import {
labelTable,
projectTable,
taskTable,
+ taskRelationTable,
userTable,
} from "../../database/schema";
import { boundedTaskRead, type TaskReadDatabase } from "../bounded-read";
@@ -27,6 +29,7 @@ import {
descriptionDeferred,
projectDescriptionDeferred,
} from "../description-pages";
+import { taskIsCompleted } from "../task-is-completed";
import { getSubtaskCounts } from "../get-subtask-counts";
export type GetTasksOptions = {
@@ -80,7 +83,7 @@ function buildOrderBy(
return (sortOrder === "desc" ? desc : asc)(sortValue(sortBy));
}
-function membershipRevision(
+function boardRevision(
publicOnly: boolean | undefined,
fields: SQLWrapper[],
): SQL<string> {
@@ -97,6 +100,9 @@ async function getTasksPage(
const [project] = await db
.select({
...getTableColumns(projectTable),
+ revision: options.publicOnly
+ ? sql<string>`${projectTable}.xmin::text`
+ : sql<string>`'0'`,
description: boardProjectDescription,
descriptionDeferred: projectDescriptionDeferred,
})
@@ -146,17 +152,26 @@ async function getTasksPage(
options.sortOrder ?? "asc",
);
- const [taskCount] = await db
+ const taskCountQuery = db
.select({
count: sql<number>`count(*)`,
- revision: membershipRevision(options.publicOnly, [
+ revision: boardRevision(options.publicOnly, [
taskTable.id,
sortValue(options.sortBy),
taskTable.status,
+ // Row versions detect content edits without hashing large descriptions.
+ sql`${taskTable}.xmin::text`,
+ userTable.name,
+ userTable.image,
]),
})
.from(taskTable)
- .where(whereClause);
+ .$dynamic();
+ const [taskCount] = await (
+ options.publicOnly
+ ? taskCountQuery.leftJoin(userTable, eq(taskTable.userId, userTable.id))
+ : taskCountQuery
+ ).where(whereClause);
const total = Number(taskCount?.count ?? 0);
@@ -306,7 +321,7 @@ async function getTasksPage(
const [columnCount] = await db
.select({
count: sql<number>`count(*)`,
- revision: membershipRevision(options.publicOnly, [
+ revision: boardRevision(options.publicOnly, [
columnTable.id,
columnTable.slug,
columnTable.position,
@@ -325,7 +340,7 @@ async function getTasksPage(
const [labels] = await db
.select({
count: sql<number>`count(*)`,
- revision: membershipRevision(options.publicOnly, [
+ revision: boardRevision(options.publicOnly, [
labelTable.id,
labelTable.taskId,
labelTable.name,
@@ -337,9 +352,10 @@ async function getTasksPage(
const [links] = await db
.select({
count: sql<number>`count(*)`,
- revision: membershipRevision(options.publicOnly, [
+ revision: boardRevision(options.publicOnly, [
externalLinkTable.id,
externalLinkTable.taskId,
+ sql`${externalLinkTable}.xmin::text`,
]),
})
.from(externalLinkTable)
@@ -350,6 +366,55 @@ async function getTasksPage(
linkRevision = links?.revision ?? "0";
}
+ let publicRelatedRevision = "0";
+ if (options.publicOnly) {
+ // Every task page must detect edits to cards or metadata loaded earlier.
+ const [labels] = await db
+ .select({
+ revision: boardRevision(true, [
+ labelTable.id,
+ labelTable.taskId,
+ labelTable.name,
+ labelTable.color,
+ ]),
+ })
+ .from(labelTable)
+ .innerJoin(taskTable, eq(labelTable.taskId, taskTable.id))
+ .where(whereClause);
+ const [links] = await db
+ .select({
+ revision: boardRevision(true, [
+ externalLinkTable.id,
+ sql`${externalLinkTable}.xmin::text`,
+ ]),
+ })
+ .from(externalLinkTable)
+ .innerJoin(taskTable, eq(externalLinkTable.taskId, taskTable.id))
+ .where(whereClause);
+ const parent = alias(taskTable, "board_parent");
+ const [children] = await db
+ .select({
+ revision: boardRevision(true, [
+ taskRelationTable.id,
+ taskTable.id,
+ taskIsCompleted,
+ ]),
+ })
+ .from(taskRelationTable)
+ .innerJoin(parent, eq(taskRelationTable.sourceTaskId, parent.id))
+ .innerJoin(taskTable, eq(taskRelationTable.targetTaskId, taskTable.id))
+ .innerJoin(projectTable, eq(taskTable.projectId, projectTable.id))
+ .where(
+ and(
+ eq(parent.projectId, projectId),
+ eq(taskRelationTable.relationType, "subtask"),
+ eq(projectTable.workspaceId, project.workspaceId),
+ eq(projectTable.isPublic, true),
+ ),
+ );
+ publicRelatedRevision = `${labels?.revision}:${links?.revision}:${children?.revision}`;
+ }
+
const columns = projectColumns.map((column) => ({
id: column.slug,
slug: column.slug,
@@ -404,7 +469,7 @@ async function getTasksPage(
total,
...(options.publicOnly
? {
- revision: `${total}:${taskCount?.revision}:${columnCount?.count}:${columnCount?.revision}`,
+ revision: `${project.revision}:${total}:${taskCount?.revision}:${columnCount?.count}:${columnCount?.revision}:${publicRelatedRevision}`,
relatedRevision: `${labelCount}:${labelRevision}:${linkCount}:${linkRevision}`,
}
: {}),
diff --git a/apps/api/src/task/controllers/task-mutation-effects.ts b/apps/api/src/task/controllers/task-mutation-effects.ts
index 46c7d5d98..3d2241d29 100644
--- a/apps/api/src/task/controllers/task-mutation-effects.ts
+++ b/apps/api/src/task/controllers/task-mutation-effects.ts
@@ -9,6 +9,7 @@ import {
import { publishEvent } from "../../events";
import createNotification from "../../notification/controllers/create-notification";
import { deleteOrphanedAssets } from "../../storage/cleanup-assets";
+import { getSubtaskParentProjects } from "../get-subtask-parent-projects";
import { parseMentionIds } from "../../utils/parse-mentions";
type Task = typeof taskTable.$inferSelect;
@@ -22,7 +23,7 @@ type Changes = Partial<
export type TaskBefore = Pick<
Task,
"id" | "projectId" | "title" | "status" | "priority" | "userId" | "dueDate"
-> & { description?: string | null };
+> & { description?: string | null; columnId?: string | null };
export async function recordTaskMutation(
tx: Transaction,
@@ -80,12 +81,21 @@ export async function publishTaskMutation(
? { skipSubtaskParentRefresh: true }
: {}),
});
- if (!options.skipRelationRefresh)
- await publishEvent("task-relation.refresh", {
- projectId: after.projectId,
- userId,
- });
}
+ const columnChanged =
+ (!options.fields || options.fields.includes("status")) &&
+ before.columnId !== undefined &&
+ after.columnId !== undefined &&
+ before.columnId !== after.columnId;
+ if (columnChanged && !changed("status") && !options.skipSubtaskParentRefresh)
+ await publishEvent("subtask-parents.refresh", {
+ projects: await getSubtaskParentProjects([after.id]),
+ });
+ if (!options.skipRelationRefresh && (changed("status") || columnChanged))
+ await publishEvent("task-relation.refresh", {
+ projectId: after.projectId,
+ userId,
+ });
if (changed("title"))
await publishEvent("task.title_changed", {
...common,
diff --git a/apps/api/src/task/controllers/update-task-status.ts b/apps/api/src/task/controllers/update-task-status.ts
index 5e76fe8d0..f949264b1 100644
--- a/apps/api/src/task/controllers/update-task-status.ts
+++ b/apps/api/src/task/controllers/update-task-status.ts
@@ -2,6 +2,7 @@ import { and, eq } from "drizzle-orm";
import { HTTPException } from "hono/http-exception";
import { withLockedTask } from "./with-locked-task";
import { columnTable, taskTable } from "../../database/schema";
+import { publishEvent } from "../../events";
import { publishTaskMutation } from "./task-mutation-effects";
import { assertValidTaskStatus } from "../validate-task-fields";
@@ -46,6 +47,16 @@ async function updateTaskStatus({
fields: ["status"],
});
+ if (
+ existingTask.status === updatedTask.status &&
+ existingTask.columnId !== updatedTask.columnId
+ )
+ await publishEvent("task.updated", {
+ taskId: updatedTask.id,
+ projectId: updatedTask.projectId,
+ userId: currentUserId,
+ });
+
return updatedTask;
}
diff --git a/apps/api/src/task/controllers/update-task.ts b/apps/api/src/task/controllers/update-task.ts
index 48278edb3..ca5d57adc 100644
--- a/apps/api/src/task/controllers/update-task.ts
+++ b/apps/api/src/task/controllers/update-task.ts
@@ -97,6 +97,7 @@ async function updateTask(
description:
description === undefined ? sql<null>`null` : taskTable.description,
status: taskTable.status,
+ columnId: taskTable.columnId,
position: taskTable.position,
projectId: taskTable.projectId,
})
diff --git a/apps/api/src/task/response.ts b/apps/api/src/task/response.ts
index 293e16685..7ea9e1528 100644
--- a/apps/api/src/task/response.ts
+++ b/apps/api/src/task/response.ts
@@ -159,7 +159,7 @@ export const boardSchema = z
}),
revision: z.string().optional().openapi({
description:
- "Public board task and column membership and ordering revision. Restart pagination if it changes between task or related pages.",
+ "Public board content, membership and ordering revision, including related records and visible subtask progress. Restart pagination if it changes between task or related pages.",
}),
})
.openapi({
diff --git a/apps/docs/openapi.json b/apps/docs/openapi.json
index 60dcc26e1..454d08c9b 100644
--- a/apps/docs/openapi.json
+++ b/apps/docs/openapi.json
@@ -343,7 +343,7 @@
},
"revision": {
"type": "string",
- "description": "Public board task and column membership and ordering revision. Restart pagination if it changes between task or related pages."
+ "description": "Public board content, membership and ordering revision, including related records and visible subtask progress. Restart pagination if it changes between task or related pages."
}
},
"required": [
diff --git a/tests/api-integration/task-mutation-parity.test.ts b/tests/api-integration/task-mutation-parity.test.ts
index f501c304b..33c5b8e0a 100644
--- a/tests/api-integration/task-mutation-parity.test.ts
+++ b/tests/api-integration/task-mutation-parity.test.ts
@@ -284,3 +284,107 @@ it("validates status and assignment without a second pool client inside the muta
}),
).toMatchObject({ status: "done", userId: user.id });
});
+
+it.each(["single", "full"])(
+ "%s status repairs notify clients without recording a status transition",
+ async (mode) => {
+ const { user, workspace } = await createWorkspaceMember();
+ const { project } = await createProjectFixture({
+ workspaceId: workspace.id,
+ });
+ const column = await db.query.columnTable.findFirst({
+ where: eq(schema.columnTable.slug, "to-do"),
+ });
+ const [task] = await db
+ .insert(schema.taskTable)
+ .values({
+ projectId: project.id,
+ title: "Legacy task",
+ status: "to-do",
+ columnId: null,
+ })
+ .returning();
+ if (mode === "single")
+ await updateTaskStatus({
+ id: task.id,
+ status: task.status,
+ currentUserId: user.id,
+ });
+ else
+ await updateTask(
+ task.id,
+ task.title,
+ task.status,
+ undefined,
+ undefined,
+ project.id,
+ undefined,
+ task.priority,
+ task.position,
+ undefined,
+ user.id,
+ );
+ expect(
+ (
+ await db.query.taskTable.findFirst({
+ where: eq(schema.taskTable.id, task.id),
+ })
+ )?.columnId,
+ ).toBe(column?.id);
+ expect(publish).toHaveBeenCalledWith(
+ "task.updated",
+ expect.objectContaining({ taskId: task.id, projectId: project.id }),
+ );
+ expect(publish).toHaveBeenCalledWith(
+ "task-relation.refresh",
+ expect.objectContaining({ projectId: project.id }),
+ );
+ expect(
+ publish.mock.calls.some(([type]) => type === "task.status_changed"),
+ ).toBe(false);
+ },
+);
+
+it("rejects a bulk due-date update after a task moves out of the authorized project", async () => {
+ const { user, workspace } = await createWorkspaceMember();
+ const { project } = await createProjectFixture({ workspaceId: workspace.id });
+ const other = await createWorkspaceMember();
+ const { project: foreign } = await createProjectFixture({
+ workspaceId: other.workspace.id,
+ });
+ const dueDate = new Date("2030-01-01");
+ const [task] = await db
+ .insert(schema.taskTable)
+ .values({ projectId: project.id, title: "Moved task", dueDate })
+ .returning();
+ await db
+ .insert(schema.taskReminderSentTable)
+ .values({ taskId: task.id, reminderType: "due_today" });
+ const transaction = db.transaction.bind(db);
+ vi.spyOn(getDatabase(), "transaction").mockImplementationOnce(
+ async (apply, config) => {
+ await db
+ .update(schema.taskTable)
+ .set({ projectId: foreign.id })
+ .where(eq(schema.taskTable.id, task.id));
+ return transaction(apply, config);
+ },
+ );
+ await expect(
+ bulkUpdateTasks({
+ taskIds: [task.id],
+ operation: "updateDueDate",
+ value: null,
+ userId: user.id,
+ }),
+ ).rejects.toMatchObject({ status: 409 });
+ expect(
+ (
+ await db.query.taskTable.findFirst({
+ where: eq(schema.taskTable.id, task.id),
+ })
+ )?.dueDate,
+ ).toEqual(dueDate);
+ expect(await db.query.taskReminderSentTable.findMany()).toHaveLength(1);
+ expect(publish).not.toHaveBeenCalled();
+});
diff --git a/tests/api-integration/task-pagination.test.ts b/tests/api-integration/task-pagination.test.ts
index 6c337d458..d6f85a7b0 100644
--- a/tests/api-integration/task-pagination.test.ts
+++ b/tests/api-integration/task-pagination.test.ts
@@ -246,7 +246,7 @@ it.each(["create", "delete", "move", "reorder"])(
},
);
-it("detects title-order boundary shifts while ordinary position-order edits remain stable", async () => {
+it("detects task edits between public pages regardless of sort order", async () => {
const { app, project, tasks } = await fixture(237, true);
mockAnonymousSession();
const path = `/api/public-project/${project.id}?limit=100`;
@@ -259,9 +259,90 @@ it("detects title-order boundary shifts while ordinary position-order edits rema
.where(eq(schema.taskTable.id, tasks[0].id));
expect(
(await (await app.request(path + "&page=2")).json()).pagination.revision,
- ).toBe(position);
+ ).not.toBe(position);
expect(
(await (await app.request(path + "&page=2&sortBy=title")).json()).pagination
.revision,
).not.toBe(title);
});
+
+it.each(["label", "link", "assignee", "project", "subtask"])(
+ "detects a %s edit to an earlier public page while loading a later page",
+ async (change) => {
+ const { app, project, tasks, member } = await fixture(2, true);
+ const task = tasks[0];
+ await db
+ .update(schema.taskTable)
+ .set({ userId: member.user.id })
+ .where(eq(schema.taskTable.id, task.id));
+ const [label] = await db
+ .insert(schema.labelTable)
+ .values({
+ taskId: task.id,
+ workspaceId: member.workspace.id,
+ name: "Before",
+ color: "red",
+ })
+ .returning();
+ const [link] = await db
+ .insert(schema.externalLinkTable)
+ .values({
+ taskId: task.id,
+ resourceType: "pull_request",
+ externalId: "1",
+ url: "https://example.com/pr/1",
+ metadata: JSON.stringify({ merged: false }),
+ })
+ .returning();
+ const { project: childProject } = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ });
+ await db
+ .update(schema.projectTable)
+ .set({ isPublic: true })
+ .where(eq(schema.projectTable.id, childProject.id));
+ const [child] = await db
+ .insert(schema.taskTable)
+ .values({ projectId: childProject.id, title: "Child", status: "to-do" })
+ .returning();
+ await db.insert(schema.taskRelationTable).values({
+ sourceTaskId: task.id,
+ targetTaskId: child.id,
+ relationType: "subtask",
+ });
+ mockAnonymousSession();
+ const path = `/api/public-project/${project.id}?limit=1`;
+ const before = (await (await app.request(path)).json()).pagination.revision;
+ expect(
+ (await (await app.request(path + "&page=2")).json()).pagination.revision,
+ ).toBe(before);
+ if (change === "label")
+ await db
+ .update(schema.labelTable)
+ .set({ name: "After" })
+ .where(eq(schema.labelTable.id, label.id));
+ if (change === "link")
+ await db
+ .update(schema.externalLinkTable)
+ .set({ metadata: JSON.stringify({ merged: true }) })
+ .where(eq(schema.externalLinkTable.id, link.id));
+ if (change === "assignee")
+ await db
+ .update(schema.userTable)
+ .set({ name: "Renamed", image: "https://example.com/avatar.png" })
+ .where(eq(schema.userTable.id, member.user.id));
+ if (change === "project")
+ await db
+ .update(schema.projectTable)
+ .set({ name: "Renamed project" })
+ .where(eq(schema.projectTable.id, project.id));
+ if (change === "subtask")
+ await db
+ .update(schema.taskTable)
+ .set({ status: "done" })
+ .where(eq(schema.taskTable.id, child.id));
+ expect(
+ (await (await app.request(path + "&page=2")).json()).pagination.revision,
+ ).not.toBe(before);
+ },
+);
diff --git a/tests/api-integration/task-related-pages.test.ts b/tests/api-integration/task-related-pages.test.ts
index f88111b76..4ef80445b 100644
--- a/tests/api-integration/task-related-pages.test.ts
+++ b/tests/api-integration/task-related-pages.test.ts
@@ -251,13 +251,13 @@ it.each(
if (collection === "columns")
expect(after.revision).not.toBe(before.revision);
else {
- expect(after.revision).toBe(before.revision);
+ expect(after.revision).not.toBe(before.revision);
expect(after.relatedRevision).not.toBe(before.relatedRevision);
}
},
);
-it("does not restart public related pagination for ordinary text and integration stamps", async () => {
+it("detects text and integration updates between public related pages", async () => {
const { app, project, task } = await fixture();
mockAnonymousSession();
const path = `/api/public-project/${project.id}?limit=100`;
@@ -276,8 +276,6 @@ it("does not restart public related pagination for ordinary text and integration
.where(eq(schema.externalLinkTable.id, "link-000"));
const after = (await (await app.request(path + "&relatedPage=2")).json())
.pagination;
- expect(after).toMatchObject({
- revision: before.revision,
- relatedRevision: before.relatedRevision,
- });
+ expect(after.revision).not.toBe(before.revision);
+ expect(after.relatedRevision).not.toBe(before.relatedRevision);
});