⚡ 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(integrations): protect title updates and converge field labels
Tin5343ee6f4a5e
diff --git a/apps/api/src/plugins/gitea/events/task-priority-changed.ts b/apps/api/src/plugins/gitea/events/task-priority-changed.tsindex 7cd8cdf19..8445b37fc 100644--- a/apps/api/src/plugins/gitea/events/task-priority-changed.ts+++ b/apps/api/src/plugins/gitea/events/task-priority-changed.ts@@ -1,4 +1,4 @@-import { createIssueWrite } from "../../sync/dispatch-issue-write";+import { syncTaskFieldLabels } from "../../sync/sync-task-field-labels";import { canSyncTask } from "../../sync/eligibility";import { findExternalLinksByTask } from "../../github/services/link-manager";import type { PluginContext, TaskPriorityChangedEvent } from "../../types";@@ -35,31 +35,21 @@ export async function handleTaskPriorityChanged(if (!issueLink) {return;}- const write = createIssueWrite(- { ...issueLink, taskId: event.taskId },- JSON.stringify(context.config),- );-const issueNumber = Number.parseInt(issueLink.externalId, 10);- if (event.oldPriority && event.oldPriority !== "no-priority") {- await removeLabelGitea(- config,- issueNumber,- `priority:${event.oldPriority}`,- write,- );- }-- if (event.newPriority && event.newPriority !== "no-priority") {- await addLabelsToIssueGitea(- config,- issueNumber,- [`priority:${event.newPriority}`],- false,- write,- );- }+ await syncTaskFieldLabels(+ event.taskId,+ context,+ issueLink,+ "gitea",+ "priority",+ async ({ add, remove }, write) => {+ for (const name of remove)+ await removeLabelGitea(config, issueNumber, name, write);+ if (add.length)+ await addLabelsToIssueGitea(config, issueNumber, add, true, write);+ },+ );} catch (error) {console.error("Failed to update Gitea issue priority:", error);}diff --git a/apps/api/src/plugins/gitea/events/task-status-changed.ts b/apps/api/src/plugins/gitea/events/task-status-changed.tsindex b1d68b500..9d9f3293e 100644--- a/apps/api/src/plugins/gitea/events/task-status-changed.ts+++ b/apps/api/src/plugins/gitea/events/task-status-changed.ts@@ -1,4 +1,4 @@-import { createIssueWrite } from "../../sync/dispatch-issue-write";+import { syncTaskFieldLabels } from "../../sync/sync-task-field-labels";import { canSyncTask } from "../../sync/eligibility";import { syncLatestTaskValue } from "../../github/services/sync-latest-task-value";import { findExternalLinksByTask } from "../../github/services/link-manager";@@ -39,36 +39,30 @@ export async function handleTaskStatusChanged(if (!issueLink) {return;}- const write = createIssueWrite(- { ...issueLink, taskId: event.taskId },- JSON.stringify(context.config),- );-const client = createGiteaClient(config);const issueNumber = Number.parseInt(issueLink.externalId, 10);- await removeLabelGitea(- config,- issueNumber,- `status:${event.oldStatus}`,- write,- );-- await addLabelsToIssueGitea(- config,- issueNumber,- [`status:${event.newStatus}`],- false,- write,+ const currentValue = await syncTaskFieldLabels(+ event.taskId,+ context,+ issueLink,+ "gitea",+ "status",+ async ({ add, remove }, write) => {+ for (const name of remove)+ await removeLabelGitea(config, issueNumber, name, write);+ if (add.length)+ await addLabelsToIssueGitea(config, issueNumber, add, true, write);+ },);-- if (event.newStatus === "done" || event.oldStatus === "done") {+ if (currentValue === undefined) return;+ if (currentValue === "done" || event.oldStatus === "done") {await syncLatestTaskValue(event.taskId,event.projectId,issueLink,"state",- event.newStatus === "done" ? "closed" : "open",+ currentValue === "done" ? "closed" : "open",async (value) => {const response = await client.updateIssue(repositoryOwner,diff --git a/apps/api/src/plugins/gitea/webhooks/issue-edited.ts b/apps/api/src/plugins/gitea/webhooks/issue-edited.tsindex 766743459..442b07b20 100644--- a/apps/api/src/plugins/gitea/webhooks/issue-edited.ts+++ b/apps/api/src/plugins/gitea/webhooks/issue-edited.ts@@ -208,7 +208,7 @@ export async function handleGiteaIssueEdited(projectId: integration.projectId,taskId: externalLink.taskId,...(typeof updateData.title === "string"- ? { title: updateData.title }+ ? { titleChanged: true }: {}),}),);diff --git a/apps/api/src/plugins/github/events/task-priority-changed.ts b/apps/api/src/plugins/github/events/task-priority-changed.tsindex 00f14b522..807fb5d47 100644--- a/apps/api/src/plugins/github/events/task-priority-changed.ts+++ b/apps/api/src/plugins/github/events/task-priority-changed.ts@@ -1,4 +1,4 @@-import { createIssueWrite } from "../../sync/dispatch-issue-write";+import { syncTaskFieldLabels } from "../../sync/sync-task-field-labels";import { canSyncTask } from "../../sync/eligibility";import type { PluginContext, TaskPriorityChangedEvent } from "../../types";import { type GitHubConfig, hasVerifiedGitHubBinding } from "../config";@@ -43,36 +43,37 @@ export async function handleTaskPriorityChanged(if (!issueLink) {return;}- const write = createIssueWrite(- { ...issueLink, taskId: event.taskId },- JSON.stringify(context.config),- );-const octokit = await getVerifiedInstallationOctokit(config);const issueNumber = Number.parseInt(issueLink.externalId, 10);- if (event.oldPriority && event.oldPriority !== "no-priority") {- await removeLabel(- octokit,- repositoryOwner,- repositoryName,- issueNumber,- `priority:${event.oldPriority}`,- write,- );- }-- if (event.newPriority && event.newPriority !== "no-priority") {- await addLabelsToIssue(- octokit,- repositoryOwner,- repositoryName,- issueNumber,- [`priority:${event.newPriority}`],- false,- write,- );- }+ await syncTaskFieldLabels(+ event.taskId,+ context,+ issueLink,+ "github",+ "priority",+ async ({ add, remove }, write) => {+ for (const name of remove)+ await removeLabel(+ octokit,+ repositoryOwner,+ repositoryName,+ issueNumber,+ name,+ write,+ );+ if (add.length)+ await addLabelsToIssue(+ octokit,+ repositoryOwner,+ repositoryName,+ issueNumber,+ add,+ true,+ write,+ );+ },+ );} catch (error) {console.error("Failed to update GitHub issue priority:", error);}diff --git a/apps/api/src/plugins/github/events/task-status-changed.ts b/apps/api/src/plugins/github/events/task-status-changed.tsindex 5ab678df3..54ffc9f97 100644--- a/apps/api/src/plugins/github/events/task-status-changed.ts+++ b/apps/api/src/plugins/github/events/task-status-changed.ts@@ -1,4 +1,4 @@-import { createIssueWrite } from "../../sync/dispatch-issue-write";+import { syncTaskFieldLabels } from "../../sync/sync-task-field-labels";import { canSyncTask } from "../../sync/eligibility";import { syncLatestTaskValue } from "../services/sync-latest-task-value";import type { PluginContext, TaskStatusChangedEvent } from "../../types";@@ -44,40 +44,45 @@ export async function handleTaskStatusChanged(if (!issueLink) {return;}- const write = createIssueWrite(- { ...issueLink, taskId: event.taskId },- JSON.stringify(context.config),- );-const octokit = await getVerifiedInstallationOctokit(config);const issueNumber = Number.parseInt(issueLink.externalId, 10);- await removeLabel(- octokit,- repositoryOwner,- repositoryName,- issueNumber,- `status:${event.oldStatus}`,- write,- );-- await addLabelsToIssue(- octokit,- repositoryOwner,- repositoryName,- issueNumber,- [`status:${event.newStatus}`],- false,- write,+ const currentValue = await syncTaskFieldLabels(+ event.taskId,+ context,+ issueLink,+ "github",+ "status",+ async ({ add, remove }, write) => {+ for (const name of remove)+ await removeLabel(+ octokit,+ repositoryOwner,+ repositoryName,+ issueNumber,+ name,+ write,+ );+ if (add.length)+ await addLabelsToIssue(+ octokit,+ repositoryOwner,+ repositoryName,+ issueNumber,+ add,+ true,+ write,+ );+ },);-- if (event.newStatus === "done" || event.oldStatus === "done") {+ if (currentValue === undefined) return;+ if (currentValue === "done" || event.oldStatus === "done") {await syncLatestTaskValue(event.taskId,event.projectId,issueLink,"state",- event.newStatus === "done" ? "closed" : "open",+ currentValue === "done" ? "closed" : "open",async (value) => {const response = await octokit.rest.issues.update({owner: repositoryOwner,diff --git a/apps/api/src/plugins/github/services/apply-observed-task-value.ts b/apps/api/src/plugins/github/services/apply-observed-task-value.tsindex 662f5bff9..31732a32e 100644--- a/apps/api/src/plugins/github/services/apply-observed-task-value.ts+++ b/apps/api/src/plugins/github/services/apply-observed-task-value.ts@@ -88,7 +88,7 @@ export async function applyObservedTaskValue(publishEvent("task.updated", {taskId: link.taskId,projectId: integration.projectId,- ...(field === "title" ? { title: value } : {}),+ ...(field === "title" ? { titleChanged: true } : {}),}),);return true;diff --git a/apps/api/src/plugins/github/webhooks/issue-edited.ts b/apps/api/src/plugins/github/webhooks/issue-edited.tsindex eeb15ba5d..8ac3bf5e1 100644--- a/apps/api/src/plugins/github/webhooks/issue-edited.ts+++ b/apps/api/src/plugins/github/webhooks/issue-edited.ts@@ -225,7 +225,7 @@ export async function handleIssueEdited(payload: IssueEditedPayload) {projectId: integration.projectId,taskId: externalLink.taskId,...(typeof updateData.title === "string"- ? { title: updateData.title }+ ? { titleChanged: true }: {}),}),);diff --git a/apps/api/src/plugins/gitlab/events/task-priority-changed.ts b/apps/api/src/plugins/gitlab/events/task-priority-changed.tsindex ddba938e6..dc0ae52a3 100644--- a/apps/api/src/plugins/gitlab/events/task-priority-changed.ts+++ b/apps/api/src/plugins/gitlab/events/task-priority-changed.ts@@ -1,4 +1,4 @@-import { createIssueWrite } from "../../sync/dispatch-issue-write";+import { syncTaskFieldLabels } from "../../sync/sync-task-field-labels";import { canSyncTask } from "../../sync/eligibility";import { findExternalLinksByTask } from "../../github/services/link-manager";import type { PluginContext, TaskPriorityChangedEvent } from "../../types";@@ -35,31 +35,19 @@ export async function handleTaskPriorityChanged(if (!issueLink) {return;}- const write = createIssueWrite(- { ...issueLink, taskId: event.taskId },- JSON.stringify(context.config),- );-const issueIid = Number.parseInt(issueLink.externalId, 10);if (Number.isNaN(issueIid)) {return;}- const remove =- event.oldPriority && event.oldPriority !== "no-priority"- ? [`priority:${event.oldPriority}`]- : [];- const add =- event.newPriority && event.newPriority !== "no-priority"- ? [`priority:${event.newPriority}`]- : [];-- await updateIssueLabelsGitlab(- config,- issueIid,- { add, remove },- false,- write,+ await syncTaskFieldLabels(+ event.taskId,+ context,+ issueLink,+ "gitlab",+ "priority",+ (changes, write) =>+ updateIssueLabelsGitlab(config, issueIid, changes, true, write),);} catch (error) {console.error("Failed to update GitLab issue priority:", error);diff --git a/apps/api/src/plugins/gitlab/events/task-status-changed.ts b/apps/api/src/plugins/gitlab/events/task-status-changed.tsindex 7b7267889..9cc655173 100644--- a/apps/api/src/plugins/gitlab/events/task-status-changed.ts+++ b/apps/api/src/plugins/gitlab/events/task-status-changed.ts@@ -1,4 +1,5 @@import { createIssueWrite } from "../../sync/dispatch-issue-write";+import { syncTaskFieldLabels } from "../../sync/sync-task-field-labels";import { canSyncTask } from "../../sync/eligibility";import {findExternalLinksByTask,@@ -44,11 +45,6 @@ export async function handleTaskStatusChanged(if (!issueLink) {return;}- const write = createIssueWrite(- { ...issueLink, taskId: event.taskId },- JSON.stringify(context.config),- );-const issueIid = Number.parseInt(issueLink.externalId, 10);if (Number.isNaN(issueIid)) {console.warn("Skipping GitLab status sync for invalid issue iid", {@@ -58,19 +54,23 @@ export async function handleTaskStatusChanged(return;}- await updateIssueLabelsGitlab(- config,- issueIid,- {- remove: [`status:${event.oldStatus}`],- add: [`status:${event.newStatus}`],- },- false,- write,+ const currentValue = await syncTaskFieldLabels(+ event.taskId,+ context,+ issueLink,+ "gitlab",+ "status",+ (changes, write) =>+ updateIssueLabelsGitlab(config, issueIid, changes, true, write),+ );+ if (currentValue === undefined) return;+ const write = createIssueWrite(+ { ...issueLink, taskId: event.taskId },+ JSON.stringify(context.config),);- const closing = event.newStatus === "done";- const reopening = event.oldStatus === "done" && event.newStatus !== "done";+ const closing = currentValue === "done";+ const reopening = event.oldStatus === "done" && currentValue !== "done";if (!closing && !reopening) {return;diff --git a/apps/api/src/plugins/gitlab/webhooks/issue-updated.ts b/apps/api/src/plugins/gitlab/webhooks/issue-updated.tsindex a99e466ef..5d23dc1a1 100644--- a/apps/api/src/plugins/gitlab/webhooks/issue-updated.ts+++ b/apps/api/src/plugins/gitlab/webhooks/issue-updated.ts@@ -256,7 +256,7 @@ export async function handleGitlabIssueUpdated(projectId: integration.projectId,taskId: task.id,...(typeof updateData.title === "string"- ? { title: updateData.title }+ ? { titleChanged: true }: {}),}),);diff --git a/apps/api/src/plugins/sync/sync-task-field-labels.ts b/apps/api/src/plugins/sync/sync-task-field-labels.tsnew file mode 100644index 000000000..7d275a4eb--- /dev/null+++ b/apps/api/src/plugins/sync/sync-task-field-labels.ts@@ -0,0 +1,100 @@+import { and, eq } from "drizzle-orm";+import db from "../../database";+import { externalLinkTable } from "../../database/schema";+import { linkedTaskScope } from "../github/services/integration-task-scope";+import { updateExternalLink } from "../github/services/link-manager";+import { parseLinkMetadata } from "../github/utils/parse-link-metadata";+import type { PluginContext } from "../types";+import { createIssueWrite } from "./dispatch-issue-write";+import { canSyncTask } from "./eligibility";+import type { IssueWrite } from "./issue-write";+import { withSyncLease } from "./lease";+import { providerIssue } from "./provider-issue";++export async function syncTaskFieldLabels(+ taskId: string,+ context: PluginContext,+ link: { id: string; externalId: string },+ provider: string,+ field: "priority" | "status",+ send: (+ changes: { add: string[]; remove: string[] },+ write: IssueWrite,+ ) => Promise<void>,+) {+ const config = JSON.stringify(context.config);+ return withSyncLease(`sync-field-labels:${link.id}`, async () => {+ const remote = await providerIssue(+ { type: provider, config },+ { ...link, taskId },+ );+ const write = createIssueWrite(+ { ...link, taskId, integrationId: context.integrationId },+ config,+ );+ for (;;) {+ if (+ !(await canSyncTask(taskId, context.integrationId, undefined, config))+ )+ return;+ const task = await db.query.taskTable.findFirst({+ where: linkedTaskScope(taskId, context.projectId),+ });+ if (!task) return;+ const value = task[field] ?? "no-priority";+ const labels = (await remote.read()).labels;+ const prefix = `${field}:`;+ const add =+ field === "priority" && value === "no-priority"+ ? []+ : [`${prefix}${value}`];+ const remove = labels.filter(+ (name) => name.startsWith(prefix) && !add.includes(name),+ );+ await send({ add, remove }, write);+ if (+ !(await canSyncTask(taskId, context.integrationId, undefined, config))+ )+ return;+ const stored = await db.query.externalLinkTable.findFirst({+ where: and(+ eq(externalLinkTable.id, link.id),+ eq(externalLinkTable.integrationId, context.integrationId),+ ),+ });+ if (!stored) return;+ const metadata = parseLinkMetadata<{+ syncResumeLabelBaseline?: string[];+ }>(stored.metadata, {+ externalLinkId: link.id,+ source: "outbound_field_labels",+ });+ if (Array.isArray(metadata.syncResumeLabelBaseline))+ await updateExternalLink(link.id, {+ metadata: {+ syncResumeLabelBaseline: [+ ...metadata.syncResumeLabelBaseline.filter(+ (name) => typeof name === "string" && !name.startsWith(prefix),+ ),+ ...add,+ ],+ },+ });+ const current = await db.query.taskTable.findFirst({+ where: linkedTaskScope(taskId, context.projectId),+ columns: { priority: true, status: true },+ });+ if (!current) return;+ // A later event may time out waiting for this lease. The current owner+ // repairs edits made during its provider request before releasing it.+ if ((current[field] ?? "no-priority") === value) return value;+ }+ }).catch(() => {+ console.error("Issue field label synchronization failed", {+ integrationId: context.integrationId,+ linkId: link.id,+ field,+ });+ throw new Error("Issue field label synchronization failed");+ });+}diff --git a/apps/api/src/ws/broadcast-adapter.ts b/apps/api/src/ws/broadcast-adapter.tsindex 13b0513d5..58256778c 100644--- a/apps/api/src/ws/broadcast-adapter.ts+++ b/apps/api/src/ws/broadcast-adapter.ts@@ -6,7 +6,7 @@ export type ProjectBroadcastMessage = {sourceTaskId?: string;targetTaskId?: string;linksChanged?: boolean;- taskTitle?: string;+ taskTitleChanged?: boolean;};export type BroadcastMessage = {diff --git a/apps/api/src/ws/index.ts b/apps/api/src/ws/index.tsindex 8b761e9ea..1db77f972 100644--- a/apps/api/src/ws/index.ts+++ b/apps/api/src/ws/index.ts@@ -539,10 +539,7 @@ export function broadcastToProject(message: {...message,...(previous?.message.linksChanged ? { linksChanged: true } : {}),- ...(message.taskTitle === undefined &&- previous?.message.taskTitle !== undefined- ? { taskTitle: previous.message.taskTitle }- : {}),+ ...(previous?.message.taskTitleChanged ? { taskTitleChanged: true } : {}),},excludeInitiatorId,});@@ -582,8 +579,7 @@ export function broadcastToProject(}type TaskEvent = {- title?: string;- newTitle?: string;+ titleChanged?: boolean;skipSubtaskParentRefresh?: boolean;id: string | undefined;projectId: string;@@ -788,12 +784,9 @@ for (const eventName of taskUpdateEvents) {taskId: taskId,sourceTaskId: data.sourceTaskId,targetTaskId: data.targetTaskId,- ...(eventName === "task.title_changed" &&- typeof data.newTitle === "string"- ? { taskTitle: data.newTitle }- : typeof data.title === "string"- ? { taskTitle: data.title }- : {}),+ ...(eventName === "task.title_changed" || data.titleChanged+ ? { taskTitleChanged: true }+ : {}),},initiatorId,);diff --git a/apps/api/src/ws/redis-broadcast-adapter.ts b/apps/api/src/ws/redis-broadcast-adapter.tsindex 958f4ad26..fe3bf7c63 100644--- a/apps/api/src/ws/redis-broadcast-adapter.ts+++ b/apps/api/src/ws/redis-broadcast-adapter.ts@@ -32,7 +32,7 @@ const broadcastMessageSchema = v.object({sourceTaskId: v.optional(v.string()),targetTaskId: v.optional(v.string()),linksChanged: v.optional(v.boolean()),- taskTitle: v.optional(v.string()),+ taskTitleChanged: v.optional(v.boolean()),}),excludeInitiatorId: v.optional(v.string()),authorizationBatch: v.optional(v.string()),diff --git a/apps/web/src/hooks/use-project-websocket-access.test.tsx b/apps/web/src/hooks/use-project-websocket-access.test.tsxindex f3b4c01d7..a82d86879 100644--- a/apps/web/src/hooks/use-project-websocket-access.test.tsx+++ b/apps/web/src/hooks/use-project-websocket-access.test.tsx@@ -16,6 +16,7 @@ const { client, auth, navigate } = vi.hoisted(() => ({getQueryData: vi.fn(),setQueryData: vi.fn(),setQueriesData: vi.fn(),+ getQueriesData: vi.fn().mockReturnValue([]),invalidateQueries: vi.fn(),cancelQueries: vi.fn(),clear: vi.fn(),diff --git a/apps/web/src/hooks/use-project-websocket-cache.test.tsx b/apps/web/src/hooks/use-project-websocket-cache.test.tsxindex 730acdfdb..ee1aa175c 100644--- a/apps/web/src/hooks/use-project-websocket-cache.test.tsx+++ b/apps/web/src/hooks/use-project-websocket-cache.test.tsx@@ -24,6 +24,7 @@ const mocks = vi.hoisted(() => ({getQueryData: vi.fn(),setQueryData: vi.fn(),setQueriesData: vi.fn(),+ getQueriesData: vi.fn().mockReturnValue([]),invalidateQueries: vi.fn(),cancelQueries: vi.fn().mockResolvedValue(undefined),},@@ -80,6 +81,7 @@ beforeEach(() => {});mocks.client.invalidateQueries.mockReset();mocks.client.setQueriesData.mockClear();+ mocks.client.getQueriesData.mockReset().mockReturnValue([]);mocks.client.getQueryState.mockReset();mocks.subscribe.mockClear();});@@ -561,19 +563,67 @@ it("patches affected task names from the normal task refresh without querying sy});});-it("patches affected names from title broadcasts without a loaded board", async () => {+it("reads affected task names through the authorized API without a loaded board", async () => {mocks.board = null;- mocks.getTask.mockClear();+ mocks.getTask+ .mockReset()+ .mockResolvedValue({ id: "a", projectId: "p", title: "Current" });+ mocks.client.getQueriesData.mockReturnValue([+ [[], { matchingTasks: [{ id: "a" }], pausedTasks: [] }],+ ]);renderHook(() => useProjectWebSocket("p"));- Socket.current.message("TASK_UPDATED", { taskId: "a", taskTitle: "Current" });+ Socket.current.message("TASK_UPDATED", {+ taskId: "a",+ taskTitleChanged: true,+ });await vi.waitFor(() =>expect(mocks.client.setQueriesData).toHaveBeenCalledWith({ queryKey: ["integration-sync-preview", "p"] },expect.any(Function),),);- expect(mocks.getTask).not.toHaveBeenCalled();+ expect(mocks.getTask).toHaveBeenCalledOnce();expect(mocks.client.invalidateQueries).not.toHaveBeenCalledWith({queryKey: ["integration-sync-preview", "p"],});});++it.each(["TASK_CREATED", "TASK_DELETED", "TASK_MOVED"])(+ "refreshes sync previews for %s during a board fetch",+ async (type) => {+ mocks.client.getQueryState.mockReturnValue({ fetchStatus: "fetching" });+ renderHook(() => useProjectWebSocket("p"));+ Socket.current.message(type, { taskId: "a" });+ for (const prefix of ["integration-sync", "integration-sync-preview"])+ expect(mocks.client.invalidateQueries).toHaveBeenCalledWith({+ queryKey: [prefix, "p"],+ });+ },+);++it("does not fetch a changed title absent from cached sync samples", () => {+ mocks.board = null;+ mocks.getTask.mockClear();+ renderHook(() => useProjectWebSocket("p"));+ Socket.current.message("TASK_UPDATED", {+ taskId: "a",+ taskTitleChanged: true,+ });+ expect(mocks.getTask).not.toHaveBeenCalled();+});++it("keeps cached names unchanged when the task API denies the title read", async () => {+ mocks.board = null;+ mocks.getTask.mockReset().mockRejectedValue(new Error("Forbidden"));+ mocks.client.getQueriesData.mockReturnValue([+ [[], { matchingTasks: [{ id: "a" }], pausedTasks: [] }],+ ]);+ renderHook(() => useProjectWebSocket("p"));+ Socket.current.message("TASK_UPDATED", {+ taskId: "a",+ taskTitleChanged: true,+ });+ await vi.waitFor(() => expect(mocks.getTask).toHaveBeenCalledOnce());+ await Promise.resolve();+ expect(mocks.client.setQueriesData).not.toHaveBeenCalled();+});diff --git a/apps/web/src/hooks/use-project-websocket-lifecycle.test.tsx b/apps/web/src/hooks/use-project-websocket-lifecycle.test.tsxindex 6c4d7de32..9672ce64f 100644--- a/apps/web/src/hooks/use-project-websocket-lifecycle.test.tsx+++ b/apps/web/src/hooks/use-project-websocket-lifecycle.test.tsx@@ -17,6 +17,7 @@ const { client, auth } = vi.hoisted(() => ({invalidateQueries: vi.fn(),setQueryData: vi.fn(),setQueriesData: vi.fn(),+ getQueriesData: vi.fn().mockReturnValue([]),getQueryData: vi.fn(),},auth: { userId: "user-a" as string | null },diff --git a/apps/web/src/hooks/use-project-websocket.ts b/apps/web/src/hooks/use-project-websocket.tsindex c69647e31..48140eb7e 100644--- a/apps/web/src/hooks/use-project-websocket.ts+++ b/apps/web/src/hooks/use-project-websocket.ts@@ -14,7 +14,10 @@ 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";-import { patchSyncTaskTitles } from "@/lib/patch-sync-task-titles";+import {+ hasSyncTaskSample,+ patchSyncTaskTitles,+} from "@/lib/patch-sync-task-titles";export function getWsUrl(projectId: string) {const base = getApiUrl("ws");@@ -43,6 +46,7 @@ export function useProjectWebSocket(projectId: string) {let needsReconcile = false;let flushQueued = false;const taskVersions = new Map<string, number>();+ const titleVersions = new Map<string, number>();const refreshingTasks = new Set<string>();let burstReconcileTimer: ReturnType<typeof setTimeout> | null = null;function reconcileBurst() {@@ -72,15 +76,7 @@ export function useProjectWebSocket(projectId: string) {targetTaskId?: string;linksChanged?: boolean;}) {- if (- [- "PROJECT_UPDATED",- "TASK_LABEL_UPDATED",- "TASK_CREATED",- "TASK_DELETED",- "TASK_MOVED",- ].includes(message.type)- ) {+ if (["PROJECT_UPDATED", "TASK_LABEL_UPDATED"].includes(message.type)) {queryClient.invalidateQueries({queryKey: ["integration-sync", projectId],});@@ -190,13 +186,44 @@ export function useProjectWebSocket(projectId: string) {if (disposed || activeSocket !== ws) return;try {const message = JSON.parse(event.data);- if (message.taskId && typeof message.taskTitle === "string")- patchSyncTaskTitles(- queryClient,- projectId,- message.taskId,- message.taskTitle,- );+ if (+ message.taskId &&+ message.taskTitleChanged &&+ hasSyncTaskSample(queryClient, projectId, message.taskId)+ ) {+ const taskId = message.taskId as string;+ const version = (titleVersions.get(taskId) ?? 0) + 1;+ titleVersions.set(taskId, version);+ // Read titles through the task API, which enforces task-read permission.+ void getTask(taskId, "board")+ .then((task) => {+ if (+ !disposed &&+ activeSocket === ws &&+ titleVersions.get(taskId) === version &&+ task.projectId === projectId+ )+ patchSyncTaskTitles(+ queryClient,+ projectId,+ taskId,+ task.title,+ );+ })+ .catch(() => {});+ }+ if (+ ["TASK_CREATED", "TASK_DELETED", "TASK_MOVED"].includes(+ message.type,+ )+ ) {+ queryClient.invalidateQueries({+ queryKey: ["integration-sync", projectId],+ });+ queryClient.invalidateQueries({+ queryKey: ["integration-sync-preview", projectId],+ });+ }if (message.type === "PROJECT_MOVED") {markBoardCacheChanged(queryClient, projectId);for (const queryKey of [diff --git a/apps/web/src/lib/patch-sync-task-titles.ts b/apps/web/src/lib/patch-sync-task-titles.tsindex 86ee1fee2..bd3d12424 100644--- a/apps/web/src/lib/patch-sync-task-titles.ts+++ b/apps/web/src/lib/patch-sync-task-titles.ts@@ -28,3 +28,21 @@ export function patchSyncTaskTitles(},);}++export function hasSyncTaskSample(+ client: QueryClient,+ projectId: string,+ taskId: string,+) {+ return ["integration-sync", "integration-sync-preview"].some((prefix) =>+ client+ .getQueriesData<SyncPreview>({ queryKey: [prefix, projectId] })+ .some(+ ([, data]) =>+ data &&+ [...data.matchingTasks, ...data.pausedTasks].some(+ (task) => task.id === taskId,+ ),+ ),+ );+}diff --git a/tests/api-integration/integration-sync-field-labels.test.ts b/tests/api-integration/integration-sync-field-labels.test.tsnew file mode 100644index 000000000..43cc8c3a3--- /dev/null+++ b/tests/api-integration/integration-sync-field-labels.test.ts@@ -0,0 +1,238 @@+import { eq } from "drizzle-orm";+import { beforeEach, expect, it, vi } from "vite-plus/test";+import db, { schema } from "../../apps/api/src/database";+import { githubPlugin } from "../../apps/api/src/plugins/github";+import { giteaPlugin } from "../../apps/api/src/plugins/gitea";+import { gitlabPlugin } from "../../apps/api/src/plugins/gitlab";+import { resetTestDatabase } from "./helpers/database";+import {+ createProjectFixture,+ createWorkspaceMember,+} from "./helpers/fixtures";++const mocks = vi.hoisted(() => ({ labels: new Set<string>(), write: vi.fn() }));+const names = [+ "status:planned",+ "status:in-progress",+ "status:in-review",+ "priority:low",+ "priority:high",+ "priority:urgent",+ "keep",+];+const available = () => names.map((name, id) => ({ name, id: id + 1 }));+const issue = () => ({+ title: "Task",+ body: "",+ state: "open",+ labels: [...mocks.labels],+ updated_at: "2026-10-04T00:00:00Z",+});+vi.mock("../../apps/api/src/plugins/github/utils/github-app", () => ({+ getGithubApp: () => ({}),+ getVerifiedInstallationOctokit: async () => ({+ rest: {+ issues: {+ get: async () => ({ data: issue() }),+ getLabel: async () => ({}),+ removeLabel: async ({ name }: { name: string }) => {+ mocks.labels.delete(name);+ },+ addLabels: async ({ labels }: { labels: string[] }) => {+ await mocks.write();+ for (const name of labels) mocks.labels.add(name);+ },+ },+ },+ }),+}));+vi.mock("../../apps/api/src/plugins/gitea/utils/gitea-api", () => ({+ createGiteaClient: () => ({+ getIssue: async () => issue(),+ listLabels: async () => available(),+ removeLabelFromIssue: async (+ _owner: string,+ _repo: string,+ _number: number,+ id: number,+ ) => {+ mocks.labels.delete(names[id - 1]);+ },+ addLabelsToIssue: async (+ _owner: string,+ _repo: string,+ _number: number,+ ids: number[],+ ) => {+ await mocks.write();+ for (const id of ids) mocks.labels.add(names[id - 1]);+ },+ }),+}));+vi.mock("../../apps/api/src/plugins/gitlab/utils/gitlab-api", () => ({+ createGitlabClient: () => ({+ getIssue: async () => issue(),+ listLabels: async () => available(),+ updateIssue: async (+ _project: string,+ _number: number,+ body: { add_labels?: string; remove_labels?: string },+ ) => {+ await mocks.write();+ for (const name of body.remove_labels?.split(",") ?? [])+ mocks.labels.delete(name);+ for (const name of body.add_labels?.split(",") ?? [])+ mocks.labels.add(name);+ return issue();+ },+ }),+}));+beforeEach(async () => {+ await resetTestDatabase();+ mocks.write.mockReset().mockResolvedValue(undefined);+ mocks.labels = new Set(["status:planned", "priority:low", "keep"]);+});++it.each(+ (["github", "gitea", "gitlab"] as const).flatMap((provider) =>+ (["status", "priority"] as const).flatMap((field) =>+ (field === "priority" ? [false, true, "clear"] : [false, true]).map(+ (overlap) => ({ provider, field, overlap }),+ ),+ ),+ ),+)(+ "$provider replaces actual $field labels after resume (overlap=$overlap)",+ async ({ provider, field, overlap }) => {+ const { workspace, user } = await createWorkspaceMember();+ const { project } = await createProjectFixture({+ workspaceId: workspace.id,+ });+ const clearing = overlap === "clear";+ const overlapping = overlap === true;+ const first =+ field === "status" ? "in-progress" : clearing ? "no-priority" : "high";+ const last = field === "status" ? "in-review" : "urgent";+ const [task] = await db+ .insert(schema.taskTable)+ .values({+ projectId: project.id,+ number: 1,+ title: "Task",+ status: "in-progress",+ priority: field === "priority" ? first : "high",+ })+ .returning();+ const config = {+ baseUrl: "https://git.example",+ accessToken: "fake-test-token",+ repositoryOwner: "team",+ repositoryName: "repo",+ projectPath: "team/repo",+ installationId: 1,+ repositoryId: 2,+ verifiedGithubAccountId: "3",+ verifiedByUserId: user.id,+ };+ const [integration] = await db+ .insert(schema.integrationTable)+ .values({+ projectId: project.id,+ type: provider,+ isActive: true,+ config: JSON.stringify(config),+ })+ .returning();+ const [link] = await db+ .insert(schema.externalLinkTable)+ .values({+ taskId: task.id,+ integrationId: integration.id,+ resourceType: "issue",+ externalId: "1",+ url: "https://git.example/team/repo/issues/1",+ metadata: JSON.stringify({+ syncResumeLabelBaseline: [...mocks.labels],+ }),+ })+ .returning();+ const plugin =+ provider === "github"+ ? githubPlugin+ : provider === "gitea"+ ? giteaPlugin+ : gitlabPlugin;+ const context = {+ integrationId: integration.id,+ projectId: project.id,+ config,+ };+ const sync = (oldValue: string, value: string) =>+ field === "status"+ ? plugin.onTaskStatusChanged!(+ {+ taskId: task.id,+ projectId: project.id,+ userId: user.id,+ title: task.title,+ oldStatus: oldValue,+ newStatus: value,+ },+ context,+ )+ : plugin.onTaskPriorityChanged!(+ {+ taskId: task.id,+ projectId: project.id,+ userId: user.id,+ title: task.title,+ oldPriority: oldValue,+ newPriority: value,+ },+ context,+ );+ let release!: () => void;+ let started!: () => void;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ const writing = new Promise<void>((resolve) => {+ started = resolve;+ });+ if (overlapping)+ mocks.write.mockImplementationOnce(async () => {+ started();+ await gate;+ });+ const initial = sync(field === "status" ? "to-do" : "urgent", first);+ if (overlapping) {+ await writing;+ // A slow provider request must not hold task or project row locks.+ await db+ .update(schema.taskTable)+ .set({ [field]: last })+ .where(eq(schema.taskTable.id, task.id));+ const later = sync(first, last);+ release();+ await Promise.all([initial, later]);+ } else await initial;+ const expected = `${field}:${overlapping ? last : first}`;+ expect(+ [...mocks.labels].filter((name) => name.startsWith(`${field}:`)),+ ).toEqual(clearing ? [] : [expected]);+ expect(mocks.labels.has("keep")).toBe(true);+ expect(+ mocks.labels.has(field === "status" ? "priority:low" : "status:planned"),+ ).toBe(true);+ const saved = await db.query.externalLinkTable.findFirst({+ where: eq(schema.externalLinkTable.id, link.id),+ });+ if (!clearing)+ expect(JSON.parse(saved!.metadata!).syncResumeLabelBaseline).toContain(+ expected,+ );+ expect(JSON.parse(saved!.metadata!).syncResumeLabelBaseline).not.toContain(+ `${field}:${field === "status" ? "planned" : "low"}`,+ );+ },+);diff --git a/tests/api-integration/provider-board-live-updates.test.ts b/tests/api-integration/provider-board-live-updates.test.tsindex 20189dc8e..07e463bec 100644--- a/tests/api-integration/provider-board-live-updates.test.ts+++ b/tests/api-integration/provider-board-live-updates.test.ts@@ -218,7 +218,11 @@ it.each([kind === "text" || (kind === "priority" && provider !== "gitlab")? "task.updated": "task.labels_updated",- { projectId: project.id, taskId: task.id },+ {+ projectId: project.id,+ taskId: task.id,+ ...(kind === "text" ? { titleChanged: true } : {}),+ },],]);},diff --git a/tests/api/plugins/github/rapid-state-sync.test.ts b/tests/api/plugins/github/rapid-state-sync.test.tsindex bd4834d71..f6f3e4517 100644--- a/tests/api/plugins/github/rapid-state-sync.test.ts+++ b/tests/api/plugins/github/rapid-state-sync.test.ts@@ -147,3 +147,7 @@ vi.mock("../../../../apps/api/src/plugins/sync/dispatch-issue-write", () => ({send: () => Promise<unknown>,) => ({ value: await send() }),}));++vi.mock("../../../../apps/api/src/plugins/sync/sync-task-field-labels", () => ({+ syncTaskFieldLabels: async () => m.status,+}));diff --git a/tests/api/plugins/gitlab/events/task-status-changed.test.ts b/tests/api/plugins/gitlab/events/task-status-changed.test.tsindex 81ca85cf5..018fb1e53 100644--- a/tests/api/plugins/gitlab/events/task-status-changed.test.ts+++ b/tests/api/plugins/gitlab/events/task-status-changed.test.ts@@ -145,3 +145,23 @@ vi.mock() => ({ value: await send() }),}),);++vi.mock(+ "../../../../../apps/api/src/plugins/sync/sync-task-field-labels",+ () => ({+ syncTaskFieldLabels: async (+ _taskId: string,+ _context: unknown,+ _link: unknown,+ _provider: string,+ _field: string,+ send: (changes: unknown, write: unknown) => Promise<void>,+ ) => {+ await send(+ { add: ["status:done"], remove: ["status:in-review"] },+ (run: () => Promise<unknown>) => run(),+ );+ return "done";+ },+ }),+);diff --git a/tests/api/ws/broadcast.test.ts b/tests/api/ws/broadcast.test.tsindex 8e954ec7a..505edc706 100644--- a/tests/api/ws/broadcast.test.ts+++ b/tests/api/ws/broadcast.test.ts@@ -206,7 +206,7 @@ describe("broadcastToProject", () => {removeConnection("proj-1", conn);});- it("preserves the latest task title through later unrelated updates in the batch", async () => {+ it("keeps title-change hints through batching without broadcasting private titles", async () => {const ws = makeFakeWs();const conn = addConnection("proj-1", ws, "user-1", "init-1", "workspace");await taskTitleHandler({@@ -229,8 +229,10 @@ describe("broadcastToProject", () => {timeout: 300,});expect(JSON.parse(send.mock.calls[0][0])).toMatchObject({- taskTitle: "Current",+ taskTitleChanged: true,});+ expect(send.mock.calls[0][0]).not.toContain("Current");+ expect(send.mock.calls[0][0]).not.toContain("First");removeConnection("proj-1", conn);});diff --git a/tests/api/ws/redis-link-refresh.test.ts b/tests/api/ws/redis-link-refresh.test.tsindex 247b52930..f551babf1 100644--- a/tests/api/ws/redis-link-refresh.test.ts+++ b/tests/api/ws/redis-link-refresh.test.ts@@ -29,7 +29,7 @@ it("retains the link-refresh flag when receiving a Redis project broadcast", asytype: "PROJECT_UPDATED",projectId: "project",linksChanged: true,- taskTitle: "Current",+ taskTitleChanged: true,},}),);@@ -37,7 +37,7 @@ it("retains the link-refresh flag when receiving a Redis project broadcast", asyexpect.objectContaining({message: expect.objectContaining({linksChanged: true,- taskTitle: "Current",+ taskTitleChanged: true,}),}),);