⚡ 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): coordinate outbound sync and retry initialization
Tin50e9340c062e
diff --git a/apps/api/src/integration-sync/controllers/preview-rules.ts b/apps/api/src/integration-sync/controllers/preview-rules.tsindex c33de9399..10856c8a8 100644--- a/apps/api/src/integration-sync/controllers/preview-rules.ts+++ b/apps/api/src/integration-sync/controllers/preview-rules.ts@@ -24,6 +24,7 @@ export async function previewSyncRules(database,);const paused = sql<boolean>`coalesce(${externalLinkTable.metadata} ~ '"syncFilterPaused"[[:space:]]*:[[:space:]]*true', false)`;+ const initializing = sql<boolean>`coalesce(${externalLinkTable.metadata} ~ '"syncInitializationPending"[[:space:]]*:[[:space:]]*true', false)`;const scope = database.$with("sync_scope").as(database.selectDistinctOn([taskTable.id], {@@ -33,6 +34,7 @@ export async function previewSyncRules(linkId: sql<string | null>`${externalLinkTable.id}`.as("link_id"),url: externalLinkTable.url,paused: paused.as("paused"),+ initializing: initializing.as("initializing"),}).from(taskTable).leftJoin(@@ -51,13 +53,13 @@ export async function previewSyncRules(.select({total: sql<number>`count(*)::int`,matching: sql<number>`count(*) filter (where ${scope.eligible})::int`,- willCreate: sql<number>`count(*) filter (where ${scope.eligible} and ${scope.linkId} is null)::int`,+ willCreate: sql<number>`count(*) filter (where ${scope.eligible} and (${scope.linkId} is null or (${scope.initializing} and not ${scope.paused})))::int`,willPause: sql<number>`count(*) filter (where ${scope.linkId} is not null and not ${scope.eligible} and not ${scope.paused})::int`,needsReview: sql<number>`count(*) filter (where ${scope.linkId} is not null and ${scope.eligible} and (${scope.paused} or not ${scope.current}))::int`,paused: sql<number>`count(*) filter (where ${scope.linkId} is not null and (not ${scope.eligible} or ${scope.paused}))::int`,// Build the ordered scope revision in PostgreSQL instead of transferring// every task/link to the API just to hash it. Page cursors do not affect it.- revision: sql<string>`md5(coalesce(string_agg(jsonb_build_array(${scope.id}, ${scope.eligible}, ${scope.current}, ${scope.linkId}, ${scope.url}, ${scope.paused})::text, ',' order by ${scope.id}), ''))`,+ revision: sql<string>`md5(coalesce(string_agg(jsonb_build_array(${scope.id}, ${scope.eligible}, ${scope.current}, ${scope.linkId}, ${scope.url}, ${scope.paused}, ${scope.initializing})::text, ',' order by ${scope.id}), ''))`,}).from(scope);const matchingTasks = await databasediff --git a/apps/api/src/plugins/gitea/events/task-comment-created.ts b/apps/api/src/plugins/gitea/events/task-comment-created.tsindex a162f3bdc..ecb0cefa3 100644--- a/apps/api/src/plugins/gitea/events/task-comment-created.ts+++ b/apps/api/src/plugins/gitea/events/task-comment-created.ts@@ -1,3 +1,4 @@+import { dispatchIssueWrite } from "../../sync/dispatch-issue-write";import { canSyncTask } from "../../sync/eligibility";import { findExternalLinkByTaskAndType } from "../../github/services/link-manager";import type { PluginContext, TaskCommentCreatedEvent } from "../../types";@@ -60,11 +61,13 @@ export async function handleTaskCommentCreated(return;}- await client.createIssueComment(- repositoryOwner,- repositoryName,- issueNumber,- markKaneoComment(event.comment),+ await dispatchIssueWrite(existingLink, JSON.stringify(context.config), () =>+ client.createIssueComment(+ repositoryOwner,+ repositoryName,+ issueNumber,+ markKaneoComment(event.comment),+ ),);} catch (error) {console.error("Failed to create Gitea comment:", error);diff --git a/apps/api/src/plugins/gitea/events/task-created.ts b/apps/api/src/plugins/gitea/events/task-created.tsindex ade9e8778..01b0654d1 100644--- a/apps/api/src/plugins/gitea/events/task-created.ts+++ b/apps/api/src/plugins/gitea/events/task-created.ts@@ -1,5 +1,8 @@+import {+ initializeTaskIssue,+ isIssueInitializationPending,+} from "../../sync/initialize-task-issue";import { canSyncTask } from "../../sync/eligibility";-import { taskIssueLabels } from "../../sync/issue-labels";import { withTaskSyncCreation } from "../../sync/create-task-issue";import {createExternalLink,@@ -7,7 +10,6 @@ import {findExternalLinkByTaskAndType,} from "../../github/services/link-manager";import { formatIssueBody, formatIssueTitle } from "../../github/utils/format";-import { isTaskInFinalState } from "../../github/services/task-service";import type { PluginContext, TaskCreatedEvent } from "../../types";import type { GiteaConfig } from "../config";import { createGiteaClient } from "../utils/gitea-api";@@ -30,9 +32,7 @@ async function createTaskIssue("issue",);- if (existingLink) {- return;- }+ if (existingLink && !isIssueInitializationPending(existingLink)) return;try {const client = createGiteaClient(config);@@ -46,28 +46,36 @@ async function createTaskIssue()return;- const createdIssue = await client.createIssue(- repositoryOwner,- repositoryName,- {- title: formatIssueTitle(event.title),- body: formatIssueBody(event.description, event.taskId),- },- );+ let createdLink: { id: string; metadata?: string | null } | undefined =+ existingLink;+ let issueNumber = existingLink ? Number(existingLink.externalId) : 0;+ if (!existingLink) {+ const createdIssue = await client.createIssue(+ repositoryOwner,+ repositoryName,+ {+ title: formatIssueTitle(event.title),+ body: formatIssueBody(event.description, event.taskId),+ },+ );- const createdLink = await createExternalLink({- taskId: event.taskId,- integrationId: context.integrationId,- resourceType: "issue",- externalId: createdIssue.number.toString(),- url: createdIssue.html_url,- title: createdIssue.title,- metadata: {- state: createdIssue.state,- createdFrom: "kaneo",- lastOutboundStateSyncAt: Date.now(),- },- });+ createdLink = await createExternalLink({+ taskId: event.taskId,+ integrationId: context.integrationId,+ resourceType: "issue",+ externalId: createdIssue.number.toString(),+ url: createdIssue.html_url,+ title: createdIssue.title,+ metadata: {+ state: createdIssue.state,+ createdFrom: "kaneo",+ syncInitializationPending: true,+ lastOutboundStateSyncAt: Date.now(),+ },+ });+ issueNumber = createdIssue.number;+ }+ if (!createdLink) return;if (!(await canSyncTask(@@ -83,30 +91,14 @@ async function createTaskIssue(return;}- if (- await isTaskInFinalState({- projectId: event.projectId,- status: event.status,- columnId: null,- })- ) {- await client.updateIssue(- repositoryOwner,- repositoryName,- createdIssue.number,- { state: "closed" },- );- await updateExternalLink(createdLink.id, {- metadata: { state: "closed", lastOutboundStateSyncAt: Date.now() },- });- }-- const labels = await taskIssueLabels(- event.taskId,- event.priority,- event.status,- );- await addLabelsToIssueGitea(config, createdIssue.number, labels);+ await initializeTaskIssue(event, context, createdLink, {+ close: () =>+ client.updateIssue(repositoryOwner, repositoryName, issueNumber, {+ state: "closed",+ }),+ labels: (labels, write) =>+ addLabelsToIssueGitea(config, issueNumber, labels, true, write),+ });} catch (error) {console.error("Failed to create Gitea issue:", error);}diff --git a/apps/api/src/plugins/gitea/events/task-priority-changed.ts b/apps/api/src/plugins/gitea/events/task-priority-changed.tsindex 946a71be1..7cd8cdf19 100644--- a/apps/api/src/plugins/gitea/events/task-priority-changed.ts+++ b/apps/api/src/plugins/gitea/events/task-priority-changed.ts@@ -1,3 +1,4 @@+import { createIssueWrite } from "../../sync/dispatch-issue-write";import { canSyncTask } from "../../sync/eligibility";import { findExternalLinksByTask } from "../../github/services/link-manager";import type { PluginContext, TaskPriorityChangedEvent } from "../../types";@@ -34,6 +35,10 @@ 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);@@ -42,13 +47,18 @@ export async function handleTaskPriorityChanged(config,issueNumber,`priority:${event.oldPriority}`,+ write,);}if (event.newPriority && event.newPriority !== "no-priority") {- await addLabelsToIssueGitea(config, issueNumber, [- `priority:${event.newPriority}`,- ]);+ await addLabelsToIssueGitea(+ config,+ issueNumber,+ [`priority:${event.newPriority}`],+ false,+ 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 9f6b017c4..b1d68b500 100644--- a/apps/api/src/plugins/gitea/events/task-status-changed.ts+++ b/apps/api/src/plugins/gitea/events/task-status-changed.ts@@ -1,3 +1,4 @@+import { createIssueWrite } from "../../sync/dispatch-issue-write";import { canSyncTask } from "../../sync/eligibility";import { syncLatestTaskValue } from "../../github/services/sync-latest-task-value";import { findExternalLinksByTask } from "../../github/services/link-manager";@@ -38,15 +39,28 @@ 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}`);+ await removeLabelGitea(+ config,+ issueNumber,+ `status:${event.oldStatus}`,+ write,+ );- await addLabelsToIssueGitea(config, issueNumber, [- `status:${event.newStatus}`,- ]);+ await addLabelsToIssueGitea(+ config,+ issueNumber,+ [`status:${event.newStatus}`],+ false,+ write,+ );if (event.newStatus === "done" || event.oldStatus === "done") {await syncLatestTaskValue(diff --git a/apps/api/src/plugins/gitea/utils/labels.ts b/apps/api/src/plugins/gitea/utils/labels.tsindex fdf60e119..9bac9da17 100644--- a/apps/api/src/plugins/gitea/utils/labels.ts+++ b/apps/api/src/plugins/gitea/utils/labels.ts@@ -1,3 +1,4 @@+import type { IssueWrite } from "../../sync/issue-write";import type { GiteaConfig } from "../config";import { createGiteaClient, type GiteaLabel } from "./gitea-api";@@ -21,6 +22,7 @@ function getLabelColor(labelName: string): string {export async function ensureLabelsExistGitea(config: GiteaConfig,labels: string[],+ requireSuccess = false,): Promise<Map<string, number>> {const client = createGiteaClient(config);const map = new Map<string, number>();@@ -30,6 +32,7 @@ export async function ensureLabelsExistGitea(try {existingLabels = await client.listLabels(repositoryOwner, repositoryName);} catch (error) {+ if (requireSuccess) throw error;console.error("Failed to list Gitea labels for ensureLabelsExistGitea", {repositoryOwner,repositoryName,@@ -58,6 +61,7 @@ export async function ensureLabelsExistGitea(nameToId.set(name, created.id);map.set(name, created.id);} catch (error) {+ if (requireSuccess) throw error;console.error(`Failed to ensure Gitea label "${name}":`, error);}}@@ -68,10 +72,16 @@ export async function addLabelsToIssueGitea(config: GiteaConfig,issueIndex: number,labelNames: string[],+ requireSuccess = false,+ write: IssueWrite = (send) => send(),) {if (labelNames.length === 0) return;- const nameToId = await ensureLabelsExistGitea(config, labelNames);+ const nameToId = await ensureLabelsExistGitea(+ config,+ labelNames,+ requireSuccess,+ );const ids: number[] = [];for (const name of labelNames) {const id = nameToId.get(name);@@ -85,13 +95,16 @@ export async function addLabelsToIssueGitea(const client = createGiteaClient(config);try {- await client.addLabelsToIssue(- config.repositoryOwner,- config.repositoryName,- issueIndex,- ids,+ await write(() =>+ client.addLabelsToIssue(+ config.repositoryOwner,+ config.repositoryName,+ issueIndex,+ ids,+ ),);} catch (error) {+ if (requireSuccess) throw error;console.error("Failed to add labels to Gitea issue:", error);}}@@ -100,6 +113,7 @@ export async function removeLabelGitea(config: GiteaConfig,issueIndex: number,labelName: string,+ write: IssueWrite = (send) => send(),) {const client = createGiteaClient(config);let labels: GiteaLabel[];@@ -123,11 +137,13 @@ export async function removeLabelGitea(if (!label) return;try {- await client.removeLabelFromIssue(- config.repositoryOwner,- config.repositoryName,- issueIndex,- label.id,+ await write(() =>+ client.removeLabelFromIssue(+ config.repositoryOwner,+ config.repositoryName,+ issueIndex,+ label.id,+ ),);} catch (error) {console.error("Failed to remove label from Gitea issue:", {diff --git a/apps/api/src/plugins/github/events/task-comment-created.ts b/apps/api/src/plugins/github/events/task-comment-created.tsindex 3f5da7497..e580e299c 100644--- a/apps/api/src/plugins/github/events/task-comment-created.ts+++ b/apps/api/src/plugins/github/events/task-comment-created.ts@@ -1,3 +1,4 @@+import { dispatchIssueWrite } from "../../sync/dispatch-issue-write";import { canSyncTask } from "../../sync/eligibility";import type { PluginContext, TaskCommentCreatedEvent } from "../../types";import { type GitHubConfig, hasVerifiedGitHubBinding } from "../config";@@ -45,12 +46,14 @@ export async function handleTaskCommentCreated(const issueNumber = Number.parseInt(existingLink.externalId, 10);- await octokit.rest.issues.createComment({- owner: repositoryOwner,- repo: repositoryName,- issue_number: issueNumber,- body: event.comment,- });+ await dispatchIssueWrite(existingLink, JSON.stringify(context.config), () =>+ octokit.rest.issues.createComment({+ owner: repositoryOwner,+ repo: repositoryName,+ issue_number: issueNumber,+ body: event.comment,+ }),+ );} catch (error) {console.error("Failed to create GitHub comment:", error);}diff --git a/apps/api/src/plugins/github/events/task-created.ts b/apps/api/src/plugins/github/events/task-created.tsindex b0f989b22..ccff5f4e9 100644--- a/apps/api/src/plugins/github/events/task-created.ts+++ b/apps/api/src/plugins/github/events/task-created.ts@@ -1,10 +1,12 @@+import {+ initializeTaskIssue,+ isIssueInitializationPending,+} from "../../sync/initialize-task-issue";import { canSyncTask } from "../../sync/eligibility";-import { taskIssueLabels } from "../../sync/issue-labels";import { withTaskSyncCreation } from "../../sync/create-task-issue";import { eq } from "drizzle-orm";import db from "../../../database";import { projectTable } from "../../../database/schema";-import { isTaskInFinalState } from "../services/task-service";import type { PluginContext, TaskCreatedEvent } from "../../types";import { type GitHubConfig, hasVerifiedGitHubBinding } from "../config";import {@@ -38,12 +40,10 @@ async function createTaskIssue("issue",);- if (existingLink) {- return;- }+ if (existingLink && !isIssueInitializationPending(existingLink)) return;try {- const octokit = await getVerifiedInstallationOctokit(config);+ const octokit = await getVerifiedInstallationOctokit(config, true);if (!(await canSyncTask(@@ -55,25 +55,33 @@ async function createTaskIssue()return;- const createdIssue = await octokit.rest.issues.create({- owner: repositoryOwner,- repo: repositoryName,- title: formatIssueTitle(event.title),- body: formatIssueBody(event.description, event.taskId),- });+ let createdLink: { id: string; metadata?: string | null } | undefined =+ existingLink;+ let issueNumber = existingLink ? Number(existingLink.externalId) : 0;+ if (!existingLink) {+ const createdIssue = await octokit.rest.issues.create({+ owner: repositoryOwner,+ repo: repositoryName,+ title: formatIssueTitle(event.title),+ body: formatIssueBody(event.description, event.taskId),+ });- const createdLink = await createExternalLink({- taskId: event.taskId,- integrationId: context.integrationId,- resourceType: "issue",- externalId: createdIssue.data.number.toString(),- url: createdIssue.data.html_url,- title: createdIssue.data.title,- metadata: {- state: createdIssue.data.state,- createdFrom: "kaneo",- },- });+ createdLink = await createExternalLink({+ taskId: event.taskId,+ integrationId: context.integrationId,+ resourceType: "issue",+ externalId: createdIssue.data.number.toString(),+ url: createdIssue.data.html_url,+ title: createdIssue.data.title,+ metadata: {+ state: createdIssue.data.state,+ createdFrom: "kaneo",+ syncInitializationPending: true,+ },+ });+ issueNumber = createdIssue.data.number;+ }+ if (!createdLink) return;if (!(await canSyncTask(@@ -89,56 +97,48 @@ async function createTaskIssue(return;}- if (- await isTaskInFinalState({- projectId: event.projectId,- status: event.status,- columnId: null,- })- ) {- await octokit.rest.issues.update({- owner: repositoryOwner,- repo: repositoryName,- issue_number: createdIssue.data.number,- state: "closed",- });- await updateExternalLink(createdLink.id, {- metadata: { state: "closed", lastOutboundStateSyncAt: Date.now() },- });- }-- const labels = await taskIssueLabels(- event.taskId,- event.priority,- event.status,- );- await addLabelsToIssue(- octokit,- repositoryOwner,- repositoryName,- createdIssue.data.number,- labels,- );-+ let comment: string | undefined;if (config.commentTaskLinkOnGitHubIssue !== false) {const project = await db.query.projectTable.findFirst({where: eq(projectTable.id, event.projectId),});-if (project) {const clientUrl =process.env.KANEO_CLIENT_URL || "http://localhost:5173";const taskUrl = `${clientUrl}/dashboard/workspace/${project.workspaceId}/project/${event.projectId}/task/${event.taskId}`;- const taskIdentifier = `${project.slug.toUpperCase()}-${event.number}`;-- await octokit.rest.issues.createComment({- owner: repositoryOwner,- repo: repositoryName,- issue_number: createdIssue.data.number,- body: `[${taskIdentifier}](${taskUrl})`,- });+ comment = `[${project.slug.toUpperCase()}-${event.number}](${taskUrl})`;}}+ await initializeTaskIssue(event, context, createdLink, {+ close: () =>+ octokit.rest.issues.update({+ owner: repositoryOwner,+ repo: repositoryName,+ issue_number: issueNumber,+ state: "closed",+ }),+ labels: (labels, write) =>+ addLabelsToIssue(+ octokit,+ repositoryOwner,+ repositoryName,+ issueNumber,+ labels,+ true,+ write,+ ),+ ...(comment+ ? {+ comment: () =>+ octokit.rest.issues.createComment({+ owner: repositoryOwner,+ repo: repositoryName,+ issue_number: issueNumber,+ body: comment!,+ }),+ }+ : {}),+ });} catch (error) {console.error("Failed to create GitHub issue:", error);}diff --git a/apps/api/src/plugins/github/events/task-priority-changed.ts b/apps/api/src/plugins/github/events/task-priority-changed.tsindex 904d249be..00f14b522 100644--- a/apps/api/src/plugins/github/events/task-priority-changed.ts+++ b/apps/api/src/plugins/github/events/task-priority-changed.ts@@ -1,3 +1,4 @@+import { createIssueWrite } from "../../sync/dispatch-issue-write";import { canSyncTask } from "../../sync/eligibility";import type { PluginContext, TaskPriorityChangedEvent } from "../../types";import { type GitHubConfig, hasVerifiedGitHubBinding } from "../config";@@ -42,6 +43,10 @@ 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);@@ -53,6 +58,7 @@ export async function handleTaskPriorityChanged(repositoryName,issueNumber,`priority:${event.oldPriority}`,+ write,);}@@ -63,6 +69,8 @@ export async function handleTaskPriorityChanged(repositoryName,issueNumber,[`priority:${event.newPriority}`],+ false,+ write,);}} catch (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 7e9a773c4..5ab678df3 100644--- a/apps/api/src/plugins/github/events/task-status-changed.ts+++ b/apps/api/src/plugins/github/events/task-status-changed.ts@@ -1,3 +1,4 @@+import { createIssueWrite } from "../../sync/dispatch-issue-write";import { canSyncTask } from "../../sync/eligibility";import { syncLatestTaskValue } from "../services/sync-latest-task-value";import type { PluginContext, TaskStatusChangedEvent } from "../../types";@@ -43,6 +44,10 @@ 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);@@ -53,6 +58,7 @@ export async function handleTaskStatusChanged(repositoryName,issueNumber,`status:${event.oldStatus}`,+ write,);await addLabelsToIssue(@@ -61,6 +67,8 @@ export async function handleTaskStatusChanged(repositoryName,issueNumber,[`status:${event.newStatus}`],+ false,+ write,);if (event.newStatus === "done" || event.oldStatus === "done") {diff --git a/apps/api/src/plugins/github/services/sync-latest-task-value.ts b/apps/api/src/plugins/github/services/sync-latest-task-value.tsindex 0e65f6766..b13b7fa98 100644--- a/apps/api/src/plugins/github/services/sync-latest-task-value.ts+++ b/apps/api/src/plugins/github/services/sync-latest-task-value.ts@@ -1,3 +1,4 @@+import { dispatchIssueWrite } from "../../sync/dispatch-issue-write";import { canSyncTask } from "../../sync/eligibility";import { deferTaskSync } from "./defer-issue-edit";import { randomUUID } from "node:crypto";@@ -97,7 +98,25 @@ export async function syncLatestTaskValue(if (persisted === false || !(await currentBinding())) return;let updatedAt: string | undefined;try {- updatedAt = await write(value);+ const dispatched = await dispatchIssueWrite(+ { ...link, taskId },+ identity?.config,+ () => write(value),+ );+ if (!dispatched) {+ await updateExternalLink(link.id, {+ outbound: {+ field,+ value,+ intentId,+ pending: false,+ cancelled: true,+ uncertain: false,+ },+ });+ return;+ }+ updatedAt = dispatched.value;attempts++;} catch (error) {const status =diff --git a/apps/api/src/plugins/github/utils/labels.ts b/apps/api/src/plugins/github/utils/labels.tsindex 91166d192..131df9d34 100644--- a/apps/api/src/plugins/github/utils/labels.ts+++ b/apps/api/src/plugins/github/utils/labels.ts@@ -1,3 +1,4 @@+import type { IssueWrite } from "../../sync/issue-write";import type { Octokit } from "octokit";const labelColors: Record<string, string> = {@@ -22,6 +23,7 @@ export async function ensureLabelsExist(owner: string,repo: string,labels: string[],+ requireSuccess = false,) {for (const labelName of labels) {try {@@ -40,6 +42,7 @@ export async function ensureLabelsExist(color,});} catch (createError) {+ if (requireSuccess) throw createError;console.error(`Failed to create label "${labelName}":`, createError);}}@@ -52,17 +55,22 @@ export async function addLabelsToIssue(repo: string,issueNumber: number,labels: string[],+ requireSuccess = false,+ write: IssueWrite = (send) => send(),) {try {- await ensureLabelsExist(octokit, owner, repo, labels);+ await ensureLabelsExist(octokit, owner, repo, labels, requireSuccess);- await octokit.rest.issues.addLabels({- owner,- repo,- issue_number: issueNumber,- labels,- });+ await write(() =>+ octokit.rest.issues.addLabels({+ owner,+ repo,+ issue_number: issueNumber,+ labels,+ }),+ );} catch (error) {+ if (requireSuccess) throw error;console.error("Failed to add labels to issue:", error);}}@@ -73,14 +81,17 @@ export async function removeLabel(repo: string,issueNumber: number,labelName: string,+ write: IssueWrite = (send) => send(),) {try {- await octokit.rest.issues.removeLabel({- owner,- repo,- issue_number: issueNumber,- name: labelName,- });+ await write(() =>+ octokit.rest.issues.removeLabel({+ owner,+ repo,+ issue_number: issueNumber,+ name: labelName,+ }),+ );} catch (error) {if (typeof error === "object" &&diff --git a/apps/api/src/plugins/gitlab/events/task-comment-created.ts b/apps/api/src/plugins/gitlab/events/task-comment-created.tsindex 3e30d2c25..f125d4ee7 100644--- a/apps/api/src/plugins/gitlab/events/task-comment-created.ts+++ b/apps/api/src/plugins/gitlab/events/task-comment-created.ts@@ -1,3 +1,4 @@+import { dispatchIssueWrite } from "../../sync/dispatch-issue-write";import { canSyncTask } from "../../sync/eligibility";import {findExternalLinkByTaskAndType,@@ -60,11 +61,18 @@ export async function handleTaskCommentCreated(}try {- const note = await createGitlabClient(config).createIssueNote(- config.projectPath,- issueIid,- event.comment,+ const dispatched = await dispatchIssueWrite(+ existingLink,+ JSON.stringify(context.config),+ () =>+ createGitlabClient(config).createIssueNote(+ config.projectPath,+ issueIid,+ event.comment,+ ),);+ if (!dispatched) return;+ const note = dispatched.value;const metadata = parseLinkSyncMetadata(existingLink.metadata, {externalLinkId: existingLink.id,diff --git a/apps/api/src/plugins/gitlab/events/task-created.ts b/apps/api/src/plugins/gitlab/events/task-created.tsindex 6474e6aa5..6a4c9352e 100644--- a/apps/api/src/plugins/gitlab/events/task-created.ts+++ b/apps/api/src/plugins/gitlab/events/task-created.ts@@ -1,5 +1,8 @@+import {+ initializeTaskIssue,+ isIssueInitializationPending,+} from "../../sync/initialize-task-issue";import { canSyncTask } from "../../sync/eligibility";-import { taskIssueLabels } from "../../sync/issue-labels";import { withTaskSyncCreation } from "../../sync/create-task-issue";import {createExternalLink,@@ -7,7 +10,6 @@ import {findExternalLinkByTaskAndType,} from "../../github/services/link-manager";import { formatIssueBody, formatIssueTitle } from "../../github/utils/format";-import { isTaskInFinalState } from "../../github/services/task-service";import type { PluginContext, TaskCreatedEvent } from "../../types";import type { GitlabConfig } from "../config";import { createGitlabClient } from "../utils/gitlab-api";@@ -28,9 +30,7 @@ async function createTaskIssue("issue",);- if (existingLink) {- return;- }+ if (existingLink && !isIssueInitializationPending(existingLink)) return;try {const client = createGitlabClient(config);@@ -44,24 +44,32 @@ async function createTaskIssue()return;- const createdIssue = await client.createIssue(config.projectPath, {- title: formatIssueTitle(event.title),- description: formatIssueBody(event.description, event.taskId),- });+ let createdLink: { id: string; metadata?: string | null } | undefined =+ existingLink;+ let issueNumber = existingLink ? Number(existingLink.externalId) : 0;+ if (!existingLink) {+ const createdIssue = await client.createIssue(config.projectPath, {+ title: formatIssueTitle(event.title),+ description: formatIssueBody(event.description, event.taskId),+ });- const createdLink = await createExternalLink({- taskId: event.taskId,- integrationId: context.integrationId,- resourceType: "issue",- externalId: createdIssue.iid.toString(),- url: createdIssue.web_url,- title: createdIssue.title,- metadata: {- state: createdIssue.state,- createdFrom: "kaneo",- lastOutboundStateSyncAt: Date.now(),- },- });+ createdLink = await createExternalLink({+ taskId: event.taskId,+ integrationId: context.integrationId,+ resourceType: "issue",+ externalId: createdIssue.iid.toString(),+ url: createdIssue.web_url,+ title: createdIssue.title,+ metadata: {+ state: createdIssue.state,+ createdFrom: "kaneo",+ syncInitializationPending: true,+ lastOutboundStateSyncAt: Date.now(),+ },+ });+ issueNumber = createdIssue.iid;+ }+ if (!createdLink) return;if (!(await canSyncTask(@@ -77,26 +85,14 @@ async function createTaskIssue(return;}- if (- await isTaskInFinalState({- projectId: event.projectId,- status: event.status,- columnId: null,- })- ) {- await client.updateIssue(config.projectPath, createdIssue.iid, {- state_event: "close",- });- await updateExternalLink(createdLink.id, {- metadata: { state: "closed", lastOutboundStateSyncAt: Date.now() },- });- }-- await addLabelsToIssueGitlab(- config,- createdIssue.iid,- await taskIssueLabels(event.taskId, event.priority, event.status),- );+ await initializeTaskIssue(event, context, createdLink, {+ close: () =>+ client.updateIssue(config.projectPath, issueNumber, {+ state_event: "close",+ }),+ labels: (labels, write) =>+ addLabelsToIssueGitlab(config, issueNumber, labels, true, write),+ });} catch (error) {console.error("Failed to create GitLab issue:", error);}diff --git a/apps/api/src/plugins/gitlab/events/task-description-changed.ts b/apps/api/src/plugins/gitlab/events/task-description-changed.tsindex 254381a8a..a8eec5267 100644--- a/apps/api/src/plugins/gitlab/events/task-description-changed.ts+++ b/apps/api/src/plugins/gitlab/events/task-description-changed.ts@@ -1,3 +1,4 @@+import { createIssueWrite } from "../../sync/dispatch-issue-write";import { canSyncTask } from "../../sync/eligibility";import {findExternalLinksByTask,@@ -43,6 +44,10 @@ export async function handleTaskDescriptionChanged(if (!issueLink) {return;}+ const write = createIssueWrite(+ { ...issueLink, taskId: event.taskId },+ JSON.stringify(context.config),+ );const metadata = parseLinkSyncMetadata(issueLink.metadata, {externalLinkId: issueLink.id,@@ -66,9 +71,11 @@ export async function handleTaskDescriptionChanged(const issueDescription = formatIssueBody(newDescription, event.taskId);- await createGitlabClient(config).updateIssue(config.projectPath, issueIid, {- description: issueDescription,- });+ await write(() =>+ createGitlabClient(config).updateIssue(config.projectPath, issueIid, {+ description: issueDescription,+ }),+ );await updateExternalLink(issueLink.id, {metadata: withLastSync(diff --git a/apps/api/src/plugins/gitlab/events/task-priority-changed.ts b/apps/api/src/plugins/gitlab/events/task-priority-changed.tsindex 403a8c14c..ddba938e6 100644--- a/apps/api/src/plugins/gitlab/events/task-priority-changed.ts+++ b/apps/api/src/plugins/gitlab/events/task-priority-changed.ts@@ -1,3 +1,4 @@+import { createIssueWrite } from "../../sync/dispatch-issue-write";import { canSyncTask } from "../../sync/eligibility";import { findExternalLinksByTask } from "../../github/services/link-manager";import type { PluginContext, TaskPriorityChangedEvent } from "../../types";@@ -34,6 +35,10 @@ 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)) {@@ -49,7 +54,13 @@ export async function handleTaskPriorityChanged(? [`priority:${event.newPriority}`]: [];- await updateIssueLabelsGitlab(config, issueIid, { add, remove });+ await updateIssueLabelsGitlab(+ config,+ issueIid,+ { add, remove },+ false,+ 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 babb9c40c..7b7267889 100644--- a/apps/api/src/plugins/gitlab/events/task-status-changed.ts+++ b/apps/api/src/plugins/gitlab/events/task-status-changed.ts@@ -1,3 +1,4 @@+import { createIssueWrite } from "../../sync/dispatch-issue-write";import { canSyncTask } from "../../sync/eligibility";import {findExternalLinksByTask,@@ -43,6 +44,10 @@ 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)) {@@ -53,10 +58,16 @@ export async function handleTaskStatusChanged(return;}- await updateIssueLabelsGitlab(config, issueIid, {- remove: [`status:${event.oldStatus}`],- add: [`status:${event.newStatus}`],- });+ await updateIssueLabelsGitlab(+ config,+ issueIid,+ {+ remove: [`status:${event.oldStatus}`],+ add: [`status:${event.newStatus}`],+ },+ false,+ write,+ );const closing = event.newStatus === "done";const reopening = event.oldStatus === "done" && event.newStatus !== "done";@@ -65,9 +76,11 @@ export async function handleTaskStatusChanged(return;}- await createGitlabClient(config).updateIssue(config.projectPath, issueIid, {- state_event: closing ? "close" : "reopen",- });+ await write(() =>+ createGitlabClient(config).updateIssue(config.projectPath, issueIid, {+ state_event: closing ? "close" : "reopen",+ }),+ );await updateExternalLink(issueLink.id, {metadata: {diff --git a/apps/api/src/plugins/gitlab/events/task-title-changed.ts b/apps/api/src/plugins/gitlab/events/task-title-changed.tsindex e1f4feb2e..1067a37f5 100644--- a/apps/api/src/plugins/gitlab/events/task-title-changed.ts+++ b/apps/api/src/plugins/gitlab/events/task-title-changed.ts@@ -1,3 +1,4 @@+import { createIssueWrite } from "../../sync/dispatch-issue-write";import { canSyncTask } from "../../sync/eligibility";import {findExternalLinksByTask,@@ -42,6 +43,10 @@ export async function handleTaskTitleChanged(if (!issueLink) {return;}+ const write = createIssueWrite(+ { ...issueLink, taskId: event.taskId },+ JSON.stringify(context.config),+ );const metadata = parseLinkSyncMetadata(issueLink.metadata, {externalLinkId: issueLink.id,@@ -61,9 +66,11 @@ export async function handleTaskTitleChanged(return;}- await createGitlabClient(config).updateIssue(config.projectPath, issueIid, {- title: event.newTitle,- });+ await write(() =>+ createGitlabClient(config).updateIssue(config.projectPath, issueIid, {+ title: event.newTitle,+ }),+ );await updateExternalLink(issueLink.id, {title: event.newTitle,diff --git a/apps/api/src/plugins/gitlab/utils/labels.ts b/apps/api/src/plugins/gitlab/utils/labels.tsindex 84fc1138c..480b36c55 100644--- a/apps/api/src/plugins/gitlab/utils/labels.ts+++ b/apps/api/src/plugins/gitlab/utils/labels.ts@@ -1,3 +1,4 @@+import type { IssueWrite } from "../../sync/issue-write";import type { GitlabConfig } from "../config";import { createGitlabClient } from "./gitlab-api";@@ -22,6 +23,7 @@ function getLabelColor(labelName: string): string {export async function ensureLabelsExistGitlab(config: GitlabConfig,labels: string[],+ requireSuccess = false,): Promise<void> {if (labels.length === 0) return;@@ -32,6 +34,7 @@ export async function ensureLabelsExistGitlab(try {existing = (await client.listLabels(projectPath)).map((l) => l.name);} catch (error) {+ if (requireSuccess) throw error;console.error("Failed to list GitLab labels for ensureLabelsExistGitlab", {projectPath,error,@@ -45,6 +48,7 @@ export async function ensureLabelsExistGitlab(try {await client.createLabel(projectPath, name, getLabelColor(name));} catch (error) {+ if (requireSuccess) throw error;console.error(`Failed to ensure GitLab label "${name}":`, error);}}@@ -55,6 +59,8 @@ export async function updateIssueLabelsGitlab(config: GitlabConfig,issueIid: number,changes: { add?: string[]; remove?: string[] },+ requireSuccess = false,+ write: IssueWrite = (send) => send(),) {const add = changes.add ?? [];// GitLab removes a label when it appears in both lists. Reapplying a@@ -63,7 +69,7 @@ export async function updateIssueLabelsGitlab(if (add.length === 0 && remove.length === 0) return;- await ensureLabelsExistGitlab(config, add);+ await ensureLabelsExistGitlab(config, add, requireSuccess);const body: Record<string, string> = {};if (add.length > 0) {@@ -74,12 +80,15 @@ export async function updateIssueLabelsGitlab(}try {- await createGitlabClient(config).updateIssue(- config.projectPath,- issueIid,- body,+ await write(() =>+ createGitlabClient(config).updateIssue(+ config.projectPath,+ issueIid,+ body,+ ),);} catch (error) {+ if (requireSuccess) throw error;console.error("Failed to update GitLab issue labels:", {projectPath: config.projectPath,issueIid,@@ -92,8 +101,16 @@ export async function addLabelsToIssueGitlab(config: GitlabConfig,issueIid: number,labelNames: string[],+ requireSuccess = false,+ write: IssueWrite = (send) => send(),) {- await updateIssueLabelsGitlab(config, issueIid, { add: labelNames });+ await updateIssueLabelsGitlab(+ config,+ issueIid,+ { add: labelNames },+ requireSuccess,+ write,+ );}export async function removeLabelGitlab(diff --git a/apps/api/src/plugins/sync/create-task-issue.ts b/apps/api/src/plugins/sync/create-task-issue.tsindex 129f24276..8469126f4 100644--- a/apps/api/src/plugins/sync/create-task-issue.ts+++ b/apps/api/src/plugins/sync/create-task-issue.ts@@ -3,6 +3,7 @@ import db from "../../database";import { externalLinkTable, taskTable } from "../../database/schema";import type { PluginContext, TaskCreatedEvent } from "../types";import { canSyncTask } from "./eligibility";+import { isIssueInitializationPending } from "./initialize-task-issue";import { withSyncLease } from "./lease";export async function withTaskSyncCreation(@@ -29,17 +30,14 @@ async function createWithLease()))return;- if (- await db.query.externalLinkTable.findFirst({- where: and(- eq(externalLinkTable.taskId, event.taskId),- eq(externalLinkTable.integrationId, context.integrationId),- eq(externalLinkTable.resourceType, "issue"),- ),- columns: { id: true },- })- )- return;+ const link = await db.query.externalLinkTable.findFirst({+ where: and(+ eq(externalLinkTable.taskId, event.taskId),+ eq(externalLinkTable.integrationId, context.integrationId),+ eq(externalLinkTable.resourceType, "issue"),+ ),+ });+ if (link && !isIssueInitializationPending(link)) return;const task = await db.query.taskTable.findFirst({where: and(eq(taskTable.id, event.taskId),diff --git a/apps/api/src/plugins/sync/dispatch-issue-write.ts b/apps/api/src/plugins/sync/dispatch-issue-write.tsnew file mode 100644index 000000000..3e3270d1c--- /dev/null+++ b/apps/api/src/plugins/sync/dispatch-issue-write.ts@@ -0,0 +1,78 @@+import type { IssueWrite } from "./issue-write";+import { and, eq, inArray, isNull, or } from "drizzle-orm";+import db from "../../database";+import { labelTable } from "../../database/schema";+import { withIntegrationLink } from "../github/services/with-integration-link";+import { canSyncTask } from "./eligibility";+import { readSyncRules } from "./rules";+import { sameConfig } from "./same-config";++export async function dispatchIssueWrite<T>(+ link: { id: string; taskId: string; integrationId: string | null },+ expectedConfig: string | undefined,+ send: () => Promise<T>,+): Promise<{ value: T } | undefined> {+ if (!link.integrationId) return;+ const integration = await db.query.integrationTable.findFirst({+ where: (table, { eq }) => eq(table.id, link.integrationId!),+ with: { project: true },+ });+ if (!integration) return;+ let request: Promise<{ value: T } | { error: unknown }> | undefined;+ await withIntegrationLink(+ link,+ integration,+ async (tx) => {+ const rule = readSyncRules(integration.config)?.outgoing;+ if (rule?.mode === "labels") {+ await tx+ .select({ id: labelTable.id })+ .from(labelTable)+ .where(+ and(+ eq(labelTable.workspaceId, integration.project.workspaceId),+ or(+ and(+ isNull(labelTable.taskId),+ inArray(labelTable.id, rule.labels),+ ),+ eq(labelTable.taskId, link.taskId),+ ),+ ),+ )+ .orderBy(labelTable.id)+ .for("share");+ }+ if (!(await canSyncTask(link.taskId, integration.id, tx, expectedConfig)))+ return;+ // Start the request while pause/rule/label writes are excluded. Settle it+ // after commit so provider latency never holds these row locks.+ request = send().then(+ (value) => ({ value }),+ (error: unknown) => ({ error }),+ );+ },+ {+ type: integration.type,+ validate: (binding) =>+ sameConfig(binding.config, integration.config) &&+ (expectedConfig === undefined ||+ sameConfig(binding.config, expectedConfig)),+ },+ );+ if (!request) return;+ const result = await request;+ if ("error" in result) throw result.error;+ return result;+}++export function createIssueWrite(+ link: Parameters<typeof dispatchIssueWrite>[0],+ expectedConfig: string | undefined,+): IssueWrite {+ return async (send) => {+ const result = await dispatchIssueWrite(link, expectedConfig, send);+ if (!result) throw new Error("Issue sync scope changed");+ return result.value;+ };+}diff --git a/apps/api/src/plugins/sync/initialize-task-issue.ts b/apps/api/src/plugins/sync/initialize-task-issue.tsnew file mode 100644index 000000000..fd8ae281f--- /dev/null+++ b/apps/api/src/plugins/sync/initialize-task-issue.ts@@ -0,0 +1,79 @@+import { updateExternalLink } from "../github/services/link-manager";+import { isTaskInFinalState } from "../github/services/task-service";+import { parseLinkMetadata } from "../github/utils/parse-link-metadata";+import type { PluginContext, TaskCreatedEvent } from "../types";+import { createIssueWrite } from "./dispatch-issue-write";+import type { IssueWrite } from "./issue-write";+import { taskIssueLabels } from "./issue-labels";++type Initialization = {+ syncInitializationPending?: boolean;+ syncInitializedState?: boolean;+ syncInitializedLabels?: boolean;+ syncInitializedComment?: boolean;+};+type Link = { id: string; metadata?: string | null };++export function isIssueInitializationPending(link: Link) {+ return (+ parseLinkMetadata<Initialization>(link.metadata, {+ externalLinkId: link.id,+ source: "sync_creation",+ }).syncInitializationPending === true+ );+}++export async function initializeTaskIssue(+ event: TaskCreatedEvent,+ context: PluginContext,+ link: Link,+ actions: {+ close: () => Promise<unknown>;+ labels: (names: string[], write: IssueWrite) => Promise<void>;+ comment?: () => Promise<unknown>;+ },+) {+ const progress = parseLinkMetadata<Initialization>(link.metadata, {+ externalLinkId: link.id,+ source: "sync_creation",+ });+ const write = createIssueWrite(+ { ...link, taskId: event.taskId, integrationId: context.integrationId },+ JSON.stringify(context.config),+ );+ if (!progress.syncInitializedState) {+ if (+ await isTaskInFinalState({+ projectId: event.projectId,+ status: event.status,+ columnId: null,+ })+ ) {+ await write(actions.close);+ await updateExternalLink(link.id, {+ metadata: { state: "closed", lastOutboundStateSyncAt: Date.now() },+ });+ }+ await updateExternalLink(link.id, {+ metadata: { syncInitializedState: true },+ });+ }+ if (!progress.syncInitializedLabels) {+ await actions.labels(+ await taskIssueLabels(event.taskId, event.priority, event.status),+ write,+ );+ await updateExternalLink(link.id, {+ metadata: { syncInitializedLabels: true },+ });+ }+ if (!progress.syncInitializedComment && actions.comment) {+ await write(actions.comment);+ await updateExternalLink(link.id, {+ metadata: { syncInitializedComment: true },+ });+ }+ await updateExternalLink(link.id, {+ metadata: { syncInitializationPending: false },+ });+}diff --git a/apps/api/src/plugins/sync/issue-write.ts b/apps/api/src/plugins/sync/issue-write.tsnew file mode 100644index 000000000..55e014a02--- /dev/null+++ b/apps/api/src/plugins/sync/issue-write.ts@@ -0,0 +1 @@+export type IssueWrite = <T>(send: () => Promise<T>) => Promise<T>;diff --git a/apps/api/src/plugins/sync/lease.ts b/apps/api/src/plugins/sync/lease.tsindex 4b0ab90ec..b521712d0 100644--- a/apps/api/src/plugins/sync/lease.ts+++ b/apps/api/src/plugins/sync/lease.ts@@ -1,62 +1,45 @@-import type { PoolClient } from "pg";-import { getDatabasePool } from "../../database";+import { randomUUID } from "node:crypto";+import { setTimeout as delay } from "node:timers/promises";+import { sql } from "drizzle-orm";+import db from "../../database";-const queues = new Map<string, Promise<unknown>>();-const waiting: Array<() => void> = [];-let active = 0;-const MAX_CONCURRENT_SYNC = 2;+const LEASE_MS = 15 * 60 * 1000;-// Reserve only two pool connections for session locks. Provider callbacks and-// ordinary requests can still use the rest of the pool during network calls.-export function withSyncLease<T>(+export async function withSyncLease<T>(key: string,run: () => Promise<T>,): Promise<T> {- const previous = queues.get(key) ?? Promise.resolve();- const next = previous- .catch(() => {})- .then(async () => {- if (active >= MAX_CONCURRENT_SYNC)- await new Promise<void>((resolve) => waiting.push(resolve));- else active++;- let client: PoolClient | undefined;- let locked = false;- let releaseError: Error | undefined;- try {- client = await getDatabasePool().connect();- // Wait for competing instances, then recheck the link in run(). A failed- // first attempt must not consume a competing task's creation attempt.- await client.query("select pg_advisory_lock(hashtextextended($1, 0))", [- key,- ]);- locked = true;- return await run();- } finally {- if (client) {- try {- if (locked)- await client.query(- "select pg_advisory_unlock(hashtextextended($1, 0))",- [key],- );- } catch (error) {- releaseError =- error instanceof Error- ? error- : new Error("Sync lock release failed");- }- client.release(releaseError);- }- const resume = waiting.shift();- if (resume) resume();- else active--;- }- });- queues.set(key, next);- void next- .finally(() => {- if (queues.get(key) === next) queues.delete(key);- })- .catch(() => {});- return next;+ const owner = randomUUID();+ for (;;) {+ const claimed = await db.execute(sql`+ insert into job_lease (name, owner, expires_at)+ values (${key}, ${owner}, timezone('UTC', clock_timestamp()) + ${LEASE_MS} * interval '1 millisecond')+ on conflict (name) do update set owner = excluded.owner, expires_at = excluded.expires_at+ where job_lease.expires_at < timezone('UTC', clock_timestamp())+ returning name+ `);+ if (claimed.rowCount) break;+ await delay(100);+ }+ // Claims use short statements rather than reserving application connections+ // during provider requests. Slow exports block only their own task key.+ const renewal = setInterval(() => {+ void db+ .execute(sql`+ update job_lease set expires_at = timezone('UTC', clock_timestamp()) + ${LEASE_MS} * interval '1 millisecond'+ where name = ${key} and owner = ${owner}+ `)+ .catch(() => {+ console.error("Sync creation lease renewal failed", { key });+ });+ }, 60_000);+ renewal.unref();+ try {+ return await run();+ } finally {+ clearInterval(renewal);+ await db.execute(+ sql`delete from job_lease where name = ${key} and owner = ${owner}`,+ );+ }}diff --git a/apps/api/src/plugins/sync/workspace-label-changed.ts b/apps/api/src/plugins/sync/workspace-label-changed.tsindex 6efa4aa89..0a5692904 100644--- a/apps/api/src/plugins/sync/workspace-label-changed.ts+++ b/apps/api/src/plugins/sync/workspace-label-changed.ts@@ -19,11 +19,12 @@ export async function notifySyncWorkspaceLabelChanged(.where(and(eq(projectTable.workspaceId, workspaceId),- eq(integrationTable.isActive, true),inArray(integrationTable.type, [...syncProviders]),),);+ const projects = new Set<string>();for (const integration of integrations) {+ projects.add(integration.projectId);const rule = readSyncRules(integration.config)?.outgoing;if (rule?.mode === "labels" && rule.labels.includes(labelId))await publishEvent("integration.sync_labels_changed", {@@ -31,4 +32,6 @@ export async function notifySyncWorkspaceLabelChanged(integrationId: integration.id,});}+ for (const projectId of projects)+ await publishEvent("project.updated", { projectId });}diff --git a/apps/docs/core/integrations/index.mdx b/apps/docs/core/integrations/index.mdxindex 1a83f6fc1..d979ae824 100644--- a/apps/docs/core/integrations/index.mdx+++ b/apps/docs/core/integrations/index.mdx@@ -34,6 +34,8 @@ Kaneo rereads the issue when you resume and rejects a changed comparison. Gitea'An issue creation request already sent to a repository may finish after its task stops matching. Kaneo keeps the returned issue link paused and stops further updates. Local edits remain available while the repository responds.+If creating an issue succeeds but its initial state, labels, or linking comment fails, **Export matching tasks** retries the unfinished steps using the existing issue link.+Newly matching tasks without an issue link are exported in the background when rules or task labels change. Use **Export matching tasks** to retry tasks that still have no issue link after a failed export. An inactive integration does not export or resume tasks. Existing installations retain unrestricted sync until a rule is saved.## Team notificationsdiff --git a/apps/web/src/components/project/sync-rules/sync-rules.test.tsx b/apps/web/src/components/project/sync-rules/sync-rules.test.tsxindex 2ac7fd782..284b0eed2 100644--- a/apps/web/src/components/project/sync-rules/sync-rules.test.tsx+++ b/apps/web/src/components/project/sync-rules/sync-rules.test.tsx@@ -107,6 +107,25 @@ function mount(node = <SyncRulesSection {...param} />) {}describe("advanced sync settings", () => {+ it("invalidates a cached rule preview after resuming a link", async () => {+ const { client } = mount(+ <ResumeSyncDialog param={param} linkId="link-1" onClose={vi.fn()} />,+ );+ const key = [+ "integration-sync-preview",+ param.projectId,+ param.provider,+ saved.rules,+ ];+ client.setQueryData(key, { ...saved, paused: 1, needsReview: 1 });+ await screen.findByText("Kaneo title");+ fireEvent.click(+ screen.getByRole("button", { name: "settings:syncRules.useKaneo" }),+ );+ await waitFor(() =>+ expect(client.getQueryState(key)?.isInvalidated).toBe(true),+ );+ });it("removes unavailable labels without resetting valid selections or match mode", async () => {useUserPreferencesStore.setState({ advancedSettings: true });mocks.get.mockResolvedValue({diff --git a/apps/web/src/hooks/mutations/integration-sync/use-resume-sync.ts b/apps/web/src/hooks/mutations/integration-sync/use-resume-sync.tsindex 6191a07e6..cb94a87ca 100644--- a/apps/web/src/hooks/mutations/integration-sync/use-resume-sync.ts+++ b/apps/web/src/hooks/mutations/integration-sync/use-resume-sync.ts@@ -16,6 +16,9 @@ export function useResumeSync(param: SyncParams, linkId: string) {await client.invalidateQueries({queryKey: ["integration-sync", param.projectId],});+ await client.invalidateQueries({+ queryKey: ["integration-sync-preview", param.projectId],+ });await client.invalidateQueries({queryKey: ["integration-sync-review",diff --git a/tests/api-integration/integration-sync-providers.test.ts b/tests/api-integration/integration-sync-providers.test.tsindex b76935727..6b95b107e 100644--- a/tests/api-integration/integration-sync-providers.test.ts+++ b/tests/api-integration/integration-sync-providers.test.ts@@ -27,6 +27,7 @@ import { getSyncIntegration } from "../../apps/api/src/integration-sync/controllimport { previewSyncRules } from "../../apps/api/src/integration-sync/controllers/preview-rules";import type { SyncRules } from "../../apps/api/src/plugins/sync/rules";import { canSyncTask } from "../../apps/api/src/plugins/sync/eligibility";+import deleteLabel from "../../apps/api/src/label/controllers/delete-label";import { resetTestDatabase } from "./helpers/database";import {createProjectFixture,@@ -89,6 +90,9 @@ beforeAll(() => {beforeEach(async () => {await resetTestDatabase();vi.clearAllMocks();+ mocks.update.mockResolvedValue(undefined);+ mocks.labels.mockResolvedValue(undefined);+ mocks.comment.mockResolvedValue({ id: 123 });mocks.githubCreate.mockResolvedValue({data: {number: 12,@@ -248,10 +252,18 @@ describe.each(["github", "gitea", "gitlab"] as const)(reconcileProjectSync(f.project.id, f.integration.id),]);expect(create).toHaveBeenCalledOnce();- expect(mocks.labels.mock.calls[0]!.at(-1)).toContain("export");- expect(mocks.labels.mock.calls[0]!.at(-1)).toContain("status:to-do");- expect(mocks.labels.mock.calls[0]!.at(-1)).not.toContain("status:done");- expect(mocks.labels.mock.calls[0]!.at(-1)).not.toContain("priority:high");+ expect(mocks.labels.mock.calls[0]![type === "github" ? 4 : 2]).toContain(+ "export",+ );+ expect(mocks.labels.mock.calls[0]![type === "github" ? 4 : 2]).toContain(+ "status:to-do",+ );+ expect(+ mocks.labels.mock.calls[0]![type === "github" ? 4 : 2],+ ).not.toContain("status:done");+ expect(+ mocks.labels.mock.calls[0]![type === "github" ? 4 : 2],+ ).not.toContain("priority:high");expect(await db.query.externalLinkTable.findMany({where: eq(schema.externalLinkTable.taskId, f.task.id),@@ -371,6 +383,143 @@ describe.each(["github", "gitea", "gitlab"] as const)(},);+ it.each(+ type === "github"+ ? (["state", "labels", "comment"] as const)+ : (["state", "labels"] as const),+ )(+ "retries incomplete %s initialization without recreating the issue",+ async (stage) => {+ const f = await setup(type);+ await f.assign();+ if (stage === "comment") {+ f.config.commentTaskLinkOnGitHubIssue = true;+ await db+ .update(schema.integrationTable)+ .set({ config: JSON.stringify(f.config) })+ .where(eq(schema.integrationTable.id, f.integration.id));+ }+ await db+ .update(schema.taskTable)+ .set({ status: f.columns.done.slug, columnId: f.columns.done.id })+ .where(eq(schema.taskTable.id, f.task.id));+ const failing = {+ state: mocks.update,+ labels: mocks.labels,+ comment: mocks.comment,+ }[stage];+ failing.mockRejectedValueOnce(+ new Error("Temporary initialization failure"),+ );+ await reconcileTaskSync(f.project.id, f.task.id);+ const integration = await getSyncIntegration(f.project.id, type);+ expect(+ (await previewSyncRules(integration, f.config.syncRules as SyncRules))+ .willCreate,+ ).toBe(1);+ const link = await db.query.externalLinkTable.findFirst({+ where: eq(schema.externalLinkTable.taskId, f.task.id),+ });+ expect(JSON.parse(link!.metadata!)).toMatchObject({+ syncInitializationPending: true,+ });+ await reconcileTaskSync(f.project.id, f.task.id);+ expect(create).toHaveBeenCalledOnce();+ expect(failing).toHaveBeenCalledTimes(2);+ expect(+ (await previewSyncRules(integration, f.config.syncRules as SyncRules))+ .willCreate,+ ).toBe(0);+ expect(await db.query.externalLinkTable.findMany()).toHaveLength(1);+ },+ );++ it("does not dispatch a comment when its link is paused while the handler waits", async () => {+ const f = await setup(type);+ await f.assign();+ await reconcileTaskSync(f.project.id, f.task.id);+ mocks.comment.mockClear();+ const link = (await db.query.externalLinkTable.findMany())[0]!;+ const holder = await getDatabasePool().connect();+ await holder.query("begin");+ await holder.query(+ "select id from external_link where id = $1 for update",+ [link.id],+ );+ await holder.query(+ "update external_link set metadata = $2 where id = $1",+ [link.id, JSON.stringify({ syncFilterPaused: true })],+ );+ const comment = plugin.onTaskCommentCreated!(+ {+ taskId: f.task.id,+ projectId: f.project.id,+ userId: "test-user",+ comment: "Excluded comment",+ },+ {+ integrationId: f.integration.id,+ projectId: f.project.id,+ config: f.config,+ },+ );+ try {+ await vi.waitFor(async () => {+ const result = await db.execute<{ waiting: number }>(+ sql`select count(*)::int as waiting from pg_stat_activity where datname = current_database() and wait_event_type = 'Lock' and pid <> pg_backend_pid()`,+ );+ expect(result.rows[0]!.waiting).toBeGreaterThan(0);+ });+ } finally {+ await holder.query("commit");+ holder.release();+ await comment;+ }+ expect(mocks.comment).not.toHaveBeenCalled();+ });++ it("releases dispatch locks while the provider handles a comment", async () => {+ const f = await setup(type);+ await f.assign();+ await reconcileTaskSync(f.project.id, f.task.id);+ let release!: () => void;+ const response = new Promise<void>((resolve) => {+ release = resolve;+ });+ mocks.comment.mockClear();+ mocks.comment.mockImplementationOnce(async () => {+ await response;+ return { id: 123 };+ });+ const comment = plugin.onTaskCommentCreated!(+ {+ taskId: f.task.id,+ projectId: f.project.id,+ userId: "test-user",+ comment: "Already dispatched",+ },+ {+ integrationId: f.integration.id,+ projectId: f.project.id,+ config: f.config,+ },+ );+ try {+ await vi.waitFor(() => expect(mocks.comment).toHaveBeenCalledOnce());+ await db+ .delete(schema.labelTable)+ .where(eq(schema.labelTable.taskId, f.task.id));+ await reconcileTaskSync(f.project.id, f.task.id);+ const link = (await db.query.externalLinkTable.findMany())[0]!;+ expect(JSON.parse(link.metadata!)).toMatchObject({+ syncFilterPaused: true,+ });+ } finally {+ release();+ await comment;+ }+ });+it("imports a closed issue gaining a label into a completed column", async () => {const f = await setup(type);if (type === "github") {@@ -561,7 +710,7 @@ it("exports a burst larger than the database pool without exhausting lease conneexpect(await db.query.externalLinkTable.findMany()).toHaveLength(20);});-it("lets an unrelated export proceed while another provider call is slow", async () => {+it("lets an unrelated export proceed while two provider calls are slow", async () => {const f = await setup("gitea");await f.assign();const [other] = await db@@ -593,9 +742,32 @@ it("lets an unrelated export proceed while another provider call is slow", asynctitle: "Fast issue",state: "open",});- const slow = reconcileTaskSync(f.project.id, f.task.id);+ const [secondSlow] = await db+ .insert(schema.taskTable)+ .values({ projectId: f.project.id, number: 3, title: "Second slow task" })+ .returning();+ await db.insert(schema.labelTable).values({+ taskId: secondSlow!.id,+ workspaceId: f.workspace.id,+ name: "export",+ color: "#123456",+ });+ mocks.giteaCreate.mockReset();+ mocks.giteaCreate.mockImplementation(async (...args) => {+ if (args[2].title !== "Fast task") await gate;+ return {+ number: args[2].title === "Fast task" ? 13 : 12,+ html_url: "https://git.example/issues/12",+ title: args[2].title,+ state: "open",+ };+ });+ const slow = Promise.all([+ reconcileTaskSync(f.project.id, f.task.id),+ reconcileTaskSync(f.project.id, secondSlow!.id),+ ]);try {- await vi.waitFor(() => expect(mocks.giteaCreate).toHaveBeenCalledTimes(1));+ await vi.waitFor(() => expect(mocks.giteaCreate).toHaveBeenCalledTimes(2));await reconcileTaskSync(f.project.id, other!.id);expect(await db.query.externalLinkTable.findFirst({@@ -652,23 +824,19 @@ it("waits for another instance's creation lease instead of dropping the export",const f = await setup("gitea");await f.assign();const key = `sync-create:${f.integration.id}:${f.task.id}`;- const holder = await getDatabasePool().connect();- await holder.query("select pg_advisory_lock(hashtextextended($1, 0))", [key]);+ await db.insert(schema.jobLeaseTable).values({+ name: key,+ owner: "other-test-instance",+ expiresAt: new Date(Date.now() + 60_000),+ });const competing = reconcileTaskSync(f.project.id, f.task.id);try {- await vi.waitFor(async () => {- const result = await db.execute<{ waiting: number }>(sql`- select count(*)::int as waiting from pg_stat_activity- where datname = current_database() and wait_event = 'advisory'- `);- expect(result.rows[0]!.waiting).toBeGreaterThan(0);- });+ await new Promise((resolve) => setTimeout(resolve, 250));expect(mocks.giteaCreate).not.toHaveBeenCalled();} finally {- await holder.query("select pg_advisory_unlock(hashtextextended($1, 0))", [- key,- ]);- holder.release();+ await db+ .delete(schema.jobLeaseTable)+ .where(eq(schema.jobLeaseTable.name, key));await competing;}expect(mocks.giteaCreate).toHaveBeenCalledOnce();@@ -758,3 +926,25 @@ it("continues after a task export throws and leaves failed tasks available for elog.mockRestore();}});++it("broadcasts deleted label availability even without changed links or an active integration", async () => {+ const f = await setup("gitea");+ const foreign = await setup("gitea");+ await db+ .update(schema.integrationTable)+ .set({ isActive: false })+ .where(eq(schema.integrationTable.id, f.integration.id));+ const publish = vi.spyOn(events, "publishEvent");+ await deleteLabel(f.config.syncRules.outgoing.labels[0]!, "test-user");+ expect(publish).toHaveBeenCalledWith("project.updated", {+ projectId: f.project.id,+ });+ expect(publish).not.toHaveBeenCalledWith("project.updated", {+ projectId: foreign.project.id,+ });+ const integration = await getSyncIntegration(f.project.id, "gitea");+ expect(+ (await previewSyncRules(integration, f.config.syncRules as SyncRules))+ .missingLabels,+ ).toEqual(f.config.syncRules.outgoing.labels);+});diff --git a/tests/api/plugins/gitea/comment-sync.test.ts b/tests/api/plugins/gitea/comment-sync.test.tsindex 9ac68332d..6b2ff4521 100644--- a/tests/api/plugins/gitea/comment-sync.test.ts+++ b/tests/api/plugins/gitea/comment-sync.test.ts@@ -228,3 +228,12 @@ vi.mock(vi.mock("../../../../apps/api/src/plugins/sync/eligibility", () => ({canSyncTask: async () => true,}));++vi.mock("../../../../apps/api/src/plugins/sync/dispatch-issue-write", () => ({+ createIssueWrite: () => (send: () => Promise<unknown>) => send(),+ dispatchIssueWrite: async (+ _link: unknown,+ _config: unknown,+ send: () => Promise<unknown>,+ ) => ({ value: await send() }),+}));diff --git a/tests/api/plugins/gitea/rapid-text-sync.test.ts b/tests/api/plugins/gitea/rapid-text-sync.test.tsindex 159f56bcd..5bca99e99 100644--- a/tests/api/plugins/gitea/rapid-text-sync.test.ts+++ b/tests/api/plugins/gitea/rapid-text-sync.test.ts@@ -428,3 +428,12 @@ it("applies a close following an inbound reopen within the same provider timestaexpect(m.status).toHaveBeenCalledTimes(2);expect(JSON.parse(m.metadata).state).toBe("closed");});++vi.mock("../../../../apps/api/src/plugins/sync/dispatch-issue-write", () => ({+ createIssueWrite: () => (send: () => Promise<unknown>) => send(),+ dispatchIssueWrite: async (+ _link: unknown,+ _config: unknown,+ send: () => Promise<unknown>,+ ) => ({ value: await send() }),+}));diff --git a/tests/api/plugins/github/outbound-intent.test.ts b/tests/api/plugins/github/outbound-intent.test.tsindex a8a450132..a6eaf11be 100644--- a/tests/api/plugins/github/outbound-intent.test.ts+++ b/tests/api/plugins/github/outbound-intent.test.ts@@ -17,6 +17,7 @@ const m = vi.hoisted(() => ({current: { title: "", description: "", status: "" },stamps: {} as Record<string, SyncStamp>,save: vi.fn(),+ dispatch: vi.fn(),}));vi.mock("../../../../apps/api/src/database", () => ({default: {@@ -77,6 +78,15 @@ vi.mock();const link = { id: "link", integrationId: "integration" };beforeEach(() => {+ m.dispatch+ .mockReset()+ .mockImplementation(+ async (+ _link: unknown,+ _config: unknown,+ send: () => Promise<unknown>,+ ) => ({ value: await send() }),+ );m.stamps = {};m.save.mockReset().mockImplementation(async (@@ -508,3 +518,28 @@ it("bounds confirmation retries and durably defers continuous sync changes", asyvi.mock("../../../../apps/api/src/plugins/sync/eligibility", () => ({canSyncTask: async () => true,}));++vi.mock("../../../../apps/api/src/plugins/sync/dispatch-issue-write", () => ({+ createIssueWrite: () => (send: () => Promise<unknown>) => send(),+ dispatchIssueWrite: m.dispatch,+}));++it("cancels an outbound intent when scope changes before dispatch", async () => {+ m.current = { title: "Paused edit", description: "", status: "to-do" };+ m.dispatch.mockResolvedValueOnce(undefined);+ const write = vi.fn();+ await syncLatestTaskValue(+ "task",+ "project",+ { id: "link", integrationId: "integration" },+ "title",+ "Paused edit",+ write,+ );+ expect(write).not.toHaveBeenCalled();+ expect(m.stamps.title?.outbound?.[0]).toMatchObject({+ pending: false,+ cancelled: true,+ uncertain: false,+ });+});diff --git a/tests/api/plugins/github/rapid-state-sync.test.ts b/tests/api/plugins/github/rapid-state-sync.test.tsindex 54c002549..bd4834d71 100644--- a/tests/api/plugins/github/rapid-state-sync.test.ts+++ b/tests/api/plugins/github/rapid-state-sync.test.ts@@ -138,3 +138,12 @@ it.each([vi.mock("../../../../apps/api/src/plugins/sync/eligibility", () => ({canSyncTask: async () => true,}));++vi.mock("../../../../apps/api/src/plugins/sync/dispatch-issue-write", () => ({+ createIssueWrite: () => (send: () => Promise<unknown>) => send(),+ dispatchIssueWrite: async (+ _link: unknown,+ _config: unknown,+ send: () => Promise<unknown>,+ ) => ({ value: await send() }),+}));diff --git a/tests/api/plugins/github/rapid-text-sync.test.ts b/tests/api/plugins/github/rapid-text-sync.test.tsindex 6c743eb8d..19a29ff31 100644--- a/tests/api/plugins/github/rapid-text-sync.test.ts+++ b/tests/api/plugins/github/rapid-text-sync.test.ts@@ -236,3 +236,12 @@ it.each([vi.mock("../../../../apps/api/src/plugins/sync/eligibility", () => ({canSyncTask: async () => true,}));++vi.mock("../../../../apps/api/src/plugins/sync/dispatch-issue-write", () => ({+ createIssueWrite: () => (send: () => Promise<unknown>) => send(),+ dispatchIssueWrite: async (+ _link: unknown,+ _config: unknown,+ send: () => Promise<unknown>,+ ) => ({ value: await send() }),+}));diff --git a/tests/api/plugins/gitlab/events/task-status-changed.test.ts b/tests/api/plugins/gitlab/events/task-status-changed.test.tsindex 80a6210c1..81ca85cf5 100644--- a/tests/api/plugins/gitlab/events/task-status-changed.test.ts+++ b/tests/api/plugins/gitlab/events/task-status-changed.test.ts@@ -133,3 +133,15 @@ describe("GitLab status webhook feedback", () => {vi.mock("../../../../../apps/api/src/plugins/sync/eligibility", () => ({canSyncTask: async () => true,}));++vi.mock(+ "../../../../../apps/api/src/plugins/sync/dispatch-issue-write",+ () => ({+ createIssueWrite: () => (send: () => Promise<unknown>) => send(),+ dispatchIssueWrite: async (+ _link: unknown,+ _config: unknown,+ send: () => Promise<unknown>,+ ) => ({ value: await send() }),+ }),+);