⚡ 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): revalidate links across webhook and import continuations
Tin802c5bd3384b
diff --git a/apps/api/src/github-integration/controllers/import-issues.ts b/apps/api/src/github-integration/controllers/import-issues.tsindex 70328deb1..5461791b7 100644--- a/apps/api/src/github-integration/controllers/import-issues.ts+++ b/apps/api/src/github-integration/controllers/import-issues.ts@@ -326,7 +326,19 @@ async function applyPage(),).for("no key update");- if (!task) {+ const [linked] = await tx+ .select({ id: externalLinkTable.id })+ .from(externalLinkTable)+ .where(+ and(+ eq(externalLinkTable.integrationId, integrationId),+ eq(externalLinkTable.resourceType, "issue"),+ eq(externalLinkTable.externalId, String(current.number)),+ eq(externalLinkTable.taskId, current.taskId),+ ),+ )+ .for("update");+ if (!task || !linked) {state.skipped++;finishIssue(state);return;@@ -423,13 +435,20 @@ async function importIssue(const priority = extractIssuePriority(issue.labels.nodes);const status = extractIssueStatus(issue.labels.nodes);if (link) {- const task = await tx.query.taskTable.findFirst({- where: and(- eq(taskTable.id, link.taskId),- eq(taskTable.projectId, projectId),- ),- });+ const [task] = await tx+ .select()+ .from(taskTable)+ .where(+ and(eq(taskTable.id, link.taskId), eq(taskTable.projectId, projectId)),+ )+ .for("no key update");if (!task) return null;+ const [linked] = await tx+ .select({ id: externalLinkTable.id })+ .from(externalLinkTable)+ .where(eq(externalLinkTable.id, link.id))+ .for("update");+ if (!linked) return null;const [updated] = await tx.update(taskTable).set({diff --git a/apps/api/src/plugins/gitea/webhooks/issue-closed.ts b/apps/api/src/plugins/gitea/webhooks/issue-closed.tsindex 8d519ba33..a8e010486 100644--- a/apps/api/src/plugins/gitea/webhooks/issue-closed.ts+++ b/apps/api/src/plugins/gitea/webhooks/issue-closed.ts@@ -1,7 +1,5 @@-import {- linkedTaskScope,- withIntegrationTask,-} from "../../github/services/integration-task-scope";+import { withIntegrationLink } from "../../github/services/with-integration-link";+import { linkedTaskScope } from "../../github/services/integration-task-scope";import { and, eq } from "drizzle-orm";import db from "../../../database";import { externalLinkTable } from "../../../database/schema";@@ -69,10 +67,10 @@ export async function handleGiteaIssueClosed(continue;}- await withIntegrationTask(- externalLink.taskId,+ await withIntegrationLink(+ externalLink,integration,- async (db, afterCommit) => {+ async (db, afterCommit, externalLink) => {const task = await db.query.taskTable.findFirst({where: linkedTaskScope(externalLink.taskId, integration.projectId),});diff --git a/apps/api/src/plugins/gitea/webhooks/issue-comment-created.ts b/apps/api/src/plugins/gitea/webhooks/issue-comment-created.tsindex 634110e74..be4d1bf2d 100644--- a/apps/api/src/plugins/gitea/webhooks/issue-comment-created.ts+++ b/apps/api/src/plugins/gitea/webhooks/issue-comment-created.ts@@ -1,4 +1,4 @@-import { withIntegrationTask } from "../../github/services/integration-task-scope";+import { withIntegrationLink } from "../../github/services/with-integration-link";import { activityTable } from "../../../database/schema";import { findExternalLink } from "../../github/services/link-manager";import {@@ -68,28 +68,32 @@ export async function handleGiteaIssueCommentCreated(continue;}- await withIntegrationTask(existingLink.taskId, integration, async (db) => {- await db- .insert(activityTable)- .values({- taskId: existingLink.taskId,- type: "comment",- content: comment.body,- externalUserName: username || "Unknown",- externalUserAvatar: comment.user?.avatar_url ?? null,- externalSource: "gitea",- externalUrl: comment.html_url,- eventData: {- externalCommentId: comment.id,- },- })- .onConflictDoNothing({- target: [- activityTable.taskId,- activityTable.externalSource,- activityTable.externalUrl,- ],- });- });+ await withIntegrationLink(+ existingLink,+ integration,+ async (db, _afterCommit, existingLink) => {+ await db+ .insert(activityTable)+ .values({+ taskId: existingLink.taskId,+ type: "comment",+ content: comment.body,+ externalUserName: username || "Unknown",+ externalUserAvatar: comment.user?.avatar_url ?? null,+ externalSource: "gitea",+ externalUrl: comment.html_url,+ eventData: {+ externalCommentId: comment.id,+ },+ })+ .onConflictDoNothing({+ target: [+ activityTable.taskId,+ activityTable.externalSource,+ activityTable.externalUrl,+ ],+ });+ },+ );}}diff --git a/apps/api/src/plugins/gitea/webhooks/issue-edited.ts b/apps/api/src/plugins/gitea/webhooks/issue-edited.tsindex 7709dade2..687c70e48 100644--- a/apps/api/src/plugins/gitea/webhooks/issue-edited.ts+++ b/apps/api/src/plugins/gitea/webhooks/issue-edited.ts@@ -1,7 +1,5 @@-import {- linkedTaskScope,- withIntegrationTask,-} from "../../github/services/integration-task-scope";+import { withIntegrationLink } from "../../github/services/with-integration-link";+import { linkedTaskScope } from "../../github/services/integration-task-scope";import { taskTable } from "../../../database/schema";import {findExternalLink,@@ -65,102 +63,108 @@ export async function handleGiteaIssueEdited(continue;}- await withIntegrationTask(externalLink.taskId, integration, async (db) => {- const task = await db.query.taskTable.findFirst({- where: linkedTaskScope(externalLink.taskId, integration.projectId),- });-- if (!task) {- return;- }-- const metadata = externalLink.metadata- ? JSON.parse(externalLink.metadata)- : {};+ await withIntegrationLink(+ externalLink,+ integration,+ async (db, _afterCommit, externalLink) => {+ const task = await db.query.taskTable.findFirst({+ where: linkedTaskScope(externalLink.taskId, integration.projectId),+ });- const updateData: Record<string, unknown> = {};- const updatedMetadata = { ...metadata };+ if (!task) {+ return;+ }- if (!updatedMetadata.lastSync) {- updatedMetadata.lastSync = {};- }+ const metadata = externalLink.metadata+ ? JSON.parse(externalLink.metadata)+ : {};- if (changes.title) {- const lastTitleSync = metadata.lastSync?.title;+ const updateData: Record<string, unknown> = {};+ const updatedMetadata = { ...metadata };- let shouldUpdateTitle = true;+ if (!updatedMetadata.lastSync) {+ updatedMetadata.lastSync = {};+ }- if (lastTitleSync) {- if (- lastTitleSync.value === issue.title &&- lastTitleSync.source === "kaneo"- ) {- shouldUpdateTitle = false;+ if (changes.title) {+ const lastTitleSync = metadata.lastSync?.title;++ let shouldUpdateTitle = true;++ if (lastTitleSync) {+ if (+ lastTitleSync.value === issue.title &&+ lastTitleSync.source === "kaneo"+ ) {+ shouldUpdateTitle = false;+ }+ const timeSinceLastSync =+ Date.now() - new Date(lastTitleSync.timestamp).getTime();+ if (timeSinceLastSync < 2000 && shouldUpdateTitle) {+ shouldUpdateTitle = false;+ }}- const timeSinceLastSync =- Date.now() - new Date(lastTitleSync.timestamp).getTime();- if (timeSinceLastSync < 2000 && shouldUpdateTitle) {- shouldUpdateTitle = false;- }- }- if (shouldUpdateTitle) {- updateData.title = issue.title;- updatedMetadata.lastSync.title = {- timestamp: new Date().toISOString(),- source: "gitea",- value: issue.title,- };+ if (shouldUpdateTitle) {+ updateData.title = issue.title;+ updatedMetadata.lastSync.title = {+ timestamp: new Date().toISOString(),+ source: "gitea",+ value: issue.title,+ };+ }}- }-- if (changes.body) {- const lastDescSync = metadata.lastSync?.description;- const formattedDescription = formatTaskDescriptionFromIssue(issue.body);- let shouldUpdateDescription = true;-- if (lastDescSync) {- if (- lastDescSync.value === formattedDescription &&- lastDescSync.source === "kaneo"- ) {- shouldUpdateDescription = false;+ if (changes.body) {+ const lastDescSync = metadata.lastSync?.description;+ const formattedDescription = formatTaskDescriptionFromIssue(+ issue.body,+ );++ let shouldUpdateDescription = true;++ if (lastDescSync) {+ if (+ lastDescSync.value === formattedDescription &&+ lastDescSync.source === "kaneo"+ ) {+ shouldUpdateDescription = false;+ }+ const timeSinceLastSync =+ Date.now() - new Date(lastDescSync.timestamp).getTime();+ if (timeSinceLastSync < 2000 && shouldUpdateDescription) {+ shouldUpdateDescription = false;+ }}- const timeSinceLastSync =- Date.now() - new Date(lastDescSync.timestamp).getTime();- if (timeSinceLastSync < 2000 && shouldUpdateDescription) {- shouldUpdateDescription = false;++ if (shouldUpdateDescription) {+ updateData.description = formattedDescription;+ updatedMetadata.lastSync.description = {+ timestamp: new Date().toISOString(),+ source: "gitea",+ value: formattedDescription,+ };}}- if (shouldUpdateDescription) {- updateData.description = formattedDescription;- updatedMetadata.lastSync.description = {- timestamp: new Date().toISOString(),- source: "gitea",- value: formattedDescription,- };+ if (Object.keys(updateData).length > 0) {+ await db+ .update(taskTable)+ .set(updateData)+ .where(linkedTaskScope(task.id, integration.projectId));++ await updateExternalLink(+ externalLink.id,+ {+ title: issue.title,+ metadata: updatedMetadata,+ },+ db,+ );}- }-- if (Object.keys(updateData).length > 0) {- await db- .update(taskTable)- .set(updateData)- .where(linkedTaskScope(task.id, integration.projectId));-- await updateExternalLink(- externalLink.id,- {- title: issue.title,- metadata: updatedMetadata,- },- db,- );- }-- return;- });++ return;+ },+ );}}diff --git a/apps/api/src/plugins/gitea/webhooks/issue-labeled.ts b/apps/api/src/plugins/gitea/webhooks/issue-labeled.tsindex 8c7f7afa1..843da0fff 100644--- a/apps/api/src/plugins/gitea/webhooks/issue-labeled.ts+++ b/apps/api/src/plugins/gitea/webhooks/issue-labeled.ts@@ -1,7 +1,7 @@+import { withIntegrationLink } from "../../github/services/with-integration-link";import {type IntegrationDatabase,linkedTaskScope,- withIntegrationTask,} from "../../github/services/integration-task-scope";import { eq, inArray } from "drizzle-orm";import { labelTable, taskTable } from "../../../database/schema";@@ -146,10 +146,10 @@ export async function handleGiteaIssueLabeled(continue;}- await withIntegrationTask(- existingLink.taskId,+ await withIntegrationLink(+ existingLink,integration,- async (db, afterCommit) => {+ async (db, afterCommit, existingLink) => {const priority = extractIssuePriority(issue.labels);const status = extractIssueStatus(issue.labels);diff --git a/apps/api/src/plugins/gitea/webhooks/issue-reopened.ts b/apps/api/src/plugins/gitea/webhooks/issue-reopened.tsindex 120835027..2f6dd8460 100644--- a/apps/api/src/plugins/gitea/webhooks/issue-reopened.ts+++ b/apps/api/src/plugins/gitea/webhooks/issue-reopened.ts@@ -1,7 +1,5 @@-import {- linkedTaskScope,- withIntegrationTask,-} from "../../github/services/integration-task-scope";+import { withIntegrationLink } from "../../github/services/with-integration-link";+import { linkedTaskScope } from "../../github/services/integration-task-scope";import { and, eq } from "drizzle-orm";import db from "../../../database";import { externalLinkTable } from "../../../database/schema";@@ -70,10 +68,10 @@ export async function handleGiteaIssueReopened(continue;}- await withIntegrationTask(- externalLink.taskId,+ await withIntegrationLink(+ externalLink,integration,- async (db, afterCommit) => {+ async (db, afterCommit, externalLink) => {const task = await db.query.taskTable.findFirst({where: linkedTaskScope(externalLink.taskId, integration.projectId),});diff --git a/apps/api/src/plugins/github/services/integration-task-scope.ts b/apps/api/src/plugins/github/services/integration-task-scope.tsindex c1f4f9e75..1db5efb30 100644--- a/apps/api/src/plugins/github/services/integration-task-scope.ts+++ b/apps/api/src/plugins/github/services/integration-task-scope.ts@@ -44,7 +44,7 @@ export async function withIntegrationTask<T>(: undefined,),)- .for("key share", { of: projectTable });+ .for("key share", { of: [projectTable, integrationTable] });if (!project) return undefined;if (taskId !== null) {const [task] = await txdiff --git a/apps/api/src/plugins/github/webhooks/issue-closed.ts b/apps/api/src/plugins/github/webhooks/issue-closed.tsindex 5cd66682a..dca964402 100644--- a/apps/api/src/plugins/github/webhooks/issue-closed.ts+++ b/apps/api/src/plugins/github/webhooks/issue-closed.ts@@ -1,7 +1,5 @@-import {- linkedTaskScope,- withIntegrationTask,-} from "../services/integration-task-scope";+import { withIntegrationLink } from "../services/with-integration-link";+import { linkedTaskScope } from "../services/integration-task-scope";import { and, eq } from "drizzle-orm";import db from "../../../database";import { externalLinkTable } from "../../../database/schema";@@ -49,10 +47,10 @@ export async function handleIssueClosed(payload: IssueClosedPayload) {continue;}- await withIntegrationTask(- externalLink.taskId,+ await withIntegrationLink(+ externalLink,integration,- async (db, afterCommit) => {+ async (db, afterCommit, externalLink) => {const task = await db.query.taskTable.findFirst({where: linkedTaskScope(externalLink.taskId, integration.projectId),});diff --git a/apps/api/src/plugins/github/webhooks/issue-comment-created.ts b/apps/api/src/plugins/github/webhooks/issue-comment-created.tsindex 8e4b738b7..23071dc0e 100644--- a/apps/api/src/plugins/github/webhooks/issue-comment-created.ts+++ b/apps/api/src/plugins/github/webhooks/issue-comment-created.ts@@ -1,4 +1,4 @@-import { withIntegrationTask } from "../services/integration-task-scope";+import { withIntegrationLink } from "../services/with-integration-link";import { activityTable } from "../../../database/schema";import { findExternalLink } from "../services/link-manager";import { findAllIntegrationsByRepo } from "../services/task-service";@@ -53,27 +53,31 @@ export async function handleIssueCommentCreated(continue;}- await withIntegrationTask(existingLink.taskId, integration, async (db) => {- await db- .insert(activityTable)- .values({- taskId: existingLink.taskId,- type: "comment",- content: comment.body,- externalUserName: comment.user?.login ?? "Unknown",- externalUserAvatar: comment.user?.avatar_url ?? null,- externalSource: "github",- externalUrl: comment.html_url,- })- .onConflictDoNothing({- target: [- activityTable.taskId,- activityTable.externalSource,- activityTable.externalUrl,- ],- });+ await withIntegrationLink(+ existingLink,+ integration,+ async (db, _afterCommit, existingLink) => {+ await db+ .insert(activityTable)+ .values({+ taskId: existingLink.taskId,+ type: "comment",+ content: comment.body,+ externalUserName: comment.user?.login ?? "Unknown",+ externalUserAvatar: comment.user?.avatar_url ?? null,+ externalSource: "github",+ externalUrl: comment.html_url,+ })+ .onConflictDoNothing({+ target: [+ activityTable.taskId,+ activityTable.externalSource,+ activityTable.externalUrl,+ ],+ });- return;- });+ return;+ },+ );}}diff --git a/apps/api/src/plugins/github/webhooks/issue-edited.ts b/apps/api/src/plugins/github/webhooks/issue-edited.tsindex 7a91fd900..8ce77232f 100644--- a/apps/api/src/plugins/github/webhooks/issue-edited.ts+++ b/apps/api/src/plugins/github/webhooks/issue-edited.ts@@ -1,7 +1,5 @@-import {- linkedTaskScope,- withIntegrationTask,-} from "../services/integration-task-scope";+import { withIntegrationLink } from "../services/with-integration-link";+import { linkedTaskScope } from "../services/integration-task-scope";import { taskTable } from "../../../database/schema";import { findExternalLink, updateExternalLink } from "../services/link-manager";import { findAllIntegrationsByRepo } from "../services/task-service";@@ -71,132 +69,136 @@ export async function handleIssueEdited(payload: IssueEditedPayload) {continue;}- await withIntegrationTask(externalLink.taskId, integration, async (db) => {- const task = await db.query.taskTable.findFirst({- where: linkedTaskScope(externalLink.taskId, integration.projectId),- });-- if (!task) {- console.error(`Task ${externalLink.taskId} not found`);- return;- }-- const metadata = parseLinkMetadata<IssueEditedMetadata>(- externalLink.metadata,- {- externalLinkId: externalLink.id,- source: "issue_edited",- },- );-- const updateData: Record<string, unknown> = {};- const updatedMetadata: IssueEditedMetadata = { ...metadata };-- if (!updatedMetadata.lastSync) {- updatedMetadata.lastSync = {};- }-- if (changes.title) {- const lastTitleSync = metadata.lastSync?.title;-- let shouldUpdateTitle = true;-- if (lastTitleSync) {- if (- lastTitleSync.value === issue.title &&- lastTitleSync.source === "kaneo"- ) {- console.log("Skipping title update - already synced from Kaneo");- shouldUpdateTitle = false;- }- const timeSinceLastSync =- Date.now() - new Date(lastTitleSync.timestamp ?? 0).getTime();- if (timeSinceLastSync < 2000 && shouldUpdateTitle) {- console.log(- `Skipping title update - recent sync detected (${timeSinceLastSync}ms ago)`,- );- shouldUpdateTitle = false;- }- }-- if (shouldUpdateTitle) {- updateData.title = issue.title;- updatedMetadata.lastSync.title = {- timestamp: new Date().toISOString(),- source: "github",- value: issue.title,- };- console.log(- `Updating task title from GitHub: "${changes.title.from}" → "${issue.title}"`,- );+ await withIntegrationLink(+ externalLink,+ integration,+ async (db, _afterCommit, externalLink) => {+ const task = await db.query.taskTable.findFirst({+ where: linkedTaskScope(externalLink.taskId, integration.projectId),+ });++ if (!task) {+ console.error(`Task ${externalLink.taskId} not found`);+ return;}- }- if (changes.body) {- const lastDescSync = metadata.lastSync?.description;- const formattedDescription = formatTaskDescriptionFromIssue(- issue.body,- task.id,+ const metadata = parseLinkMetadata<IssueEditedMetadata>(+ externalLink.metadata,+ {+ externalLinkId: externalLink.id,+ source: "issue_edited",+ },);- let shouldUpdateDescription = true;+ const updateData: Record<string, unknown> = {};+ const updatedMetadata: IssueEditedMetadata = { ...metadata };- if (lastDescSync) {- if (- lastDescSync.value === formattedDescription &&- lastDescSync.source === "kaneo"- ) {- console.log(- "Skipping description update - already synced from Kaneo",- );- shouldUpdateDescription = false;+ if (!updatedMetadata.lastSync) {+ updatedMetadata.lastSync = {};+ }++ if (changes.title) {+ const lastTitleSync = metadata.lastSync?.title;++ let shouldUpdateTitle = true;++ if (lastTitleSync) {+ if (+ lastTitleSync.value === issue.title &&+ lastTitleSync.source === "kaneo"+ ) {+ console.log("Skipping title update - already synced from Kaneo");+ shouldUpdateTitle = false;+ }+ const timeSinceLastSync =+ Date.now() - new Date(lastTitleSync.timestamp ?? 0).getTime();+ if (timeSinceLastSync < 2000 && shouldUpdateTitle) {+ console.log(+ `Skipping title update - recent sync detected (${timeSinceLastSync}ms ago)`,+ );+ shouldUpdateTitle = false;+ }}- const timeSinceLastSync =- Date.now() - new Date(lastDescSync.timestamp ?? 0).getTime();- if (timeSinceLastSync < 2000 && shouldUpdateDescription) {++ if (shouldUpdateTitle) {+ updateData.title = issue.title;+ updatedMetadata.lastSync.title = {+ timestamp: new Date().toISOString(),+ source: "github",+ value: issue.title,+ };console.log(- `Skipping description update - recent sync detected (${timeSinceLastSync}ms ago)`,+ `Updating task title from GitHub: "${changes.title.from}" → "${issue.title}"`,);- shouldUpdateDescription = false;}}- if (shouldUpdateDescription) {- updateData.description = formattedDescription;- updatedMetadata.lastSync.description = {- timestamp: new Date().toISOString(),- source: "github",- value: formattedDescription,- };- console.log("Updating task description from GitHub");- }- }+ if (changes.body) {+ const lastDescSync = metadata.lastSync?.description;+ const formattedDescription = formatTaskDescriptionFromIssue(+ issue.body,+ task.id,+ );- if (Object.keys(updateData).length > 0) {- await db- .update(taskTable)- .set(updateData)- .where(linkedTaskScope(task.id, integration.projectId));+ let shouldUpdateDescription = true;++ if (lastDescSync) {+ if (+ lastDescSync.value === formattedDescription &&+ lastDescSync.source === "kaneo"+ ) {+ console.log(+ "Skipping description update - already synced from Kaneo",+ );+ shouldUpdateDescription = false;+ }+ const timeSinceLastSync =+ Date.now() - new Date(lastDescSync.timestamp ?? 0).getTime();+ if (timeSinceLastSync < 2000 && shouldUpdateDescription) {+ console.log(+ `Skipping description update - recent sync detected (${timeSinceLastSync}ms ago)`,+ );+ shouldUpdateDescription = false;+ }+ }- await updateExternalLink(- externalLink.id,- {- title: issue.title,- metadata: updatedMetadata,- },- db,- );+ if (shouldUpdateDescription) {+ updateData.description = formattedDescription;+ updatedMetadata.lastSync.description = {+ timestamp: new Date().toISOString(),+ source: "github",+ value: formattedDescription,+ };+ console.log("Updating task description from GitHub");+ }+ }- console.log(- `Synced ${Object.keys(updateData).join(", ")} from GitHub issue #${issue.number} to task ${task.id}`,- );- } else {- console.log(- `No updates needed for task ${task.id} from issue #${issue.number}`,- );- }+ if (Object.keys(updateData).length > 0) {+ await db+ .update(taskTable)+ .set(updateData)+ .where(linkedTaskScope(task.id, integration.projectId));++ await updateExternalLink(+ externalLink.id,+ {+ title: issue.title,+ metadata: updatedMetadata,+ },+ db,+ );- return;- });+ console.log(+ `Synced ${Object.keys(updateData).join(", ")} from GitHub issue #${issue.number} to task ${task.id}`,+ );+ } else {+ console.log(+ `No updates needed for task ${task.id} from issue #${issue.number}`,+ );+ }++ return;+ },+ );}}diff --git a/apps/api/src/plugins/github/webhooks/issue-labeled.ts b/apps/api/src/plugins/github/webhooks/issue-labeled.tsindex 46c295a80..14a7fbe9f 100644--- a/apps/api/src/plugins/github/webhooks/issue-labeled.ts+++ b/apps/api/src/plugins/github/webhooks/issue-labeled.ts@@ -1,7 +1,5 @@-import {- linkedTaskScope,- withIntegrationTask,-} from "../services/integration-task-scope";+import { withIntegrationLink } from "../services/with-integration-link";+import { linkedTaskScope } from "../services/integration-task-scope";import { eq } from "drizzle-orm";import { labelTable, taskTable } from "../../../database/schema";import { publishEvent } from "../../../events";@@ -49,10 +47,10 @@ export async function handleIssueLabeled(payload: IssueLabeledPayload) {continue;}- await withIntegrationTask(- existingLink.taskId,+ await withIntegrationLink(+ existingLink,integration,- async (db, afterCommit) => {+ async (db, afterCommit, existingLink) => {const priority = extractIssuePriority(issue.labels);const status = extractIssueStatus(issue.labels);diff --git a/apps/api/src/plugins/github/webhooks/issue-reopened.ts b/apps/api/src/plugins/github/webhooks/issue-reopened.tsindex 11e76dbf6..ff22d069f 100644--- a/apps/api/src/plugins/github/webhooks/issue-reopened.ts+++ b/apps/api/src/plugins/github/webhooks/issue-reopened.ts@@ -1,7 +1,5 @@-import {- linkedTaskScope,- withIntegrationTask,-} from "../services/integration-task-scope";+import { withIntegrationLink } from "../services/with-integration-link";+import { linkedTaskScope } from "../services/integration-task-scope";import { and, eq } from "drizzle-orm";import db from "../../../database";import { externalLinkTable } from "../../../database/schema";@@ -49,10 +47,10 @@ export async function handleIssueReopened(payload: IssueReopenedPayload) {continue;}- await withIntegrationTask(- externalLink.taskId,+ await withIntegrationLink(+ externalLink,integration,- async (db, afterCommit) => {+ async (db, afterCommit, externalLink) => {const task = await db.query.taskTable.findFirst({where: linkedTaskScope(externalLink.taskId, integration.projectId),});diff --git a/apps/api/src/plugins/gitlab/webhooks/issue-closed.ts b/apps/api/src/plugins/gitlab/webhooks/issue-closed.tsindex ff3ae5e43..405d794f7 100644--- a/apps/api/src/plugins/gitlab/webhooks/issue-closed.ts+++ b/apps/api/src/plugins/gitlab/webhooks/issue-closed.ts@@ -1,7 +1,5 @@-import {- linkedTaskScope,- withIntegrationTask,-} from "../../github/services/integration-task-scope";+import { withIntegrationLink } from "../../github/services/with-integration-link";+import { linkedTaskScope } from "../../github/services/integration-task-scope";import { and, eq } from "drizzle-orm";import db from "../../../database";import { externalLinkTable } from "../../../database/schema";@@ -65,10 +63,10 @@ export async function handleGitlabIssueClosed(continue;}- await withIntegrationTask(- externalLink.taskId,+ await withIntegrationLink(+ externalLink,integration,- async (db, afterCommit) => {+ async (db, afterCommit, externalLink) => {const task = await db.query.taskTable.findFirst({where: linkedTaskScope(externalLink.taskId, integration.projectId),});diff --git a/apps/api/src/plugins/gitlab/webhooks/issue-reopened.ts b/apps/api/src/plugins/gitlab/webhooks/issue-reopened.tsindex 4a6bd6454..1bfc698dc 100644--- a/apps/api/src/plugins/gitlab/webhooks/issue-reopened.ts+++ b/apps/api/src/plugins/gitlab/webhooks/issue-reopened.ts@@ -1,7 +1,5 @@-import {- linkedTaskScope,- withIntegrationTask,-} from "../../github/services/integration-task-scope";+import { withIntegrationLink } from "../../github/services/with-integration-link";+import { linkedTaskScope } from "../../github/services/integration-task-scope";import { and, eq } from "drizzle-orm";import db from "../../../database";import { externalLinkTable } from "../../../database/schema";@@ -65,10 +63,10 @@ export async function handleGitlabIssueReopened(continue;}- await withIntegrationTask(- externalLink.taskId,+ await withIntegrationLink(+ externalLink,integration,- async (db, afterCommit) => {+ async (db, afterCommit, externalLink) => {const task = await db.query.taskTable.findFirst({where: linkedTaskScope(externalLink.taskId, integration.projectId),});diff --git a/apps/api/src/plugins/gitlab/webhooks/issue-updated.ts b/apps/api/src/plugins/gitlab/webhooks/issue-updated.tsindex 3954c3a4b..61860cd6d 100644--- a/apps/api/src/plugins/gitlab/webhooks/issue-updated.ts+++ b/apps/api/src/plugins/gitlab/webhooks/issue-updated.ts@@ -1,7 +1,7 @@+import { withIntegrationLink } from "../../github/services/with-integration-link";import {type IntegrationDatabase,linkedTaskScope,- withIntegrationTask,} from "../../github/services/integration-task-scope";import { eq, inArray } from "drizzle-orm";import { labelTable, taskTable } from "../../../database/schema";@@ -164,10 +164,10 @@ export async function handleGitlabIssueUpdated(continue;}- await withIntegrationTask(- externalLink.taskId,+ await withIntegrationLink(+ externalLink,integration,- async (db, afterCommit) => {+ async (db, afterCommit, externalLink) => {const task = await db.query.taskTable.findFirst({where: linkedTaskScope(externalLink.taskId, integration.projectId),with: { project: true },diff --git a/apps/api/src/plugins/gitlab/webhooks/note-created.ts b/apps/api/src/plugins/gitlab/webhooks/note-created.tsindex 8faf4a1c6..b1eb3578d 100644--- a/apps/api/src/plugins/gitlab/webhooks/note-created.ts+++ b/apps/api/src/plugins/gitlab/webhooks/note-created.ts@@ -1,4 +1,4 @@-import { withIntegrationTask } from "../../github/services/integration-task-scope";+import { withIntegrationLink } from "../../github/services/with-integration-link";import { activityTable } from "../../../database/schema";import { findExternalLink } from "../../github/services/link-manager";import { findAllIntegrationsByGitlabProject } from "../services/integration-lookup";@@ -67,32 +67,36 @@ export async function handleGitlabNoteCreated(continue;}- await withIntegrationTask(externalLink.taskId, integration, async (db) => {- if (syncedNoteIds(externalLink.metadata).includes(note.id)) {- return;- }+ await withIntegrationLink(+ externalLink,+ integration,+ async (db, _afterCommit, externalLink) => {+ if (syncedNoteIds(externalLink.metadata).includes(note.id)) {+ return;+ }- await db- .insert(activityTable)- .values({- taskId: externalLink.taskId,- type: "comment",- content: note.note,- externalUserName: username || "Unknown",- externalUserAvatar: payload.user?.avatar_url ?? null,- externalSource: "gitlab",- externalUrl: note.url,- eventData: {- externalCommentId: note.id,- },- })- .onConflictDoNothing({- target: [- activityTable.taskId,- activityTable.externalSource,- activityTable.externalUrl,- ],- });- });+ await db+ .insert(activityTable)+ .values({+ taskId: externalLink.taskId,+ type: "comment",+ content: note.note,+ externalUserName: username || "Unknown",+ externalUserAvatar: payload.user?.avatar_url ?? null,+ externalSource: "gitlab",+ externalUrl: note.url,+ eventData: {+ externalCommentId: note.id,+ },+ })+ .onConflictDoNothing({+ target: [+ activityTable.taskId,+ activityTable.externalSource,+ activityTable.externalUrl,+ ],+ });+ },+ );}}diff --git a/tests/api-integration/github-description-sync.test.ts b/tests/api-integration/github-description-sync.test.tsindex fe64b25f4..f68333206 100644--- a/tests/api-integration/github-description-sync.test.ts+++ b/tests/api-integration/github-description-sync.test.ts@@ -26,18 +26,21 @@ beforeEach(async () => {async function setup() {const { workspace } = await createWorkspaceMember();const { project } = await createProjectFixture({ workspaceId: workspace.id });- await db.insert(schema.integrationTable).values({- projectId: project.id,- type: "github",- config: JSON.stringify({- repositoryOwner: "example",- repositoryName: "repo",- installationId: 10,- repositoryId: 20,- verifiedGithubAccountId: "123",- verifiedByUserId: "user",- }),- });+ const [integration] = await db+ .insert(schema.integrationTable)+ .values({+ projectId: project.id,+ type: "github",+ config: JSON.stringify({+ repositoryOwner: "example",+ repositoryName: "repo",+ installationId: 10,+ repositoryId: 20,+ verifiedGithubAccountId: "123",+ verifiedByUserId: "user",+ }),+ })+ .returning();const [task] = await db.insert(schema.taskTable).values({@@ -47,8 +50,12 @@ async function setup() {number: 1,}).returning();- m.find.mockResolvedValue({+ const link = {id: "link",+ integrationId: integration.id,+ resourceType: "issue",+ externalId: "1",+ url: "https://github.com/example/repo/issues/1",taskId: task.id,metadata: JSON.stringify({lastSync: {@@ -59,7 +66,9 @@ async function setup() {},},}),- });+ };+ await db.insert(schema.externalLinkTable).values(link);+ m.find.mockResolvedValue(link);return task;}function webhook(body: string) {diff --git a/tests/api-integration/github-import-bounds.test.ts b/tests/api-integration/github-import-bounds.test.tsindex 57cca274a..12a107da5 100644--- a/tests/api-integration/github-import-bounds.test.ts+++ b/tests/api-integration/github-import-bounds.test.ts@@ -5,6 +5,7 @@ import { importIssues } from "../../apps/api/src/github-integration/controllers/import { withGithubImportLock } from "../../apps/api/src/github-integration/import-lock";import { IMPORT_PAGES_PER_REQUEST } from "../../apps/api/src/github-integration/import-pages";import { createApp } from "../../apps/api/src/index";+import moveTask from "../../apps/api/src/task/controllers/move-task";import { handleIssueOpened } from "../../apps/api/src/plugins/github/webhooks/issue-opened";import { mockAuthenticatedSession } from "./helpers/auth";import { resetTestDatabase } from "./helpers/database";@@ -632,3 +633,85 @@ describe("bounded resumable GitHub import", () => {).toHaveLength(25);});});++it.each(["labels", "comments"])(+ "skips unlinked GitHub %s continuation data after a task moves away and back",+ async (phase) => {+ const { project, member } = await setup();+ const { project: destination } = await createProjectFixture({+ workspaceId: project.workspaceId,+ });+ let movedTaskId: string | undefined;+ mocks.graphql.mockImplementation(async (query: string) => {+ if (query.includes("query ImportIssues("))+ return issuePage([+ issue(+ 1,+ phase === "labels"+ ? { labels: connection([label(1)], true, "first", 2) }+ : { comments: connection([comment(1)], true, "first", 2) },+ ),+ ]);+ if (+ query.includes(+ phase === "labels"+ ? "query ImportIssueLabels("+ : "query ImportIssueComments(",+ )+ ) {+ const task = await db.query.taskTable.findFirst({+ where: eq(schema.taskTable.projectId, project.id),+ });+ movedTaskId = task!.id;+ await moveTask({+ taskId: task!.id,+ destinationProjectId: destination.id,+ userId: member.user.id,+ });+ await moveTask({+ taskId: task!.id,+ destinationProjectId: project.id,+ userId: member.user.id,+ });+ return {+ repository: {+ databaseId: 2,+ issue:+ phase === "labels"+ ? {+ labels: connection([+ { name: "status:in-progress", color: "ffffff" },+ label(2),+ ]),+ }+ : { comments: connection([comment(2)]) },+ },+ };+ }+ return emptyPulls();+ });+ expect(await importIssues(project.id)).toMatchObject({+ pending: false,+ skipped: 1,+ });+ const saved = await db.query.taskTable.findFirst({+ where: eq(schema.taskTable.id, movedTaskId!),+ });+ expect(saved?.status).toBe("to-do");+ expect(+ await db.query.externalLinkTable.findMany({+ where: eq(schema.externalLinkTable.taskId, movedTaskId!),+ }),+ ).toEqual([]);+ const labels = await db.query.labelTable.findMany({+ where: eq(schema.labelTable.taskId, movedTaskId!),+ });+ expect(labels.some((row) => row.name === "label-2")).toBe(false);+ const comments = await db.query.activityTable.findMany({+ where: eq(schema.activityTable.taskId, movedTaskId!),+ });+ expect(comments.some((row) => row.externalUrl === comment(2).url)).toBe(+ false,+ );+ },+);diff --git a/tests/api-integration/integration-task-ownership.test.ts b/tests/api-integration/integration-task-ownership.test.tsindex 978d30048..5b515b38f 100644--- a/tests/api-integration/integration-task-ownership.test.ts+++ b/tests/api-integration/integration-task-ownership.test.ts@@ -413,3 +413,73 @@ it("preserves legacy links belonging to the destination integration when moving});expect(await db.query.externalLinkTable.findMany()).toEqual([compatible]);});++it.each(["edit", "labels", "comment"])(+ "ignores a stale %s webhook after its link is removed during a move and return",+ async (kind) => {+ const f = await setup();+ const transaction = getDatabase().transaction.bind(getDatabase());+ const intercepted = vi+ .spyOn(getDatabase(), "transaction")+ .mockImplementationOnce(async (apply, config) => {+ await moveTask({+ taskId: f.task.id,+ destinationProjectId: f.destination.id,+ userId: f.source.user.id,+ });+ await moveTask({+ taskId: f.task.id,+ destinationProjectId: f.project.id,+ userId: f.source.user.id,+ });+ return transaction(apply, config);+ });+ try {+ if (kind === "edit")+ await handleGiteaIssueEdited(+ {+ action: "edited",+ issue: remoteIssue,+ repository,+ changes: {+ title: { from: "Private title" },+ body: { from: "Private description" },+ },+ },+ f.integration.id,+ );+ if (kind === "labels")+ await handleGiteaIssueLabeled(+ {+ action: "labeled",+ issue: {+ number: 1,+ labels: [{ name: "priority:high" }, { name: "bug" }],+ },+ label: { name: "bug", color: "ff0000" },+ repository,+ },+ f.integration.id,+ );+ if (kind === "comment")+ await handleGiteaIssueCommentCreated(+ {+ action: "created",+ issue: { number: 1 },+ repository,+ comment: {+ id: 4,+ body: "Wrong workspace",+ html_url: `${remoteIssue.html_url}#comment-4`,+ user: { login: "author", avatar_url: "" },+ created_at: new Date().toISOString(),+ },+ },+ f.integration.id,+ );+ await expectPrivateTask(f.task.id);+ } finally {+ intercepted.mockRestore();+ }+ },+);diff --git a/tests/api/plugins/gitea/comment-sync.test.ts b/tests/api/plugins/gitea/comment-sync.test.tsindex 096ac6813..2e16fa697 100644--- a/tests/api/plugins/gitea/comment-sync.test.ts+++ b/tests/api/plugins/gitea/comment-sync.test.ts@@ -200,3 +200,26 @@ vi.mock(};},);++vi.mock(+ "../../../../apps/api/src/plugins/github/services/with-integration-link",+ async () => ({+ withIntegrationLink: async (+ link: unknown,+ integration: unknown,+ apply: (+ database: unknown,+ afterCommit: (effect: () => Promise<void>) => void,+ link: unknown,+ ) => Promise<unknown>,+ ) => {+ const { withIntegrationTask } =+ await import("../../../../apps/api/src/plugins/github/services/integration-task-scope");+ return withIntegrationTask(+ (link as { taskId: string }).taskId,+ integration as Parameters<typeof withIntegrationTask>[1],+ (database, afterCommit) => apply(database, afterCommit, link),+ );+ },+ }),+);diff --git a/tests/api/plugins/github/issue-reopened.test.ts b/tests/api/plugins/github/issue-reopened.test.tsindex e80dc3442..fde8fb304 100644--- a/tests/api/plugins/github/issue-reopened.test.ts+++ b/tests/api/plugins/github/issue-reopened.test.ts@@ -137,3 +137,26 @@ it("skips a reopen that Kaneo already applied", async () => {expect(m.update).not.toHaveBeenCalled();expect(m.status).not.toHaveBeenCalled();});++vi.mock(+ "../../../../apps/api/src/plugins/github/services/with-integration-link",+ async () => ({+ withIntegrationLink: async (+ link: unknown,+ integration: unknown,+ apply: (+ database: unknown,+ afterCommit: (effect: () => Promise<void>) => void,+ link: unknown,+ ) => Promise<unknown>,+ ) => {+ const { withIntegrationTask } =+ await import("../../../../apps/api/src/plugins/github/services/integration-task-scope");+ return withIntegrationTask(+ (link as { taskId: string }).taskId,+ integration as Parameters<typeof withIntegrationTask>[1],+ (database, afterCommit) => apply(database, afterCommit, link),+ );+ },+ }),+);diff --git a/tests/api/plugins/gitlab/webhooks/issue-reopened.test.ts b/tests/api/plugins/gitlab/webhooks/issue-reopened.test.tsindex 0ddaa8a87..a9ac8c3f3 100644--- a/tests/api/plugins/gitlab/webhooks/issue-reopened.test.ts+++ b/tests/api/plugins/gitlab/webhooks/issue-reopened.test.ts@@ -149,3 +149,26 @@ vi.mock(};},);++vi.mock(+ "../../../../../apps/api/src/plugins/github/services/with-integration-link",+ async () => ({+ withIntegrationLink: async (+ link: unknown,+ integration: unknown,+ apply: (+ database: unknown,+ afterCommit: (effect: () => Promise<void>) => void,+ link: unknown,+ ) => Promise<unknown>,+ ) => {+ const { withIntegrationTask } =+ await import("../../../../../apps/api/src/plugins/github/services/integration-task-scope");+ return withIntegrationTask(+ (link as { taskId: string }).taskId,+ integration as Parameters<typeof withIntegrationTask>[1],+ (database, afterCommit) => apply(database, afterCommit, link),+ );+ },+ }),+);diff --git a/tests/api/plugins/gitlab/webhooks/issue-updated.test.ts b/tests/api/plugins/gitlab/webhooks/issue-updated.test.tsindex 48f24e179..60ac19540 100644--- a/tests/api/plugins/gitlab/webhooks/issue-updated.test.ts+++ b/tests/api/plugins/gitlab/webhooks/issue-updated.test.ts@@ -200,3 +200,26 @@ vi.mock(};},);++vi.mock(+ "../../../../../apps/api/src/plugins/github/services/with-integration-link",+ async () => ({+ withIntegrationLink: async (+ link: unknown,+ integration: unknown,+ apply: (+ database: unknown,+ afterCommit: (effect: () => Promise<void>) => void,+ link: unknown,+ ) => Promise<unknown>,+ ) => {+ const { withIntegrationTask } =+ await import("../../../../../apps/api/src/plugins/github/services/integration-task-scope");+ return withIntegrationTask(+ (link as { taskId: string }).taskId,+ integration as Parameters<typeof withIntegrationTask>[1],+ (database, afterCommit) => apply(database, afterCommit, link),+ );+ },+ }),+);diff --git a/tests/api/plugins/gitlab/webhooks/note-created.test.ts b/tests/api/plugins/gitlab/webhooks/note-created.test.tsindex 9acd51557..996a24c68 100644--- a/tests/api/plugins/gitlab/webhooks/note-created.test.ts+++ b/tests/api/plugins/gitlab/webhooks/note-created.test.ts@@ -151,3 +151,26 @@ vi.mock(};},);++vi.mock(+ "../../../../../apps/api/src/plugins/github/services/with-integration-link",+ async () => ({+ withIntegrationLink: async (+ link: unknown,+ integration: unknown,+ apply: (+ database: unknown,+ afterCommit: (effect: () => Promise<void>) => void,+ link: unknown,+ ) => Promise<unknown>,+ ) => {+ const { withIntegrationTask } =+ await import("../../../../../apps/api/src/plugins/github/services/integration-task-scope");+ return withIntegrationTask(+ (link as { taskId: string }).taskId,+ integration as Parameters<typeof withIntegrationTask>[1],+ (database, afterCommit) => apply(database, afterCommit, link),+ );+ },+ }),+);