⚡ 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): replay creation edits and keep sync previews current
Tin03f9147c624b
diff --git a/apps/api/src/gitea-integration/index.ts b/apps/api/src/gitea-integration/index.tsindex 0f55f08f3..cace23655 100644--- a/apps/api/src/gitea-integration/index.ts+++ b/apps/api/src/gitea-integration/index.ts@@ -336,7 +336,7 @@ const giteaIntegration = apiRouter<BaseVariables & { workspaceId: string }>()projectId,integrationId: row.id,});- await publishEvent("project.updated", { projectId });+ await publishEvent("project.updated", { projectId, linksChanged: true });return c.json(updated, 200);}).openapi(deleteIntegrationRoute, async (c) => {diff --git a/apps/api/src/github-integration/controllers/import-issues.ts b/apps/api/src/github-integration/controllers/import-issues.tsindex 88b242bd4..53b017460 100644--- a/apps/api/src/github-integration/controllers/import-issues.ts+++ b/apps/api/src/github-integration/controllers/import-issues.ts@@ -361,6 +361,7 @@ async function applyPage(};await importIssueLabels(task.id, project.workspaceId, scopeLabels, tx);await importLabels(tx, issue.labels.nodes, task.id, project.workspaceId);+ await canSyncTask(task.id, integrationId, tx);await importComments(tx, issue.comments.nodes, task.id, state.startedAt);announce(task.id, "task.updated", "task.labels_updated", "comment.updated");nextIssuePart(state);diff --git a/apps/api/src/github-integration/index.ts b/apps/api/src/github-integration/index.tsindex 5e8a111e7..182b4f759 100644--- a/apps/api/src/github-integration/index.ts+++ b/apps/api/src/github-integration/index.ts@@ -384,7 +384,7 @@ const githubIntegration = apiRouter<BaseVariables & { workspaceId: string }>()projectId,integrationId: row.id,});- await publishEvent("project.updated", { projectId });+ await publishEvent("project.updated", { projectId, linksChanged: true });return c.json(updated, 200);}).openapi(deleteIntegrationRoute, async (c) => {diff --git a/apps/api/src/gitlab-integration/index.ts b/apps/api/src/gitlab-integration/index.tsindex 950d2eabb..1b0e80b75 100644--- a/apps/api/src/gitlab-integration/index.ts+++ b/apps/api/src/gitlab-integration/index.ts@@ -343,7 +343,7 @@ const gitlabIntegration = apiRouter<BaseVariables & { workspaceId: string }>()projectId,integrationId: row.id,});- await publishEvent("project.updated", { projectId });+ await publishEvent("project.updated", { projectId, linksChanged: true });return c.json(updated, 200);}).openapi(deleteIntegrationRoute, async (c) => {diff --git a/apps/api/src/integration-sync/controllers/save-rules.ts b/apps/api/src/integration-sync/controllers/save-rules.tsindex d3677f0cb..a40de8a0c 100644--- a/apps/api/src/integration-sync/controllers/save-rules.ts+++ b/apps/api/src/integration-sync/controllers/save-rules.ts@@ -73,6 +73,6 @@ export async function saveSyncRules(projectId,integrationId: integration.id,});- await publishEvent("project.updated", { projectId });+ await publishEvent("project.updated", { projectId, linksChanged: true });return previewSyncRules(await getSyncIntegration(projectId, provider), rules);}diff --git a/apps/api/src/plugins/gitea/events/task-created.ts b/apps/api/src/plugins/gitea/events/task-created.tsindex 01b0654d1..e65c39b36 100644--- a/apps/api/src/plugins/gitea/events/task-created.ts+++ b/apps/api/src/plugins/gitea/events/task-created.ts@@ -70,6 +70,10 @@ async function createTaskIssue(state: createdIssue.state,createdFrom: "kaneo",syncInitializationPending: true,+ syncCreatedText: {+ title: event.title,+ description: event.description ?? "",+ },lastOutboundStateSyncAt: Date.now(),},});@@ -92,6 +96,17 @@ async function createTaskIssue(}await initializeTaskIssue(event, context, createdLink, {+ text: async (field, value) =>+ (+ await client.updateIssue(+ repositoryOwner,+ repositoryName,+ issueNumber,+ field === "title"+ ? { title: formatIssueTitle(value) }+ : { body: formatIssueBody(value, event.taskId) },+ )+ )?.updated_at,close: () =>client.updateIssue(repositoryOwner, repositoryName, issueNumber, {state: "closed",diff --git a/apps/api/src/plugins/gitea/webhooks/issue-edited.ts b/apps/api/src/plugins/gitea/webhooks/issue-edited.tsindex 730e22500..766743459 100644--- a/apps/api/src/plugins/gitea/webhooks/issue-edited.ts+++ b/apps/api/src/plugins/gitea/webhooks/issue-edited.ts@@ -207,6 +207,9 @@ export async function handleGiteaIssueEdited(publishEvent("task.updated", {projectId: integration.projectId,taskId: externalLink.taskId,+ ...(typeof updateData.title === "string"+ ? { title: updateData.title }+ : {}),}),);}diff --git a/apps/api/src/plugins/gitea/webhooks/issue-opened.ts b/apps/api/src/plugins/gitea/webhooks/issue-opened.tsindex 132b13e93..a69839d66 100644--- a/apps/api/src/plugins/gitea/webhooks/issue-opened.ts+++ b/apps/api/src/plugins/gitea/webhooks/issue-opened.ts@@ -1,5 +1,6 @@import { acceptsIssue } from "../../sync/rules";import { importIssueLabels } from "../../sync/issue-labels";+import { canSyncTask } from "../../sync/eligibility";import { and, eq } from "drizzle-orm";import db from "../../../database";import {@@ -168,6 +169,7 @@ export async function handleGiteaIssueOpened(issue.labels,tx,);+ await canSyncTask(task.id, integration.id, tx, integration.config);return { task, link, linkMetadata };});if (!result) continue;diff --git a/apps/api/src/plugins/github/events/task-created.ts b/apps/api/src/plugins/github/events/task-created.tsindex ccff5f4e9..cdd06c7d9 100644--- a/apps/api/src/plugins/github/events/task-created.ts+++ b/apps/api/src/plugins/github/events/task-created.ts@@ -77,6 +77,10 @@ async function createTaskIssue(state: createdIssue.data.state,createdFrom: "kaneo",syncInitializationPending: true,+ syncCreatedText: {+ title: event.title,+ description: event.description ?? "",+ },},});issueNumber = createdIssue.data.number;@@ -110,6 +114,17 @@ async function createTaskIssue(}}await initializeTaskIssue(event, context, createdLink, {+ text: async (field, value) =>+ (+ await octokit.rest.issues.update({+ owner: repositoryOwner,+ repo: repositoryName,+ issue_number: issueNumber,+ ...(field === "title"+ ? { title: formatIssueTitle(value) }+ : { body: formatIssueBody(value, event.taskId) }),+ })+ )?.data?.updated_at,close: () =>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 373578d5c..662f5bff9 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,6 +88,7 @@ export async function applyObservedTaskValue(publishEvent("task.updated", {taskId: link.taskId,projectId: integration.projectId,+ ...(field === "title" ? { title: value } : {}),}),);return true;diff --git a/apps/api/src/plugins/github/webhooks/issue-edited.ts b/apps/api/src/plugins/github/webhooks/issue-edited.tsindex 610b69050..eeb15ba5d 100644--- a/apps/api/src/plugins/github/webhooks/issue-edited.ts+++ b/apps/api/src/plugins/github/webhooks/issue-edited.ts@@ -224,6 +224,9 @@ export async function handleIssueEdited(payload: IssueEditedPayload) {publishEvent("task.updated", {projectId: integration.projectId,taskId: externalLink.taskId,+ ...(typeof updateData.title === "string"+ ? { title: updateData.title }+ : {}),}),);diff --git a/apps/api/src/plugins/github/webhooks/issue-opened.ts b/apps/api/src/plugins/github/webhooks/issue-opened.tsindex 81fd1bc92..1719ff790 100644--- a/apps/api/src/plugins/github/webhooks/issue-opened.ts+++ b/apps/api/src/plugins/github/webhooks/issue-opened.ts@@ -1,5 +1,6 @@import { acceptsIssue } from "../../sync/rules";import { importIssueLabels } from "../../sync/issue-labels";+import { canSyncTask } from "../../sync/eligibility";import { and, eq } from "drizzle-orm";import db from "../../../database";import { publishEvent } from "../../../events";@@ -152,6 +153,7 @@ export async function handleIssueOpened(issue.labels,tx,);+ await canSyncTask(task.id, integration.id, tx, integration.config);return task;});if (!createdTask) continue;diff --git a/apps/api/src/plugins/gitlab/events/task-created.ts b/apps/api/src/plugins/gitlab/events/task-created.tsindex 6a4c9352e..e9f885ac2 100644--- a/apps/api/src/plugins/gitlab/events/task-created.ts+++ b/apps/api/src/plugins/gitlab/events/task-created.ts@@ -64,6 +64,10 @@ async function createTaskIssue(state: createdIssue.state,createdFrom: "kaneo",syncInitializationPending: true,+ syncCreatedText: {+ title: event.title,+ description: event.description ?? "",+ },lastOutboundStateSyncAt: Date.now(),},});@@ -86,6 +90,16 @@ async function createTaskIssue(}await initializeTaskIssue(event, context, createdLink, {+ text: async (field, value) =>+ (+ await client.updateIssue(+ config.projectPath,+ issueNumber,+ field === "title"+ ? { title: formatIssueTitle(value) }+ : { description: formatIssueBody(value, event.taskId) },+ )+ )?.updated_at,close: () =>client.updateIssue(config.projectPath, issueNumber, {state_event: "close",diff --git a/apps/api/src/plugins/gitlab/webhooks/issue-opened.ts b/apps/api/src/plugins/gitlab/webhooks/issue-opened.tsindex a07ae36d3..a7dba399c 100644--- a/apps/api/src/plugins/gitlab/webhooks/issue-opened.ts+++ b/apps/api/src/plugins/gitlab/webhooks/issue-opened.ts@@ -1,5 +1,6 @@import { acceptsIssue } from "../../sync/rules";import { importIssueLabels } from "../../sync/issue-labels";+import { canSyncTask } from "../../sync/eligibility";import { and, eq } from "drizzle-orm";import db from "../../../database";import {@@ -174,6 +175,7 @@ export async function handleGitlabIssueOpened(payload.labels,tx,);+ await canSyncTask(task.id, integration.id, tx, integration.config);return { task, link, linkMetadata };});if (!result) continue;diff --git a/apps/api/src/plugins/gitlab/webhooks/issue-updated.ts b/apps/api/src/plugins/gitlab/webhooks/issue-updated.tsindex b95b95c6a..a99e466ef 100644--- a/apps/api/src/plugins/gitlab/webhooks/issue-updated.ts+++ b/apps/api/src/plugins/gitlab/webhooks/issue-updated.ts@@ -255,6 +255,9 @@ export async function handleGitlabIssueUpdated(publishEvent("task.updated", {projectId: integration.projectId,taskId: task.id,+ ...(typeof updateData.title === "string"+ ? { title: updateData.title }+ : {}),}),);}diff --git a/apps/api/src/plugins/sync/initialize-task-issue.ts b/apps/api/src/plugins/sync/initialize-task-issue.tsindex fd8ae281f..daaf1c23a 100644--- a/apps/api/src/plugins/sync/initialize-task-issue.ts+++ b/apps/api/src/plugins/sync/initialize-task-issue.ts@@ -5,6 +5,7 @@ import type { PluginContext, TaskCreatedEvent } from "../types";import { createIssueWrite } from "./dispatch-issue-write";import type { IssueWrite } from "./issue-write";import { taskIssueLabels } from "./issue-labels";+import { initializeTaskText } from "./initialize-task-text";type Initialization = {syncInitializationPending?: boolean;@@ -28,11 +29,16 @@ export async function initializeTaskIssue(context: PluginContext,link: Link,actions: {+ text: (+ field: "title" | "description",+ value: string,+ ) => Promise<string | undefined>;close: () => Promise<unknown>;labels: (names: string[], write: IssueWrite) => Promise<void>;comment?: () => Promise<unknown>;},) {+ const current = await initializeTaskText(event, context, link, actions.text);const progress = parseLinkMetadata<Initialization>(link.metadata, {externalLinkId: link.id,source: "sync_creation",@@ -45,7 +51,7 @@ export async function initializeTaskIssue(if (await isTaskInFinalState({projectId: event.projectId,- status: event.status,+ status: current.status,columnId: null,})) {@@ -60,7 +66,7 @@ export async function initializeTaskIssue(}if (!progress.syncInitializedLabels) {await actions.labels(- await taskIssueLabels(event.taskId, event.priority, event.status),+ await taskIssueLabels(event.taskId, current.priority, current.status),write,);await updateExternalLink(link.id, {diff --git a/apps/api/src/plugins/sync/initialize-task-text.ts b/apps/api/src/plugins/sync/initialize-task-text.tsnew file mode 100644index 000000000..4b88c3c52--- /dev/null+++ b/apps/api/src/plugins/sync/initialize-task-text.ts@@ -0,0 +1,81 @@+import db from "../../database";+import { and, eq } from "drizzle-orm";+import { externalLinkTable } from "../../database/schema";+import { linkedTaskScope } from "../github/services/integration-task-scope";+import { updateExternalLink } from "../github/services/link-manager";+import { syncLatestTaskValue } from "../github/services/sync-latest-task-value";+import { parseLinkMetadata } from "../github/utils/parse-link-metadata";+import type { PluginContext, TaskCreatedEvent } from "../types";+import { canSyncTask } from "./eligibility";++export async function initializeTaskText(+ event: TaskCreatedEvent,+ context: PluginContext,+ link: { id: string; metadata?: string | null },+ send: (+ field: "title" | "description",+ value: string,+ ) => Promise<string | undefined>,+) {+ const task = await db.query.taskTable.findFirst({+ where: linkedTaskScope(event.taskId, context.projectId),+ });+ if (!task) throw new Error("Task sync scope changed");+ const stored = await db.query.externalLinkTable.findFirst({+ where: and(+ eq(externalLinkTable.id, link.id),+ eq(externalLinkTable.taskId, event.taskId),+ eq(externalLinkTable.integrationId, context.integrationId),+ ),+ columns: { metadata: true },+ });+ if (!stored) throw new Error("Issue sync scope changed");+ const progress = parseLinkMetadata<{+ syncInitializedText?: { title: string; description: string };+ syncCreatedText?: { title: string; description: string };+ }>(stored.metadata, {+ externalLinkId: link.id,+ source: "sync_initialization",+ });+ const previous = progress.syncInitializedText ?? progress.syncCreatedText;+ const values = { title: task.title, description: task.description ?? "" };+ for (const field of ["title", "description"] as const) {+ if (previous?.[field] === values[field]) continue;+ await syncLatestTaskValue(+ task.id,+ context.projectId,+ { id: link.id, integrationId: context.integrationId },+ field,+ values[field],+ (value) => send(field, value),+ undefined,+ { config: JSON.stringify(context.config) },+ );+ }+ if (+ !(await canSyncTask(+ event.taskId,+ context.integrationId,+ undefined,+ JSON.stringify(context.config),+ ))+ )+ throw new Error("Issue sync scope changed");+ await updateExternalLink(link.id, {+ metadata: { syncInitializedText: values },+ });+ const current = await db.query.taskTable.findFirst({+ where: linkedTaskScope(event.taskId, context.projectId),+ });+ if (!current || current.number === null)+ throw new Error("Task sync scope changed");+ return {+ ...event,+ title: current.title,+ description: current.description,+ priority: current.priority,+ status: current.status,+ userId: current.userId ?? "",+ number: current.number,+ };+}diff --git a/apps/api/src/ws/broadcast-adapter.ts b/apps/api/src/ws/broadcast-adapter.tsindex c393a53bd..13b0513d5 100644--- a/apps/api/src/ws/broadcast-adapter.ts+++ b/apps/api/src/ws/broadcast-adapter.ts@@ -5,6 +5,8 @@ export type ProjectBroadcastMessage = {tasks?: Array<{ id: string; position: number; status?: string }>;sourceTaskId?: string;targetTaskId?: string;+ linksChanged?: boolean;+ taskTitle?: string;};export type BroadcastMessage = {diff --git a/apps/api/src/ws/index.ts b/apps/api/src/ws/index.tsindex 077eac7e1..8b761e9ea 100644--- a/apps/api/src/ws/index.ts+++ b/apps/api/src/ws/index.ts@@ -534,9 +534,18 @@ export function broadcastToProject(}const messageKey = `${message.type === "TASKS_REORDERED" ? `${message.type}:${crypto.randomUUID()}` : message.type}:${message.taskId ?? ""}:${message.sourceTaskId ?? ""}:${message.targetTaskId ?? ""}`;- projectBroadcastQueues- .get(projectId)- ?.set(messageKey, { message, excludeInitiatorId });+ const previous = projectBroadcastQueues.get(projectId)?.get(messageKey);+ projectBroadcastQueues.get(projectId)?.set(messageKey, {+ message: {+ ...message,+ ...(previous?.message.linksChanged ? { linksChanged: true } : {}),+ ...(message.taskTitle === undefined &&+ previous?.message.taskTitle !== undefined+ ? { taskTitle: previous.message.taskTitle }+ : {}),+ },+ excludeInitiatorId,+ });if (projectBroadcastTimeouts.has(projectId)) {return;@@ -573,6 +582,8 @@ export function broadcastToProject(}type TaskEvent = {+ title?: string;+ newTitle?: string;skipSubtaskParentRefresh?: boolean;id: string | undefined;projectId: string;@@ -708,13 +719,18 @@ subscribeToEvent<{ notificationId: string; userId: string }>(subscribeToEvent<{projectId: string;initiatorId?: string;+ linksChanged?: boolean;}>("project.updated", async (data) => {const { projectId, initiatorId } = data;if (!projectId) return;broadcastToProject(projectId,- { type: "PROJECT_UPDATED", projectId },+ {+ type: "PROJECT_UPDATED",+ projectId,+ ...(data.linksChanged ? { linksChanged: true } : {}),+ },initiatorId,);});@@ -772,6 +788,12 @@ 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 }+ : {}),},initiatorId,);diff --git a/apps/api/src/ws/redis-broadcast-adapter.ts b/apps/api/src/ws/redis-broadcast-adapter.tsindex 0b93d7343..958f4ad26 100644--- a/apps/api/src/ws/redis-broadcast-adapter.ts+++ b/apps/api/src/ws/redis-broadcast-adapter.ts@@ -31,6 +31,8 @@ const broadcastMessageSchema = v.object({),sourceTaskId: v.optional(v.string()),targetTaskId: v.optional(v.string()),+ linksChanged: v.optional(v.boolean()),+ taskTitle: v.optional(v.string()),}),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 efcb43630..f3b4c01d7 100644--- a/apps/web/src/hooks/use-project-websocket-access.test.tsx+++ b/apps/web/src/hooks/use-project-websocket-access.test.tsx@@ -15,6 +15,7 @@ const { client, auth, navigate } = vi.hoisted(() => ({getQueryState: vi.fn(),getQueryData: vi.fn(),setQueryData: vi.fn(),+ setQueriesData: vi.fn(),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 f5bc5cce8..730acdfdb 100644--- a/apps/web/src/hooks/use-project-websocket-cache.test.tsx+++ b/apps/web/src/hooks/use-project-websocket-cache.test.tsx@@ -23,6 +23,7 @@ const mocks = vi.hoisted(() => ({getQueryState: vi.fn(),getQueryData: vi.fn(),setQueryData: vi.fn(),+ setQueriesData: vi.fn(),invalidateQueries: vi.fn(),cancelQueries: vi.fn().mockResolvedValue(undefined),},@@ -78,6 +79,7 @@ beforeEach(() => {mocks.board = typeof value === "function" ? value(mocks.board) : value;});mocks.client.invalidateQueries.mockReset();+ mocks.client.setQueriesData.mockClear();mocks.client.getQueryState.mockReset();mocks.subscribe.mockClear();});@@ -481,12 +483,22 @@ it("refreshes workspace label filters when a remote project event changes labelsexpect(mocks.client.invalidateQueries).toHaveBeenCalledWith({queryKey: ["labels"],});- expect(mocks.client.invalidateQueries).toHaveBeenCalledWith({+ expect(mocks.client.invalidateQueries).not.toHaveBeenCalledWith({queryKey: ["external-links"],});});});+it("refreshes task link details when a project event explicitly changes links", async () => {+ renderHook(() => useProjectWebSocket("p"));+ Socket.current.message("PROJECT_UPDATED", { linksChanged: true });+ await vi.waitFor(() =>+ expect(mocks.client.invalidateQueries).toHaveBeenCalledWith({+ queryKey: ["external-links"],+ }),+ );+});+it.each(["PROJECT_UPDATED","TASK_LABEL_UPDATED",@@ -522,3 +534,46 @@ it("keeps sync comparisons and scope queries stable during unrelated task edits"queryKey: [key, "p"],});});++it("patches affected task names from the normal task refresh without querying sync scope", async () => {+ mocks.getTask.mockResolvedValue({+ id: "a",+ projectId: "p",+ title: "Renamed",+ status: "todo",+ position: 0,+ });+ renderHook(() => useProjectWebSocket("p"));+ Socket.current.message("TASK_UPDATED", { taskId: "a" });+ await vi.waitFor(() =>+ expect(mocks.client.setQueriesData).toHaveBeenCalledWith(+ { queryKey: ["integration-sync-preview", "p"] },+ expect.any(Function),+ ),+ );+ for (const prefix of [+ "integration-sync",+ "integration-sync-preview",+ "integration-sync-review",+ ])+ expect(mocks.client.invalidateQueries).not.toHaveBeenCalledWith({+ queryKey: [prefix, "p"],+ });+});++it("patches affected names from title broadcasts without a loaded board", async () => {+ mocks.board = null;+ mocks.getTask.mockClear();+ renderHook(() => useProjectWebSocket("p"));+ Socket.current.message("TASK_UPDATED", { taskId: "a", taskTitle: "Current" });+ await vi.waitFor(() =>+ expect(mocks.client.setQueriesData).toHaveBeenCalledWith(+ { queryKey: ["integration-sync-preview", "p"] },+ expect.any(Function),+ ),+ );+ expect(mocks.getTask).not.toHaveBeenCalled();+ expect(mocks.client.invalidateQueries).not.toHaveBeenCalledWith({+ queryKey: ["integration-sync-preview", "p"],+ });+});diff --git a/apps/web/src/hooks/use-project-websocket-lifecycle.test.tsx b/apps/web/src/hooks/use-project-websocket-lifecycle.test.tsxindex c7c2fd4cf..6c4d7de32 100644--- a/apps/web/src/hooks/use-project-websocket-lifecycle.test.tsx+++ b/apps/web/src/hooks/use-project-websocket-lifecycle.test.tsx@@ -16,6 +16,7 @@ const { client, auth } = vi.hoisted(() => ({cancelQueries: vi.fn().mockResolvedValue(undefined),invalidateQueries: vi.fn(),setQueryData: vi.fn(),+ setQueriesData: vi.fn(),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 104ad6806..c69647e31 100644--- a/apps/web/src/hooks/use-project-websocket.ts+++ b/apps/web/src/hooks/use-project-websocket.ts@@ -14,6 +14,7 @@ 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";export function getWsUrl(projectId: string) {const base = getApiUrl("ws");@@ -69,6 +70,7 @@ export function useProjectWebSocket(projectId: string) {taskId?: string;sourceTaskId?: string;targetTaskId?: string;+ linksChanged?: boolean;}) {if ([@@ -89,7 +91,8 @@ export function useProjectWebSocket(projectId: string) {if (message.type === "PROJECT_UPDATED") {queryClient.invalidateQueries({ queryKey: ["projects"] });queryClient.invalidateQueries({ queryKey: ["labels"] });- queryClient.invalidateQueries({ queryKey: ["external-links"] });+ if (message.linksChanged)+ queryClient.invalidateQueries({ queryKey: ["external-links"] });return;}@@ -187,6 +190,13 @@ 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.type === "PROJECT_MOVED") {markBoardCacheChanged(queryClient, projectId);for (const queryKey of [@@ -365,6 +375,13 @@ export function useProjectWebSocket(projectId: string) {}const staleOwnCounts =(parentCountVersions.get(taskId) ?? 0) > sequence;+ if (task.projectId === projectId)+ patchSyncTaskTitles(+ queryClient,+ projectId,+ taskId,+ task.title,+ );const { subtaskCounts, ...taskFields } = task;if (staleOwnCounts)void queryClient.invalidateQueries({diff --git a/apps/web/src/lib/patch-sync-task-titles.test.ts b/apps/web/src/lib/patch-sync-task-titles.test.tsnew file mode 100644index 000000000..3daebfbd9--- /dev/null+++ b/apps/web/src/lib/patch-sync-task-titles.test.ts@@ -0,0 +1,47 @@+import { QueryClient } from "@tanstack/react-query";+import { expect, it } from "vite-plus/test";+import { patchSyncTaskTitles } from "./patch-sync-task-titles";++it("updates saved and draft task names without changing scope or tokens", () => {+ const client = new QueryClient();+ const snapshot = {+ matchingTasks: [+ { id: "task", title: "Old" },+ { id: "other", title: "Other" },+ ],+ pausedTasks: [{ id: "task", title: "Old", linkId: "link" }],+ matching: 3,+ willPause: 2,+ previewToken: "reviewed",+ };+ const keys = [+ ["integration-sync", "project", "github", ""],+ ["integration-sync-preview", "project", "gitea", { outgoing: "labels" }],+ ];+ for (const key of keys) client.setQueryData(key, snapshot);+ client.setQueryData(["integration-sync", "foreign"], snapshot);+ client.setQueryData(+ ["integration-sync-review", "project", "github", "link"],+ { token: "review" },+ );+ patchSyncTaskTitles(client, "project", "task", "Current");+ for (const key of keys)+ expect(client.getQueryData(key)).toEqual({+ ...snapshot,+ matchingTasks: [+ { id: "task", title: "Current" },+ { id: "other", title: "Other" },+ ],+ pausedTasks: [{ id: "task", title: "Current", linkId: "link" }],+ });+ expect(client.getQueryData(["integration-sync", "foreign"])).toBe(snapshot);+ expect(+ client.getQueryData([+ "integration-sync-review",+ "project",+ "github",+ "link",+ ]),+ ).toEqual({ token: "review" });+ client.clear();+});diff --git a/apps/web/src/lib/patch-sync-task-titles.ts b/apps/web/src/lib/patch-sync-task-titles.tsnew file mode 100644index 000000000..86ee1fee2--- /dev/null+++ b/apps/web/src/lib/patch-sync-task-titles.ts@@ -0,0 +1,30 @@+import type { QueryClient } from "@tanstack/react-query";+import type { SyncPreview } from "@/fetchers/integration-sync/types";++export function patchSyncTaskTitles(+ client: QueryClient,+ projectId: string,+ taskId: string,+ title: string,+) {+ for (const prefix of ["integration-sync", "integration-sync-preview"])+ client.setQueriesData<SyncPreview>(+ { queryKey: [prefix, projectId] },+ (current) => {+ if (!current) return current;+ if (+ ![...current.matchingTasks, ...current.pausedTasks].some(+ (task) => task.id === taskId && task.title !== title,+ )+ )+ return current;+ const patch = <T extends { id: string; title: string }>(tasks: T[]) =>+ tasks.map((task) => (task.id === taskId ? { ...task, title } : task));+ return {+ ...current,+ matchingTasks: patch(current.matchingTasks),+ pausedTasks: patch(current.pausedTasks),+ };+ },+ );+}diff --git a/tests/api-integration/github-import-bounds.test.ts b/tests/api-integration/github-import-bounds.test.tsindex 3882002af..9e2510198 100644--- a/tests/api-integration/github-import-bounds.test.ts+++ b/tests/api-integration/github-import-bounds.test.ts@@ -158,6 +158,39 @@ async function saved() {}describe("bounded resumable GitHub import", () => {+ it("pauses a newly imported issue that misses the outgoing rule before announcing it", async () => {+ const { member, integration, config, request } = await setup();+ const [root] = await db+ .insert(schema.labelTable)+ .values({+ workspaceId: member.workspace.id,+ name: "export",+ color: "red",+ })+ .returning();+ await db+ .update(schema.integrationTable)+ .set({+ config: JSON.stringify({+ ...config,+ syncRules: {+ outgoing: { mode: "labels", match: "any", labels: [root.id] },+ incoming: { mode: "all" },+ },+ }),+ })+ .where(eq(schema.integrationTable.id, integration.id));+ mocks.verify.mockResolvedValue({+ graphql: mocks.graphql,+ rest: { issues: { get: async () => ({ data: { labels: [] } }) } },+ });+ serveIssues(1);+ expect((await request()).status).toBe(200);+ const link = (await db.query.externalLinkTable.findMany())[0]!;+ expect(JSON.parse(link.metadata!)).toMatchObject({+ syncFilterPaused: true,+ });+ });it("rejects an incoming rule change while fetching a page before creating tasks or consuming its cursor", async () => {const { integration, config, request } = await setup();const started = deferred();diff --git a/tests/api-integration/integration-label-dispatch.test.ts b/tests/api-integration/integration-label-dispatch.test.tsindex 06436bc98..4fee7fee8 100644--- a/tests/api-integration/integration-label-dispatch.test.ts+++ b/tests/api-integration/integration-label-dispatch.test.ts@@ -92,7 +92,11 @@ it.each(["github", "gitea", "gitlab"] as const)(async (provider) => {const f = await fixture(provider);await updateExternalLink(f.link.id, {- metadata: { syncInitializationPending: true, syncInitializedState: true },+ metadata: {+ syncInitializationPending: true,+ syncInitializedState: true,+ syncCreatedText: { title: f.task.title, description: "" },+ },});const link = (await db.query.externalLinkTable.findFirst({where: eq(schema.externalLinkTable.id, f.link.id),@@ -130,6 +134,7 @@ it.each(["github", "gitea", "gitlab"] as const)(},link,{+ text: async () => undefined,close: mocks.addLabel,labels: (names, write) => {if (provider === "github")diff --git a/tests/api-integration/integration-sync-imported-link.test.ts b/tests/api-integration/integration-sync-imported-link.test.tsnew file mode 100644index 000000000..da1814378--- /dev/null+++ b/tests/api-integration/integration-sync-imported-link.test.ts@@ -0,0 +1,131 @@+import { eq } from "drizzle-orm";+import { beforeEach, expect, it, vi } from "vite-plus/test";+import db, { schema } from "../../apps/api/src/database";+import { handleIssueOpened } from "../../apps/api/src/plugins/github/webhooks/issue-opened";+import { handleGiteaIssueOpened } from "../../apps/api/src/plugins/gitea/webhooks/issue-opened";+import { handleGitlabIssueOpened } from "../../apps/api/src/plugins/gitlab/webhooks/issue-opened";+import { canSyncTask } from "../../apps/api/src/plugins/sync/eligibility";+import { resetTestDatabase } from "./helpers/database";+import {+ createProjectFixture,+ createWorkspaceMember,+} from "./helpers/fixtures";++vi.mock("../../apps/api/src/events", () => ({ publishEvent: async () => {} }));+vi.mock("../../apps/api/src/plugins/github/utils/github-app", () => ({+ getGithubApp: () => ({+ getInstallationOctokit: async () => ({+ rest: { issues: { createComment: async () => {} } },+ }),+ }),+}));+beforeEach(async () => {+ await resetTestDatabase();+});++it.each(+ (["github", "gitea", "gitlab"] as const).flatMap((provider) =>+ [true, false].map((qualifying) => ({ provider, qualifying })),+ ),+)(+ "$provider imports links with their committed outgoing scope (qualifying=$qualifying)",+ async ({ provider, qualifying }) => {+ const { workspace, user } = await createWorkspaceMember();+ const { project } = await createProjectFixture({+ workspaceId: workspace.id,+ });+ const [label] = await db+ .insert(schema.labelTable)+ .values({ workspaceId: workspace.id, name: "export", color: "red" })+ .returning();+ const [integration] = await db+ .insert(schema.integrationTable)+ .values({+ projectId: project.id,+ type: provider,+ isActive: true,+ config: JSON.stringify({+ repositoryOwner: "team",+ repositoryName: "repo",+ repositoryId: 1,+ installationId: 2,+ verifiedGithubAccountId: "3",+ verifiedByUserId: user.id,+ baseUrl: "https://git.example",+ projectPath: "team/repo",+ accessToken: "fake-test-token",+ commentTaskLinkOnGitHubIssue: false,+ commentTaskLinkOnGiteaIssue: false,+ commentTaskLinkOnGitlabIssue: false,+ syncRules: {+ outgoing: { mode: "labels", match: "any", labels: [label.id] },+ incoming: { mode: "all" },+ },+ }),+ })+ .returning();+ const labels = qualifying ? ["export"] : ["other"];+ const issue = {+ number: 9,+ title: "Imported issue",+ body: "Body",+ html_url: "https://git.example/team/repo/issues/9",+ labels,+ user: { login: "author" },+ };+ const repository = {+ id: 1,+ owner: { login: "team" },+ name: "repo",+ full_name: "team/repo",+ html_url: "https://git.example/team/repo",+ };+ if (provider === "github")+ await handleIssueOpened(+ { action: "opened", installation: { id: 2 }, issue, repository },+ integration.id,+ );+ else if (provider === "gitea")+ await handleGiteaIssueOpened(+ { action: "opened", issue, repository },+ integration.id,+ );+ else+ await handleGitlabIssueOpened(+ {+ object_attributes: {+ iid: 9,+ title: issue.title,+ description: "Body",+ url: issue.html_url,+ },+ labels: labels.map((title) => ({ title })),+ project: {+ name: "repo",+ path_with_namespace: "team/repo",+ web_url: "https://git.example/team/repo",+ },+ },+ integration.id,+ );+ const link = (await db.query.externalLinkTable.findMany())[0]!;+ expect(link).toBeDefined();+ expect(JSON.parse(link.metadata!).syncFilterPaused === true).toBe(+ !qualifying,+ );+ if (!qualifying) {+ await db.insert(schema.labelTable).values({+ taskId: link.taskId,+ workspaceId: workspace.id,+ name: label.name,+ color: label.color,+ });+ expect(await canSyncTask(link.taskId, integration.id)).toBe(false);+ expect(+ await db.query.externalLinkTable.findFirst({+ where: eq(schema.externalLinkTable.id, link.id),+ }),+ ).toMatchObject({ id: link.id, integrationId: integration.id });+ }+ },+);diff --git a/tests/api-integration/integration-sync-providers.test.ts b/tests/api-integration/integration-sync-providers.test.tsindex 233d19e7d..f94a1022a 100644--- a/tests/api-integration/integration-sync-providers.test.ts+++ b/tests/api-integration/integration-sync-providers.test.ts@@ -367,6 +367,83 @@ describe.each(["github", "gitea", "gitlab"] as const)(expect(JSON.parse(link!.metadata!)).toMatchObject({ state: "closed" });});+ it.each([false, true])(+ "replays edits made during creation and retries failed text initialization (failure=%s)",+ async (failure) => {+ const f = await setup(type);+ await f.assign();+ let release!: () => void;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ const response = await create.getMockImplementation()!();+ create.mockImplementationOnce(async () => {+ await gate;+ return response;+ });+ if (failure)+ mocks.update.mockRejectedValueOnce(+ new Error("Temporary text initialization failure"),+ );+ const exportTask = reconcileTaskSync(f.project.id, f.task.id);+ try {+ await vi.waitFor(() => expect(create).toHaveBeenCalledOnce());+ await db+ .update(schema.taskTable)+ .set({+ title: "Edited title",+ description: "Edited description",+ status: f.columns.done.slug,+ columnId: f.columns.done.id,+ priority: "urgent",+ })+ .where(eq(schema.taskTable.id, f.task.id));+ } finally {+ release();+ await exportTask;+ }+ if (failure) {+ const link = (await db.query.externalLinkTable.findMany())[0]!;+ expect(JSON.parse(link.metadata!)).toMatchObject({+ syncInitializationPending: true,+ });+ await reconcileTaskSync(f.project.id, f.task.id);+ }+ expect(create).toHaveBeenCalledOnce();+ const updates = mocks.update.mock.calls.map((call) => call.at(-1));+ expect(updates).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ title: "Edited title" }),+ expect.objectContaining(+ type === "gitlab"+ ? { description: expect.stringContaining("Edited description") }+ : { body: expect.stringContaining("Edited description") },+ ),+ expect.objectContaining(+ type === "gitlab"+ ? { state_event: "close" }+ : { state: "closed" },+ ),+ ]),+ );+ const names = mocks.labels.mock.calls[0]![type === "github" ? 4 : 2];+ expect(names).toEqual(+ expect.arrayContaining(["priority:urgent", "status:done"]),+ );+ expect(names).not.toContain("status:to-do");+ const link = (await db.query.externalLinkTable.findMany())[0]!;+ expect(link.title).toBe("Edited title");+ expect(JSON.parse(link.metadata!)).toMatchObject({+ syncInitializationPending: false,+ syncInitializedText: {+ title: "Edited title",+ description: "Edited description",+ },+ state: "closed",+ });+ },+ );+it.each(["labels", "rules", "deactivation"])("pauses a dispatched creation after %s change without follow-up writes",async (change) => {diff --git a/tests/api/plugins/gitea/webhooks/issue-opened.test.ts b/tests/api/plugins/gitea/webhooks/issue-opened.test.tsindex a1be2930b..7bc07d358 100644--- a/tests/api/plugins/gitea/webhooks/issue-opened.test.ts+++ b/tests/api/plugins/gitea/webhooks/issue-opened.test.ts@@ -42,6 +42,10 @@ const mocks = vi.hoisted(() => {};});+vi.mock("../../../../../apps/api/src/plugins/sync/eligibility", () => ({+ canSyncTask: async () => true,+}));+vi.mock("../../../../../apps/api/src/database", () => ({ default: mocks.db }));vi.mock("../../../../../apps/api/src/events", () => ({diff --git a/tests/api/plugins/github/webhooks/issue-opened.test.ts b/tests/api/plugins/github/webhooks/issue-opened.test.tsindex 41f15b67b..5e10b661e 100644--- a/tests/api/plugins/github/webhooks/issue-opened.test.ts+++ b/tests/api/plugins/github/webhooks/issue-opened.test.ts@@ -68,6 +68,10 @@ const mocks = vi.hoisted(() => {};});+vi.mock("../../../../../apps/api/src/plugins/sync/eligibility", () => ({+ canSyncTask: async () => true,+}));+vi.mock("../../../../../apps/api/src/database", () => ({default: mocks.mockDb,}));diff --git a/tests/api/plugins/gitlab/webhooks/issue-opened.test.ts b/tests/api/plugins/gitlab/webhooks/issue-opened.test.tsindex 3076fe102..41061c1d3 100644--- a/tests/api/plugins/gitlab/webhooks/issue-opened.test.ts+++ b/tests/api/plugins/gitlab/webhooks/issue-opened.test.ts@@ -41,6 +41,10 @@ const mocks = vi.hoisted(() => {};});+vi.mock("../../../../../apps/api/src/plugins/sync/eligibility", () => ({+ canSyncTask: async () => true,+}));+vi.mock("../../../../../apps/api/src/database", () => ({ default: mocks.db }));vi.mock("../../../../../apps/api/src/events", () => ({diff --git a/tests/api/ws/broadcast.test.ts b/tests/api/ws/broadcast.test.tsindex b984cc8ea..8e954ec7a 100644--- a/tests/api/ws/broadcast.test.ts+++ b/tests/api/ws/broadcast.test.ts@@ -28,6 +28,10 @@ const projectUpdateHandler = vi([eventName]: [string]) => eventName === "project.updated",)?.[1];+const taskTitleHandler = vi+ .mocked(subscribeToEvent)+ .mock.calls.find(([eventName]) => eventName === "task.title_changed")![1];+function makeFakeWs() {return {send: vi.fn(),@@ -185,6 +189,51 @@ describe("broadcastToProject", () => {removeConnection("proj-1", conn);});+ it("preserves a link refresh when a later unrelated project update shares its batch", async () => {+ const ws = makeFakeWs();+ const conn = addConnection("proj-1", ws, "user-1", "init-1", "workspace");+ await projectUpdateHandler?.({ projectId: "proj-1", linksChanged: true });+ await projectUpdateHandler?.({ projectId: "proj-1" });+ const send = (ws as { send: ReturnType<typeof vi.fn> }).send;+ await vi.waitFor(() => expect(send).toHaveBeenCalledOnce(), {+ timeout: 300,+ });+ expect(JSON.parse(send.mock.calls[0][0])).toMatchObject({+ type: "PROJECT_UPDATED",+ projectId: "proj-1",+ linksChanged: true,+ });+ removeConnection("proj-1", conn);+ });++ it("preserves the latest task title through later unrelated updates in the batch", async () => {+ const ws = makeFakeWs();+ const conn = addConnection("proj-1", ws, "user-1", "init-1", "workspace");+ await taskTitleHandler({+ projectId: "proj-1",+ taskId: "t1",+ newTitle: "First",+ });+ await taskTitleHandler({+ projectId: "proj-1",+ taskId: "t1",+ newTitle: "Current",+ });+ broadcastToProject("proj-1", {+ type: "TASK_UPDATED",+ projectId: "proj-1",+ taskId: "t1",+ });+ const send = (ws as { send: ReturnType<typeof vi.fn> }).send;+ await vi.waitFor(() => expect(send).toHaveBeenCalledOnce(), {+ timeout: 300,+ });+ expect(JSON.parse(send.mock.calls[0][0])).toMatchObject({+ taskTitle: "Current",+ });+ removeConnection("proj-1", conn);+ });+it("does not deliver to connections on a different project", async () => {const ws = makeFakeWs();const conn = addConnection("proj-2", ws, "user-1", "init-1", "workspace");diff --git a/tests/api/ws/redis-link-refresh.test.ts b/tests/api/ws/redis-link-refresh.test.tsnew file mode 100644index 000000000..247b52930--- /dev/null+++ b/tests/api/ws/redis-link-refresh.test.ts@@ -0,0 +1,45 @@+import { expect, it, vi } from "vite-plus/test";+import { RedisBroadcastAdapter } from "../../../apps/api/src/ws/redis-broadcast-adapter";++const mocks = vi.hoisted(() => ({+ on: vi.fn(),+ off: vi.fn(),+ psubscribe: vi.fn().mockResolvedValue(undefined),+ punsubscribe: vi.fn().mockResolvedValue(undefined),+}));+vi.mock("../../../apps/api/src/redis", () => ({+ getRedisSub: () => mocks,+ getRedisPub: () => ({ publish: vi.fn() }),+ closeRedis: async () => {},+}));++it("retains the link-refresh flag when receiving a Redis project broadcast", async () => {+ const adapter = new RedisBroadcastAdapter();+ const receive = vi.fn();+ await adapter.subscribe(receive);+ const handle = mocks.on.mock.calls.find(+ ([event]) => event === "pmessage",+ )![1];+ handle(+ "kaneo:ws:*:broadcast",+ "kaneo:ws:project:broadcast",+ JSON.stringify({+ projectId: "project",+ message: {+ type: "PROJECT_UPDATED",+ projectId: "project",+ linksChanged: true,+ taskTitle: "Current",+ },+ }),+ );+ expect(receive).toHaveBeenCalledWith(+ expect.objectContaining({+ message: expect.objectContaining({+ linksChanged: true,+ taskTitle: "Current",+ }),+ }),+ );+ await adapter.shutdown();+});