Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

fix(api): stop label webhook echoes from flipping task status

Tin23bdea7f5747
diff --git a/apps/api/src/plugins/gitea/webhooks/issue-labeled.ts b/apps/api/src/plugins/gitea/webhooks/issue-labeled.ts
index 4f3e3f469..0e064f234 100644
--- a/apps/api/src/plugins/gitea/webhooks/issue-labeled.ts
+++ b/apps/api/src/plugins/gitea/webhooks/issue-labeled.ts
@@ -1,4 +1,6 @@
+import { changedLabelFields } from "../../sync/changed-label-fields";
import { resumeLabelChanges } from "../../sync/resume-label-changes";
+import { withCurrentIssueLabels } from "../../sync/with-current-issue-labels";
import { acceptsIssue, readSyncRules } from "../../sync/rules";
import { handleGiteaIssueOpened } from "./issue-opened";
import { withIntegrationLink } from "../../github/services/with-integration-link";
@@ -14,10 +16,6 @@ import {
updateExternalLink,
} from "../../github/services/link-manager";
import { updateTaskStatus } from "../../github/services/task-service";
-import {
- extractIssuePriority,
- extractIssueStatus,
-} from "../../github/utils/extract-priority";
import {
findAllIntegrationsByGiteaRepo,
repoOwnerLogin,
@@ -175,173 +173,189 @@ export async function handleGiteaIssueLabeled(
continue;
}
- await withIntegrationLink(
- existingLink,
- integration,
- async (db, afterCommit, existingLink) => {
- const names = (issue.labels ?? []).flatMap((label) => {
- const name = typeof label === "string" ? label : label.name;
- return name ? [name] : [];
- });
- const changes = resumeLabelChanges(existingLink, names);
- if (changes.baseline && issue.labels !== undefined)
- await updateExternalLink(
- existingLink.id,
- { metadata: { syncResumeLabelBaseline: names } },
- db,
- );
- const priority = extractIssuePriority(issue.labels);
- const status = extractIssueStatus(issue.labels);
-
- if (priority && changes.priorityChanged) {
- await db
- .update(taskTable)
- .set({ priority })
- .where(
- linkedTaskScope(existingLink.taskId, integration.projectId),
+ const names = (issue.labels ?? []).flatMap((label) => {
+ const name = typeof label === "string" ? label : label.name;
+ return name ? [name] : [];
+ });
+ const apply = (current?: string[]) =>
+ withIntegrationLink(
+ existingLink,
+ integration,
+ async (db, afterCommit, existingLink) => {
+ const changes = resumeLabelChanges(existingLink, names);
+ if (changes.baseline && issue.labels !== undefined)
+ await updateExternalLink(
+ existingLink.id,
+ { metadata: { syncResumeLabelBaseline: names } },
+ db,
);
- }
+ const task =
+ current &&
+ (await db.query.taskTable.findFirst({
+ where: linkedTaskScope(
+ existingLink.taskId,
+ integration.projectId,
+ ),
+ columns: { status: true, priority: true },
+ }));
+ const { priority, status } = task
+ ? changedLabelFields(existingLink, current, task)
+ : {};
- if (status && changes.statusChanged) {
- const statusResult = await updateTaskStatus(
- existingLink.taskId,
- status,
- db,
- );
- if (
- statusResult.applied &&
- statusResult.before.status !== statusResult.after.status
- ) {
- afterCommit(() =>
- publishEvent("task.status_changed", {
- taskId: statusResult.after.id,
- projectId: statusResult.after.projectId,
- userId: null,
- oldStatus: statusResult.before.status,
- newStatus: statusResult.after.status,
- title: statusResult.after.title,
- assigneeId: statusResult.after.userId,
- type: "status_changed",
- }),
+ if (priority) {
+ await db
+ .update(taskTable)
+ .set({ priority })
+ .where(
+ linkedTaskScope(existingLink.taskId, integration.projectId),
+ );
+ }
+
+ if (status) {
+ const statusResult = await updateTaskStatus(
+ existingLink.taskId,
+ status,
+ db,
);
+ if (
+ statusResult.applied &&
+ statusResult.before.status !== statusResult.after.status
+ ) {
+ afterCommit(() =>
+ publishEvent("task.status_changed", {
+ taskId: statusResult.after.id,
+ projectId: statusResult.after.projectId,
+ userId: null,
+ oldStatus: statusResult.before.status,
+ newStatus: statusResult.after.status,
+ title: statusResult.after.title,
+ assigneeId: statusResult.after.userId,
+ type: "status_changed",
+ }),
+ );
+ }
}
- }
- if (payload.action === "label_updated") {
- if (issue.labels === undefined) {
+ if (payload.action === "label_updated") {
+ if (issue.labels === undefined) {
+ return;
+ }
+
+ const task = await db.query.taskTable.findFirst({
+ where: linkedTaskScope(
+ existingLink.taskId,
+ integration.projectId,
+ ),
+ with: {
+ project: true,
+ },
+ });
+ if (task?.project?.workspaceId) {
+ await syncGiteaLabelsToTask(
+ existingLink.taskId,
+ task.project.workspaceId,
+ giteaLabelsForSync(issue.labels),
+ db,
+ changes.baseline,
+ );
+ afterCommit(() =>
+ publishEvent("task.labels_updated", {
+ projectId: integration.projectId,
+ taskId: existingLink.taskId,
+ }),
+ );
+ }
return;
}
- const task = await db.query.taskTable.findFirst({
- where: linkedTaskScope(
- existingLink.taskId,
- integration.projectId,
- ),
- with: {
- project: true,
- },
- });
- if (task?.project?.workspaceId) {
- await syncGiteaLabelsToTask(
- existingLink.taskId,
- task.project.workspaceId,
- giteaLabelsForSync(issue.labels),
- db,
- changes.baseline,
- );
- afterCommit(() =>
- publishEvent("task.labels_updated", {
- projectId: integration.projectId,
- taskId: existingLink.taskId,
- }),
- );
+ if (!addedLabel) {
+ if (priority)
+ afterCommit(() =>
+ publishEvent("task.updated", {
+ projectId: integration.projectId,
+ taskId: existingLink.taskId,
+ }),
+ );
+ return;
}
- return;
- }
- if (!addedLabel) {
- if (priority)
- afterCommit(() =>
- publishEvent("task.updated", {
- projectId: integration.projectId,
- taskId: existingLink.taskId,
- }),
- );
- return;
- }
+ if (isSystemLabelName(addedLabel.name)) {
+ if (priority)
+ afterCommit(() =>
+ publishEvent("task.updated", {
+ projectId: integration.projectId,
+ taskId: existingLink.taskId,
+ }),
+ );
+ return;
+ }
- if (isSystemLabelName(addedLabel.name)) {
- if (priority)
- afterCommit(() =>
- publishEvent("task.updated", {
- projectId: integration.projectId,
- taskId: existingLink.taskId,
- }),
- );
- return;
- }
+ if (payload.action === "labeled") {
+ const task = await db.query.taskTable.findFirst({
+ where: linkedTaskScope(
+ existingLink.taskId,
+ integration.projectId,
+ ),
+ with: {
+ project: true,
+ },
+ });
- if (payload.action === "labeled") {
- const task = await db.query.taskTable.findFirst({
- where: linkedTaskScope(
- existingLink.taskId,
- integration.projectId,
- ),
- with: {
- project: true,
- },
- });
+ if (task?.project?.workspaceId) {
+ const existingLabel = await db.query.labelTable.findFirst({
+ where: (table, { and, eq: e }) =>
+ and(
+ e(table.workspaceId, task.project.workspaceId),
+ e(table.name, addedLabel.name),
+ e(table.taskId, task.id),
+ ),
+ });
- if (task?.project?.workspaceId) {
- const existingLabel = await db.query.labelTable.findFirst({
+ if (!existingLabel) {
+ const color = addedLabel.color
+ ? `#${addedLabel.color.replace(/^#/, "")}`
+ : "#6B7280";
+ await db
+ .insert(labelTable)
+ .values({
+ name: addedLabel.name,
+ color,
+ taskId: task.id,
+ workspaceId: task.project.workspaceId,
+ })
+ .onConflictDoNothing({
+ target: [labelTable.taskId, labelTable.name],
+ });
+ }
+ }
+ }
+
+ if (payload.action === "unlabeled") {
+ const labelsToDelete = await db.query.labelTable.findMany({
where: (table, { and, eq: e }) =>
and(
- e(table.workspaceId, task.project.workspaceId),
+ e(table.taskId, existingLink.taskId),
e(table.name, addedLabel.name),
- e(table.taskId, task.id),
),
});
- if (!existingLabel) {
- const color = addedLabel.color
- ? `#${addedLabel.color.replace(/^#/, "")}`
- : "#6B7280";
- await db
- .insert(labelTable)
- .values({
- name: addedLabel.name,
- color,
- taskId: task.id,
- workspaceId: task.project.workspaceId,
- })
- .onConflictDoNothing({
- target: [labelTable.taskId, labelTable.name],
- });
+ for (const label of labelsToDelete) {
+ await db.delete(labelTable).where(eq(labelTable.id, label.id));
}
}
- }
-
- if (payload.action === "unlabeled") {
- const labelsToDelete = await db.query.labelTable.findMany({
- where: (table, { and, eq: e }) =>
- and(
- e(table.taskId, existingLink.taskId),
- e(table.name, addedLabel.name),
- ),
- });
+ afterCommit(() =>
+ publishEvent("task.labels_updated", {
+ projectId: integration.projectId,
+ taskId: existingLink.taskId,
+ }),
+ );
+ },
+ );
- for (const label of labelsToDelete) {
- await db.delete(labelTable).where(eq(labelTable.id, label.id));
- }
- }
- afterCommit(() =>
- publishEvent("task.labels_updated", {
- projectId: integration.projectId,
- taskId: existingLink.taskId,
- }),
- );
- },
- );
+ // label_updated has no single label, so it always reads the issue.
+ await (!addedLabel || isSystemLabelName(addedLabel.name)
+ ? withCurrentIssueLabels(integration, existingLink, apply)
+ : apply());
} catch (error) {
console.error("Gitea issue_labeled handler failed for integration", {
integrationId: integration.id,
diff --git a/apps/api/src/plugins/github/webhooks/issue-labeled.ts b/apps/api/src/plugins/github/webhooks/issue-labeled.ts
index 13af1ba2a..f59bf0a8e 100644
--- a/apps/api/src/plugins/github/webhooks/issue-labeled.ts
+++ b/apps/api/src/plugins/github/webhooks/issue-labeled.ts
@@ -1,4 +1,6 @@
+import { changedLabelFields } from "../../sync/changed-label-fields";
import { resumeLabelChanges } from "../../sync/resume-label-changes";
+import { withCurrentIssueLabels } from "../../sync/with-current-issue-labels";
import { acceptsIssue, readSyncRules } from "../../sync/rules";
import { handleIssueOpened } from "./issue-opened";
import { withIntegrationLink } from "../services/with-integration-link";
@@ -11,10 +13,6 @@ import {
findAllIntegrationsByRepo,
updateTaskStatus,
} from "../services/task-service";
-import {
- extractIssuePriority,
- extractIssueStatus,
-} from "../utils/extract-priority";
type IssueLabeledPayload = {
action: string;
@@ -64,141 +62,153 @@ export async function handleIssueLabeled(payload: IssueLabeledPayload) {
continue;
}
- await withIntegrationLink(
- existingLink,
- integration,
- async (db, afterCommit, existingLink) => {
- const names = (issue.labels ?? []).flatMap((label) => {
- const name = typeof label === "string" ? label : label.name;
- return name ? [name] : [];
- });
- const changes = resumeLabelChanges(existingLink, names);
- if (changes.baseline && issue.labels !== undefined)
- await updateExternalLink(
- existingLink.id,
- { metadata: { syncResumeLabelBaseline: names } },
- db,
- );
- const priority = extractIssuePriority(issue.labels);
- const status = extractIssueStatus(issue.labels);
-
- if (priority && changes.priorityChanged) {
- await db
- .update(taskTable)
- .set({ priority })
- .where(linkedTaskScope(existingLink.taskId, integration.projectId));
- }
-
- if (status && changes.statusChanged) {
- const statusResult = await updateTaskStatus(
- existingLink.taskId,
- status,
- db,
- );
- if (
- statusResult.applied &&
- statusResult.before.status !== statusResult.after.status
- ) {
- afterCommit(() =>
- publishEvent("task.status_changed", {
- taskId: statusResult.after.id,
- projectId: statusResult.after.projectId,
- userId: null,
- oldStatus: statusResult.before.status,
- newStatus: statusResult.after.status,
- title: statusResult.after.title,
- assigneeId: statusResult.after.userId,
- type: "status_changed",
- }),
+ const names = (issue.labels ?? []).flatMap((label) => {
+ const name = typeof label === "string" ? label : label.name;
+ return name ? [name] : [];
+ });
+ const systemEvent =
+ !addedLabel ||
+ addedLabel.name.startsWith("priority:") ||
+ addedLabel.name.startsWith("status:");
+
+ const apply = (current?: string[]) =>
+ withIntegrationLink(
+ existingLink,
+ integration,
+ async (db, afterCommit, existingLink) => {
+ const changes = resumeLabelChanges(existingLink, names);
+ if (changes.baseline && issue.labels !== undefined)
+ await updateExternalLink(
+ existingLink.id,
+ { metadata: { syncResumeLabelBaseline: names } },
+ db,
);
+ const task =
+ current &&
+ (await db.query.taskTable.findFirst({
+ where: linkedTaskScope(
+ existingLink.taskId,
+ integration.projectId,
+ ),
+ columns: { status: true, priority: true },
+ }));
+ const { priority, status } = task
+ ? changedLabelFields(existingLink, current, task)
+ : {};
+
+ if (priority) {
+ await db
+ .update(taskTable)
+ .set({ priority })
+ .where(
+ linkedTaskScope(existingLink.taskId, integration.projectId),
+ );
}
- }
-
- if (!addedLabel) {
- if (priority)
- afterCommit(() =>
- publishEvent("task.updated", {
- projectId: integration.projectId,
- taskId: existingLink.taskId,
- }),
- );
- return;
- }
-
- const isSystemLabel =
- addedLabel.name.startsWith("priority:") ||
- addedLabel.name.startsWith("status:");
-
- if (isSystemLabel) {
- if (priority)
- afterCommit(() =>
- publishEvent("task.updated", {
- projectId: integration.projectId,
- taskId: existingLink.taskId,
- }),
+
+ if (status) {
+ const statusResult = await updateTaskStatus(
+ existingLink.taskId,
+ status,
+ db,
);
- return;
- }
-
- if (payload.action === "labeled") {
- const task = await db.query.taskTable.findFirst({
- where: linkedTaskScope(existingLink.taskId, integration.projectId),
- with: {
- project: true,
- },
- });
-
- if (task?.project?.workspaceId) {
- const existingLabel = await db.query.labelTable.findFirst({
+ if (
+ statusResult.applied &&
+ statusResult.before.status !== statusResult.after.status
+ ) {
+ afterCommit(() =>
+ publishEvent("task.status_changed", {
+ taskId: statusResult.after.id,
+ projectId: statusResult.after.projectId,
+ userId: null,
+ oldStatus: statusResult.before.status,
+ newStatus: statusResult.after.status,
+ title: statusResult.after.title,
+ assigneeId: statusResult.after.userId,
+ type: "status_changed",
+ }),
+ );
+ }
+ }
+
+ if (!addedLabel || systemEvent) {
+ if (priority)
+ afterCommit(() =>
+ publishEvent("task.updated", {
+ projectId: integration.projectId,
+ taskId: existingLink.taskId,
+ }),
+ );
+ return;
+ }
+
+ if (payload.action === "labeled") {
+ const task = await db.query.taskTable.findFirst({
+ where: linkedTaskScope(
+ existingLink.taskId,
+ integration.projectId,
+ ),
+ with: {
+ project: true,
+ },
+ });
+
+ if (task?.project?.workspaceId) {
+ const existingLabel = await db.query.labelTable.findFirst({
+ where: (table, { and, eq }) =>
+ and(
+ eq(table.workspaceId, task.project.workspaceId),
+ eq(table.name, addedLabel.name),
+ eq(table.taskId, task.id),
+ ),
+ });
+
+ if (!existingLabel) {
+ const color = addedLabel.color
+ ? `#${addedLabel.color}`
+ : "#6B7280";
+ await db
+ .insert(labelTable)
+ .values({
+ name: addedLabel.name,
+ color,
+ taskId: task.id,
+ workspaceId: task.project.workspaceId,
+ })
+ .onConflictDoNothing({
+ target: [labelTable.taskId, labelTable.name],
+ });
+ }
+ }
+ }
+
+ if (payload.action === "unlabeled") {
+ const labelsToDelete = await db.query.labelTable.findMany({
where: (table, { and, eq }) =>
and(
- eq(table.workspaceId, task.project.workspaceId),
+ eq(table.taskId, existingLink.taskId),
eq(table.name, addedLabel.name),
- eq(table.taskId, task.id),
),
});
- if (!existingLabel) {
- const color = addedLabel.color
- ? `#${addedLabel.color}`
- : "#6B7280";
- await db
- .insert(labelTable)
- .values({
- name: addedLabel.name,
- color,
- taskId: task.id,
- workspaceId: task.project.workspaceId,
- })
- .onConflictDoNothing({
- target: [labelTable.taskId, labelTable.name],
- });
+ for (const label of labelsToDelete) {
+ await db.delete(labelTable).where(eq(labelTable.id, label.id));
}
}
- }
-
- if (payload.action === "unlabeled") {
- const labelsToDelete = await db.query.labelTable.findMany({
- where: (table, { and, eq }) =>
- and(
- eq(table.taskId, existingLink.taskId),
- eq(table.name, addedLabel.name),
- ),
- });
- for (const label of labelsToDelete) {
- await db.delete(labelTable).where(eq(labelTable.id, label.id));
- }
- }
-
- afterCommit(() =>
- publishEvent("task.labels_updated", {
- projectId: integration.projectId,
- taskId: existingLink.taskId,
- }),
- );
- return;
- },
- );
+ afterCommit(() =>
+ publishEvent("task.labels_updated", {
+ projectId: integration.projectId,
+ taskId: existingLink.taskId,
+ }),
+ );
+ return;
+ },
+ );
+
+ // Only status and priority label events can change those fields. Other
+ // events skip the provider read; their snapshot may predate Kaneo's write.
+ await (systemEvent
+ ? withCurrentIssueLabels(integration, existingLink, apply)
+ : apply());
}
}
diff --git a/apps/api/src/plugins/gitlab/webhooks/issue-updated.ts b/apps/api/src/plugins/gitlab/webhooks/issue-updated.ts
index 85ebe2b4d..5a4b8d9d5 100644
--- a/apps/api/src/plugins/gitlab/webhooks/issue-updated.ts
+++ b/apps/api/src/plugins/gitlab/webhooks/issue-updated.ts
@@ -1,4 +1,6 @@
+import { changedLabelFields } from "../../sync/changed-label-fields";
import { resumeLabelChanges } from "../../sync/resume-label-changes";
+import { withCurrentIssueLabels } from "../../sync/with-current-issue-labels";
import { acceptsIssue, readSyncRules } from "../../sync/rules";
import { handleGitlabIssueOpened } from "./issue-opened";
import { withIntegrationLink } from "../../github/services/with-integration-link";
@@ -14,10 +16,6 @@ import {
updateExternalLink,
} from "../../github/services/link-manager";
import { updateTaskStatus } from "../../github/services/task-service";
-import {
- extractIssuePriority,
- extractIssueStatus,
-} from "../../github/utils/extract-priority";
import { findAllIntegrationsByGitlabProject } from "../services/integration-lookup";
import { taskDescriptionFromIssue } from "../utils/issue-description";
import {
@@ -189,157 +187,165 @@ export async function handleGitlabIssueUpdated(
continue;
}
- await withIntegrationLink(
- externalLink,
- integration,
- async (db, afterCommit, externalLink) => {
- const task = await db.query.taskTable.findFirst({
- where: linkedTaskScope(externalLink.taskId, integration.projectId),
- with: { project: true },
- });
-
- if (!task) {
- return;
- }
-
- let metadata: LinkMetadata = parseLinkSyncMetadata(
- externalLink.metadata,
- { externalLinkId: externalLink.id, field: "issue" },
- );
-
- if (touchedText) {
- const updateData: Record<string, unknown> = {};
- const lastSync = { ...metadata.lastSync };
- const now = new Date().toISOString();
-
- if (
- changes?.title &&
- !isEchoOf(metadata.lastSync?.title, "kaneo", issue.title)
- ) {
- updateData.title = issue.title;
- lastSync.title = {
- timestamp: now,
- source: "gitlab",
- value: issue.title,
- };
+ const apply = (current?: string[]) =>
+ withIntegrationLink(
+ externalLink,
+ integration,
+ async (db, afterCommit, externalLink) => {
+ const task = await db.query.taskTable.findFirst({
+ where: linkedTaskScope(
+ externalLink.taskId,
+ integration.projectId,
+ ),
+ with: { project: true },
+ });
+
+ if (!task) {
+ return;
}
- if (changes?.description) {
- // Kaneo recorded the body with its footer, so compare the raw body.
- const issueBody = issue.description ?? "";
+ let metadata: LinkMetadata = parseLinkSyncMetadata(
+ externalLink.metadata,
+ { externalLinkId: externalLink.id, field: "issue" },
+ );
+
+ if (touchedText) {
+ const updateData: Record<string, unknown> = {};
+ const lastSync = { ...metadata.lastSync };
+ const now = new Date().toISOString();
+
if (
- !isEchoOf(metadata.lastSync?.description, "kaneo", issueBody)
+ changes?.title &&
+ !isEchoOf(metadata.lastSync?.title, "kaneo", issue.title)
) {
- const description = taskDescriptionFromIssue(issue.description);
- updateData.description = description;
- lastSync.description = {
+ updateData.title = issue.title;
+ lastSync.title = {
timestamp: now,
source: "gitlab",
- value: description,
+ value: issue.title,
};
}
+
+ if (changes?.description) {
+ // Kaneo recorded the body with its footer, so compare the raw body.
+ const issueBody = issue.description ?? "";
+ if (
+ !isEchoOf(metadata.lastSync?.description, "kaneo", issueBody)
+ ) {
+ const description = taskDescriptionFromIssue(
+ issue.description,
+ );
+ updateData.description = description;
+ lastSync.description = {
+ timestamp: now,
+ source: "gitlab",
+ value: description,
+ };
+ }
+ }
+
+ if (Object.keys(updateData).length > 0) {
+ await db
+ .update(taskTable)
+ .set(updateData)
+ .where(linkedTaskScope(task.id, integration.projectId));
+
+ metadata = { ...metadata, lastSync };
+
+ await updateExternalLink(
+ externalLink.id,
+ {
+ title: issue.title,
+ metadata,
+ },
+ db,
+ );
+ afterCommit(() =>
+ publishEvent("task.updated", {
+ projectId: integration.projectId,
+ taskId: task.id,
+ ...(typeof updateData.title === "string"
+ ? { titleChanged: true }
+ : {}),
+ }),
+ );
+ }
}
- if (Object.keys(updateData).length > 0) {
+ if (!touchedLabels || !currentLabels) {
+ return;
+ }
+
+ const titles = labelTitles(currentLabels);
+ const labelChanges = resumeLabelChanges(externalLink, titles);
+ if (labelChanges.baseline)
+ await updateExternalLink(
+ externalLink.id,
+ { metadata: { syncResumeLabelBaseline: titles } },
+ db,
+ );
+
+ const { priority, status } = current
+ ? changedLabelFields(externalLink, current, task)
+ : {};
+
+ if (priority) {
await db
.update(taskTable)
- .set(updateData)
+ .set({ priority })
.where(linkedTaskScope(task.id, integration.projectId));
+ }
- metadata = { ...metadata, lastSync };
+ if (status) {
+ const statusResult = await updateTaskStatus(task.id, status, db);
+ if (
+ statusResult.applied &&
+ statusResult.before.status !== statusResult.after.status
+ ) {
+ afterCommit(() =>
+ publishEvent("task.status_changed", {
+ sourceIntegrationId: integration.id,
+ taskId: statusResult.after.id,
+ projectId: statusResult.after.projectId,
+ userId: null,
+ oldStatus: statusResult.before.status,
+ newStatus: statusResult.after.status,
+ title: statusResult.after.title,
+ assigneeId: statusResult.after.userId,
+ type: "status_changed",
+ }),
+ );
+ }
+ }
- await updateExternalLink(
- externalLink.id,
- {
- title: issue.title,
- metadata,
- },
+ if (task.project?.workspaceId) {
+ await syncGitlabLabelsToTask(
+ task.id,
+ task.project.workspaceId,
+ nonSystemLabels(currentLabels),
+ changes?.labels?.previous,
db,
+ labelChanges.baseline,
);
afterCommit(() =>
- publishEvent("task.updated", {
+ publishEvent("task.labels_updated", {
projectId: integration.projectId,
taskId: task.id,
- ...(typeof updateData.title === "string"
- ? { titleChanged: true }
- : {}),
- }),
- );
- }
- }
-
- if (!touchedLabels || !currentLabels) {
- return;
- }
-
- const titles = labelTitles(currentLabels);
- const labelChanges = resumeLabelChanges(externalLink, titles);
- if (labelChanges.baseline)
- await updateExternalLink(
- externalLink.id,
- { metadata: { syncResumeLabelBaseline: titles } },
- db,
- );
-
- const priority = extractIssuePriority(titles);
- const status = extractIssueStatus(titles);
-
- if (priority && labelChanges.priorityChanged) {
- await db
- .update(taskTable)
- .set({ priority })
- .where(linkedTaskScope(task.id, integration.projectId));
- }
-
- // Unrelated label edits also include the full label snapshot. Its status
- // can predate a close/reopen, so only apply an actual status-label change.
- const previousStatus = extractIssueStatus(
- labelTitles(changes?.labels?.previous),
- );
- if (
- status &&
- labelChanges.statusChanged &&
- status !== previousStatus
- ) {
- const statusResult = await updateTaskStatus(task.id, status, db);
- if (
- statusResult.applied &&
- statusResult.before.status !== statusResult.after.status
- ) {
- afterCommit(() =>
- publishEvent("task.status_changed", {
- sourceIntegrationId: integration.id,
- taskId: statusResult.after.id,
- projectId: statusResult.after.projectId,
- userId: null,
- oldStatus: statusResult.before.status,
- newStatus: statusResult.after.status,
- title: statusResult.after.title,
- assigneeId: statusResult.after.userId,
- type: "status_changed",
}),
);
}
- }
-
- if (task.project?.workspaceId) {
- await syncGitlabLabelsToTask(
- task.id,
- task.project.workspaceId,
- nonSystemLabels(currentLabels),
- changes?.labels?.previous,
- db,
- labelChanges.baseline,
- );
- afterCommit(() =>
- publishEvent("task.labels_updated", {
- projectId: integration.projectId,
- taskId: task.id,
- }),
- );
- }
- },
- );
+ },
+ );
+
+ // Unrelated label edits also include the full label snapshot, which can
+ // predate a close/reopen or a newer Kaneo write. Only status and priority
+ // label changes resolve those fields, from the issue's current labels.
+ const fieldLabels = (labels?: GitlabWebhookLabel[]) =>
+ labelTitles(labels).filter(isSystemLabelName).sort().join();
+ await (touchedLabels &&
+ fieldLabels(changes?.labels?.previous) !== fieldLabels(currentLabels)
+ ? withCurrentIssueLabels(integration, externalLink, apply)
+ : apply());
} catch (error) {
console.error("GitLab issue update handler failed for integration", {
integrationId: integration.id,
diff --git a/apps/api/src/plugins/sync/changed-label-fields.ts b/apps/api/src/plugins/sync/changed-label-fields.ts
new file mode 100644
index 000000000..fe3efb0ec
--- /dev/null
+++ b/apps/api/src/plugins/sync/changed-label-fields.ts
@@ -0,0 +1,26 @@
+import {
+ extractIssuePriority,
+ extractIssueStatus,
+} from "../github/utils/extract-priority";
+import { resumeLabelChanges } from "./resume-label-changes";
+
+/** Fields that the issue's current labels set to a value the task lacks. */
+export function changedLabelFields(
+ link: { id: string; metadata: string | null },
+ labels: string[],
+ task: { status: string; priority: string | null },
+) {
+ const changes = resumeLabelChanges(link, labels);
+ // Prefer a label the task doesn't have, so adding a status label next to
+ // the synced one still changes the task.
+ const status = labels
+ .map((name) => extractIssueStatus([name]))
+ .find((value) => value && value !== task.status);
+ const priority = labels
+ .map((name) => extractIssuePriority([name]))
+ .find((value) => value && value !== task.priority);
+ return {
+ status: changes.statusChanged ? status : undefined,
+ priority: changes.priorityChanged ? priority : undefined,
+ };
+}
diff --git a/apps/api/src/plugins/sync/with-current-issue-labels.ts b/apps/api/src/plugins/sync/with-current-issue-labels.ts
new file mode 100644
index 000000000..910fdc056
--- /dev/null
+++ b/apps/api/src/plugins/sync/with-current-issue-labels.ts
@@ -0,0 +1,29 @@
+import { withSyncLease } from "./lease";
+import { SyncLeaseBusyError } from "./lease-busy-error";
+import { providerIssue } from "./provider-issue";
+
+/**
+ * Label webhooks carry a snapshot that can predate Kaneo's latest label write,
+ * so applying it echoes an old status back. Runs `apply` with the issue's
+ * current labels under the lease that outbound field-label sync holds while it
+ * rewrites them. `labels` is undefined when that sync stays busy: it is
+ * writing a newer Kaneo value over them.
+ */
+export async function withCurrentIssueLabels<T>(
+ integration: { type: string; config: string },
+ link: { id: string; externalId: string; taskId: string },
+ apply: (labels: string[] | undefined) => Promise<T>,
+): Promise<T> {
+ let claimed = false;
+ try {
+ return await withSyncLease(`sync-field-labels:${link.id}`, async () => {
+ claimed = true;
+ return apply(
+ (await (await providerIssue(integration, link)).read()).labels,
+ );
+ });
+ } catch (error) {
+ if (claimed || !(error instanceof SyncLeaseBusyError)) throw error;
+ }
+ return apply(undefined);
+}
diff --git a/tests/api-integration/gitlab-sync-boundaries.test.ts b/tests/api-integration/gitlab-sync-boundaries.test.ts
index 91eac1404..1da7e13ac 100644
--- a/tests/api-integration/gitlab-sync-boundaries.test.ts
+++ b/tests/api-integration/gitlab-sync-boundaries.test.ts
@@ -14,6 +14,7 @@ const mocks = vi.hoisted(() => ({
listIssues: vi.fn(),
listIssueNotes: vi.fn(async () => []),
listMergeRequests: vi.fn(async () => []),
+ getIssue: vi.fn(),
}));
vi.mock(
"../../apps/api/src/plugins/gitlab/utils/gitlab-api",
@@ -215,6 +216,10 @@ describe("GitLab status label snapshots", () => {
.update(schema.taskTable)
.set({ status: "done" })
.where(eq(schema.taskTable.id, task.id));
+ mocks.getIssue.mockResolvedValue({
+ ...remoteIssue,
+ labels: [statusLabel, "bug"],
+ });
await handleGitlabIssueUpdated(
{
object_attributes: {
diff --git a/tests/api-integration/integration-label-echo-loop.test.ts b/tests/api-integration/integration-label-echo-loop.test.ts
new file mode 100644
index 000000000..fc113297d
--- /dev/null
+++ b/tests/api-integration/integration-label-echo-loop.test.ts
@@ -0,0 +1,328 @@
+import { eq } from "drizzle-orm";
+import { beforeEach, expect, it, vi } from "vite-plus/test";
+import db, { schema } from "../../apps/api/src/database";
+import { giteaPlugin } from "../../apps/api/src/plugins/gitea";
+import { handleGiteaIssueLabeled } from "../../apps/api/src/plugins/gitea/webhooks/issue-labeled";
+import { githubPlugin } from "../../apps/api/src/plugins/github";
+import { gitlabPlugin } from "../../apps/api/src/plugins/gitlab";
+import { handleGitlabIssueUpdated } from "../../apps/api/src/plugins/gitlab/webhooks/issue-updated";
+import { handleIssueLabeled } from "../../apps/api/src/plugins/github/webhooks/issue-labeled";
+import { resetTestDatabase } from "./helpers/database";
+import {
+ createProjectFixture,
+ createWorkspaceMember,
+} from "./helpers/fixtures";
+
+type Delivery = {
+ action: string;
+ label: string;
+ labels: string[];
+ previous: string[];
+};
+
+// The provider mock keeps one issue and queues the webhook each label write
+// would trigger, so tests control when and in which order they arrive.
+const mocks = vi.hoisted(() => ({
+ labels: new Set<string>(),
+ deliveries: [] as Delivery[],
+}));
+const names = [
+ "status:to-do",
+ "status:in-progress",
+ "status:in-review",
+ "one",
+ "two",
+];
+function change(action: "labeled" | "unlabeled", name: string) {
+ const previous = [...mocks.labels];
+ if (action === "labeled") mocks.labels.add(name);
+ else mocks.labels.delete(name);
+ mocks.deliveries.push({
+ action,
+ label: name,
+ labels: [...mocks.labels],
+ previous,
+ });
+}
+const issue = () => ({
+ title: "Task",
+ body: "",
+ state: "open",
+ labels: [...mocks.labels].map((name) => ({ name })),
+ updated_at: "2026-10-07T04:00:00Z",
+});
+vi.mock("../../apps/api/src/plugins/github/utils/github-app", () => ({
+ getGithubApp: () => ({}),
+ getVerifiedInstallationOctokit: async () => ({
+ rest: {
+ issues: {
+ get: async () => ({ data: issue() }),
+ getLabel: async () => ({}),
+ removeLabel: async ({ name }: { name: string }) => {
+ if (mocks.labels.has(name)) change("unlabeled", name);
+ },
+ addLabels: async ({ labels }: { labels: string[] }) => {
+ for (const name of labels)
+ if (!mocks.labels.has(name)) change("labeled", name);
+ },
+ },
+ },
+ }),
+}));
+vi.mock("../../apps/api/src/plugins/gitea/utils/gitea-api", () => ({
+ createGiteaClient: () => ({
+ getIssue: async () => issue(),
+ listLabels: async () => names.map((name, id) => ({ name, id: id + 1 })),
+ removeLabelFromIssue: async (
+ _owner: string,
+ _repo: string,
+ _number: number,
+ id: number,
+ ) => {
+ if (mocks.labels.has(names[id - 1]!)) change("unlabeled", names[id - 1]!);
+ },
+ addLabelsToIssue: async (
+ _owner: string,
+ _repo: string,
+ _number: number,
+ ids: number[],
+ ) => {
+ for (const id of ids)
+ if (!mocks.labels.has(names[id - 1]!))
+ change("labeled", names[id - 1]!);
+ },
+ }),
+}));
+vi.mock("../../apps/api/src/plugins/gitlab/utils/gitlab-api", () => ({
+ createGitlabClient: () => ({
+ getIssue: async () => issue(),
+ listLabels: async () => names.map((name, id) => ({ name, id: id + 1 })),
+ // GitLab applies both lists in one request and sends one webhook.
+ updateIssue: async (
+ _project: string,
+ _number: number,
+ body: { add_labels?: string; remove_labels?: string },
+ ) => {
+ const previous = [...mocks.labels];
+ for (const name of body.remove_labels?.split(",") ?? [])
+ mocks.labels.delete(name);
+ for (const name of body.add_labels?.split(",") ?? [])
+ mocks.labels.add(name);
+ mocks.deliveries.push({
+ action: "update",
+ label: "",
+ labels: [...mocks.labels],
+ previous,
+ });
+ return issue();
+ },
+ }),
+}));
+
+beforeEach(async () => {
+ await resetTestDatabase();
+ mocks.labels = new Set(["status:to-do"]);
+ mocks.deliveries = [];
+});
+
+async function setup(provider: "github" | "gitea" | "gitlab") {
+ const { workspace, user } = await createWorkspaceMember();
+ const { project } = await createProjectFixture({ workspaceId: workspace.id });
+ const column = await db.query.columnTable.findFirst({
+ where: (table, { and, eq }) =>
+ and(eq(table.projectId, project.id), eq(table.slug, "to-do")),
+ });
+ const [task] = await db
+ .insert(schema.taskTable)
+ .values({
+ projectId: project.id,
+ number: 1,
+ title: "Task",
+ status: "to-do",
+ columnId: column!.id,
+ })
+ .returning();
+ const config = {
+ baseUrl: "https://git.example",
+ accessToken: "fake-test-token",
+ repositoryOwner: "team",
+ repositoryName: "repo",
+ projectPath: "team/repo",
+ installationId: 1,
+ repositoryId: 2,
+ verifiedGithubAccountId: "3",
+ verifiedByUserId: user.id,
+ commentTaskLinkOnGitHubIssue: false,
+ commentTaskLinkOnGiteaIssue: false,
+ commentTaskLinkOnGitlabIssue: false,
+ };
+ const [integration] = await db
+ .insert(schema.integrationTable)
+ .values({
+ projectId: project.id,
+ type: provider,
+ isActive: true,
+ config: JSON.stringify(config),
+ })
+ .returning();
+ await db.insert(schema.externalLinkTable).values({
+ taskId: task!.id,
+ integrationId: integration!.id,
+ resourceType: "issue",
+ externalId: "1",
+ url: "https://git.example/team/repo/issues/1",
+ });
+ const plugin =
+ provider === "github"
+ ? githubPlugin
+ : provider === "gitea"
+ ? giteaPlugin
+ : gitlabPlugin;
+ const context = {
+ integrationId: integration!.id,
+ projectId: project.id,
+ config,
+ };
+ const status = async () =>
+ (await db.query.taskTable.findFirst({
+ where: eq(schema.taskTable.id, task!.id),
+ }))!.status;
+ // Mirrors the status_changed subscriber: Kaneo writes its new status back.
+ const syncStatus = (oldStatus: string, newStatus: string) =>
+ plugin.onTaskStatusChanged!(
+ {
+ taskId: task!.id,
+ projectId: project.id,
+ userId: null,
+ title: task!.title,
+ oldStatus,
+ newStatus,
+ },
+ context,
+ );
+ const receive = ({ action, label, labels, previous }: Delivery) =>
+ provider === "gitlab"
+ ? handleGitlabIssueUpdated(
+ {
+ object_attributes: {
+ iid: 1,
+ title: "Task",
+ description: "",
+ state: "opened",
+ url: "https://git.example/team/repo/-/issues/1",
+ },
+ changes: {
+ labels: {
+ previous: previous.map((title) => ({ title })),
+ current: labels.map((title) => ({ title })),
+ },
+ },
+ project: {
+ name: "repo",
+ path_with_namespace: "team/repo",
+ web_url: "https://git.example/team/repo",
+ },
+ },
+ integration!.id,
+ )
+ : provider === "github"
+ ? handleIssueLabeled({
+ action,
+ installation: { id: 1 },
+ repository: { id: 2, owner: { login: "team" }, name: "repo" },
+ issue: { number: 1, labels: labels.map((name) => ({ name })) },
+ label: { name: label, color: "6B7280" },
+ })
+ : handleGiteaIssueLabeled(
+ {
+ action: "label_updated",
+ repository: {
+ owner: { login: "team" },
+ name: "repo",
+ html_url: "https://git.example/team/repo",
+ },
+ issue: { number: 1, labels: labels.map((name) => ({ name })) },
+ },
+ integration!.id,
+ );
+ // Deliver queued webhooks and replay the outbound sync after every status
+ // change they cause, as the event bus would. Returns the inbound flips.
+ const drain = async () => {
+ const flips: string[] = [];
+ for (let step = 0; step < 40 && mocks.deliveries.length; step++) {
+ const before = await status();
+ await receive(mocks.deliveries.shift()!);
+ const after = await status();
+ if (after === before) continue;
+ flips.push(after);
+ await syncStatus(before, after);
+ }
+ return flips;
+ };
+ return { task: task!, workspace, status, syncStatus, drain };
+}
+
+it.each(["github", "gitea", "gitlab"] as const)(
+ "%s ignores stale label echoes after Kaneo changes the status (#1956)",
+ async (provider) => {
+ const f = await setup(provider);
+ // Two ordinary labels reach the issue first. Their webhooks still carry
+ // the old status label when they arrive after the status change below.
+ for (const name of ["one", "two"]) {
+ await db.insert(schema.labelTable).values({
+ workspaceId: f.workspace.id,
+ taskId: f.task.id,
+ name,
+ color: "#6B7280",
+ });
+ change("labeled", name);
+ }
+ await db
+ .update(schema.taskTable)
+ .set({ status: "in-progress", columnId: null })
+ .where(eq(schema.taskTable.id, f.task.id));
+ await f.syncStatus("to-do", "in-progress");
+
+ expect(await f.drain()).toEqual([]);
+ expect(mocks.deliveries).toEqual([]);
+ expect(await f.status()).toBe("in-progress");
+ expect(
+ [...mocks.labels].filter((name) => name.startsWith("status:")),
+ ).toEqual(["status:in-progress"]);
+ },
+);
+
+it.each(["github", "gitea", "gitlab"] as const)(
+ "%s ignores an echo that arrives after a newer Kaneo status",
+ async (provider) => {
+ const f = await setup(provider);
+ await db
+ .update(schema.taskTable)
+ .set({ status: "in-progress" })
+ .where(eq(schema.taskTable.id, f.task.id));
+ await f.syncStatus("to-do", "in-progress");
+ await db
+ .update(schema.taskTable)
+ .set({ status: "in-review" })
+ .where(eq(schema.taskTable.id, f.task.id));
+ await f.syncStatus("in-progress", "in-review");
+
+ expect(await f.drain()).toEqual([]);
+ expect(await f.status()).toBe("in-review");
+ },
+);
+
+it.each(["github", "gitea", "gitlab"] as const)(
+ "%s still applies a status label changed on the provider",
+ async (provider) => {
+ const f = await setup(provider);
+ change("unlabeled", "status:to-do");
+ change("labeled", "status:in-review");
+
+ expect(await f.drain()).toEqual(["in-review"]);
+ expect(await f.status()).toBe("in-review");
+ expect(
+ [...mocks.labels].filter((name) => name.startsWith("status:")),
+ ).toEqual(["status:in-review"]);
+ },
+);
diff --git a/tests/api-integration/integration-sync-providers.test.ts b/tests/api-integration/integration-sync-providers.test.ts
index a2266ae29..fa7104851 100644
--- a/tests/api-integration/integration-sync-providers.test.ts
+++ b/tests/api-integration/integration-sync-providers.test.ts
@@ -1241,6 +1241,11 @@ describe.each(["github", "gitea", "gitlab"] as const)(
previous: string[],
added = "new-remote",
) {
+ // Label webhooks resolve fields from the issue's current labels.
+ mocks.read.mockResolvedValue({
+ ...(await mocks.read()),
+ labels: names,
+ });
if (type === "github")
await handleIssueLabeled({
action: "labeled",
diff --git a/tests/api-integration/provider-board-live-updates.test.ts b/tests/api-integration/provider-board-live-updates.test.ts
index 07e463bec..c7f9be453 100644
--- a/tests/api-integration/provider-board-live-updates.test.ts
+++ b/tests/api-integration/provider-board-live-updates.test.ts
@@ -13,6 +13,7 @@ import {
} from "./helpers/fixtures";
const m = vi.hoisted(() => ({
integrations: [] as unknown[],
+ labels: [] as string[],
publish: vi.fn(
async (
_name: string,
@@ -21,6 +22,9 @@ const m = vi.hoisted(() => ({
),
}));
vi.mock("../../apps/api/src/events", () => ({ publishEvent: m.publish }));
+vi.mock("../../apps/api/src/plugins/sync/provider-issue", () => ({
+ providerIssue: async () => ({ read: async () => ({ labels: m.labels }) }),
+}));
vi.mock(
"../../apps/api/src/plugins/github/services/task-service",
async (original) => ({
@@ -163,6 +167,7 @@ it.each([
label,
repository,
};
+ m.labels = payload.issue.labels.map(({ name }) => name);
if (provider === "github") await handleIssueLabeled(payload);
else await handleGiteaIssueLabeled(payload);
}