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): make label field sync idempotent and durable

Tin7732196b5c7f
diff --git a/apps/api/src/plugins/gitea/webhooks/issue-labeled.ts b/apps/api/src/plugins/gitea/webhooks/issue-labeled.ts
index 0e064f234..33722a796 100644
--- a/apps/api/src/plugins/gitea/webhooks/issue-labeled.ts
+++ b/apps/api/src/plugins/gitea/webhooks/issue-labeled.ts
@@ -1,6 +1,5 @@
-import { changedLabelFields } from "../../sync/changed-label-fields";
import { resumeLabelChanges } from "../../sync/resume-label-changes";
-import { withCurrentIssueLabels } from "../../sync/with-current-issue-labels";
+import { syncLabelFieldsFromIssue } from "../../sync/sync-label-fields-from-issue";
import { acceptsIssue, readSyncRules } from "../../sync/rules";
import { handleGiteaIssueOpened } from "./issue-opened";
import { withIntegrationLink } from "../../github/services/with-integration-link";
@@ -9,13 +8,12 @@ import {
linkedTaskScope,
} from "../../github/services/integration-task-scope";
import { eq, inArray } from "drizzle-orm";
-import { labelTable, taskTable } from "../../../database/schema";
+import { labelTable } from "../../../database/schema";
import { publishEvent } from "../../../events";
import {
findExternalLink,
updateExternalLink,
} from "../../github/services/link-manager";
-import { updateTaskStatus } from "../../github/services/task-service";
import {
findAllIntegrationsByGiteaRepo,
repoOwnerLogin,
@@ -173,189 +171,121 @@ export async function handleGiteaIssueLabeled(
continue;
}
- 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)
- : {};
+ const fieldEvent = !addedLabel || isSystemLabelName(addedLabel.name);
+ // label_updated has no single label, so it always reads the issue.
+ // Status and priority never come from this payload's label snapshot.
+ if (fieldEvent) await syncLabelFieldsFromIssue(integration, existingLink);
- if (priority) {
- await db
- .update(taskTable)
- .set({ priority })
- .where(
- linkedTaskScope(existingLink.taskId, integration.projectId),
- );
+ 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,
+ );
+ if (payload.action === "label_updated") {
+ if (issue.labels === undefined) {
+ return;
}
- if (status) {
- const statusResult = await updateTaskStatus(
+ const task = await db.query.taskTable.findFirst({
+ where: linkedTaskScope(
+ existingLink.taskId,
+ integration.projectId,
+ ),
+ with: {
+ project: true,
+ },
+ });
+ if (task?.project?.workspaceId) {
+ await syncGiteaLabelsToTask(
existingLink.taskId,
- status,
+ task.project.workspaceId,
+ giteaLabelsForSync(issue.labels),
db,
+ changes.baseline,
+ );
+ afterCommit(() =>
+ publishEvent("task.labels_updated", {
+ projectId: integration.projectId,
+ taskId: existingLink.taskId,
+ }),
);
- 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) {
- 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;
- }
-
- if (!addedLabel) {
- if (priority)
- afterCommit(() =>
- publishEvent("task.updated", {
- projectId: integration.projectId,
- taskId: existingLink.taskId,
- }),
- );
- return;
}
+ return;
+ }
- if (isSystemLabelName(addedLabel.name)) {
- if (priority)
- afterCommit(() =>
- publishEvent("task.updated", {
- projectId: integration.projectId,
- taskId: existingLink.taskId,
- }),
- );
- return;
- }
+ if (!addedLabel || fieldEvent) 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: e }) =>
- and(
- e(table.workspaceId, task.project.workspaceId),
- 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],
- });
- }
- }
- }
+ if (payload.action === "labeled") {
+ const task = await db.query.taskTable.findFirst({
+ where: linkedTaskScope(
+ existingLink.taskId,
+ integration.projectId,
+ ),
+ with: {
+ project: true,
+ },
+ });
- if (payload.action === "unlabeled") {
- const labelsToDelete = await db.query.labelTable.findMany({
+ if (task?.project?.workspaceId) {
+ const existingLabel = await db.query.labelTable.findFirst({
where: (table, { and, eq: e }) =>
and(
- e(table.taskId, existingLink.taskId),
+ e(table.workspaceId, task.project.workspaceId),
e(table.name, addedLabel.name),
+ e(table.taskId, task.id),
),
});
- for (const label of labelsToDelete) {
- await db.delete(labelTable).where(eq(labelTable.id, label.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],
+ });
}
}
- 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());
+ 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),
+ ),
+ });
+
+ 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,
+ }),
+ );
+ },
+ );
} 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 f59bf0a8e..baf8d559e 100644
--- a/apps/api/src/plugins/github/webhooks/issue-labeled.ts
+++ b/apps/api/src/plugins/github/webhooks/issue-labeled.ts
@@ -1,18 +1,14 @@
-import { changedLabelFields } from "../../sync/changed-label-fields";
import { resumeLabelChanges } from "../../sync/resume-label-changes";
-import { withCurrentIssueLabels } from "../../sync/with-current-issue-labels";
+import { syncLabelFieldsFromIssue } from "../../sync/sync-label-fields-from-issue";
import { acceptsIssue, readSyncRules } from "../../sync/rules";
import { handleIssueOpened } from "./issue-opened";
import { withIntegrationLink } from "../services/with-integration-link";
import { linkedTaskScope } from "../services/integration-task-scope";
import { eq } from "drizzle-orm";
-import { labelTable, taskTable } from "../../../database/schema";
+import { labelTable } from "../../../database/schema";
import { publishEvent } from "../../../events";
import { findExternalLink, updateExternalLink } from "../services/link-manager";
-import {
- findAllIntegrationsByRepo,
- updateTaskStatus,
-} from "../services/task-service";
+import { findAllIntegrationsByRepo } from "../services/task-service";
type IssueLabeledPayload = {
action: string;
@@ -62,153 +58,90 @@ export async function handleIssueLabeled(payload: IssueLabeledPayload) {
continue;
}
- const names = (issue.labels ?? []).flatMap((label) => {
- const name = typeof label === "string" ? label : label.name;
- return name ? [name] : [];
- });
- const systemEvent =
+ const fieldEvent =
!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 (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 (!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({
+ // Other label events skip the provider read; status and priority come
+ // only from the issue's current labels, never from this snapshot.
+ if (fieldEvent) await syncLabelFieldsFromIssue(integration, existingLink);
+
+ 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,
+ );
+ if (!addedLabel || fieldEvent) 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.taskId, existingLink.taskId),
+ eq(table.workspaceId, task.project.workspaceId),
eq(table.name, addedLabel.name),
+ eq(table.taskId, task.id),
),
});
- for (const label of labelsToDelete) {
- await db.delete(labelTable).where(eq(labelTable.id, label.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.taskId, existingLink.taskId),
+ eq(table.name, addedLabel.name),
+ ),
+ });
- afterCommit(() =>
- publishEvent("task.labels_updated", {
- projectId: integration.projectId,
- taskId: existingLink.taskId,
- }),
- );
- return;
- },
- );
+ for (const label of labelsToDelete) {
+ await db.delete(labelTable).where(eq(labelTable.id, label.id));
+ }
+ }
- // 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());
+ afterCommit(() =>
+ publishEvent("task.labels_updated", {
+ projectId: integration.projectId,
+ taskId: existingLink.taskId,
+ }),
+ );
+ return;
+ },
+ );
}
}
diff --git a/apps/api/src/plugins/gitlab/webhooks/issue-updated.ts b/apps/api/src/plugins/gitlab/webhooks/issue-updated.ts
index 5a4b8d9d5..85ebe2b4d 100644
--- a/apps/api/src/plugins/gitlab/webhooks/issue-updated.ts
+++ b/apps/api/src/plugins/gitlab/webhooks/issue-updated.ts
@@ -1,6 +1,4 @@
-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";
@@ -16,6 +14,10 @@ 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 {
@@ -187,165 +189,157 @@ export async function handleGitlabIssueUpdated(
continue;
}
- 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;
- }
-
- let metadata: LinkMetadata = parseLinkSyncMetadata(
- externalLink.metadata,
- { externalLinkId: externalLink.id, field: "issue" },
- );
+ 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 (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,
+ };
+ }
+ if (changes?.description) {
+ // Kaneo recorded the body with its footer, so compare the raw body.
+ const issueBody = issue.description ?? "";
if (
- changes?.title &&
- !isEchoOf(metadata.lastSync?.title, "kaneo", issue.title)
+ !isEchoOf(metadata.lastSync?.description, "kaneo", issueBody)
) {
- updateData.title = issue.title;
- lastSync.title = {
+ const description = taskDescriptionFromIssue(issue.description);
+ updateData.description = description;
+ lastSync.description = {
timestamp: now,
source: "gitlab",
- value: issue.title,
+ value: description,
};
}
-
- 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 (!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) {
+ if (Object.keys(updateData).length > 0) {
await db
.update(taskTable)
- .set({ priority })
+ .set(updateData)
.where(linkedTaskScope(task.id, integration.projectId));
- }
- 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",
- }),
- );
- }
- }
+ metadata = { ...metadata, lastSync };
- if (task.project?.workspaceId) {
- await syncGitlabLabelsToTask(
- task.id,
- task.project.workspaceId,
- nonSystemLabels(currentLabels),
- changes?.labels?.previous,
+ await updateExternalLink(
+ externalLink.id,
+ {
+ title: issue.title,
+ metadata,
+ },
db,
- labelChanges.baseline,
);
afterCommit(() =>
- publishEvent("task.labels_updated", {
+ publishEvent("task.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",
}),
);
}
- },
- );
-
- // 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());
+ }
+
+ 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,
+ }),
+ );
+ }
+ },
+ );
} 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.test.ts b/apps/api/src/plugins/sync/changed-label-fields.test.ts
new file mode 100644
index 000000000..9d5b6b78d
--- /dev/null
+++ b/apps/api/src/plugins/sync/changed-label-fields.test.ts
@@ -0,0 +1,59 @@
+import { expect, it } from "vite-plus/test";
+import { changedLabelFields } from "./changed-label-fields";
+
+const link = { id: "link", metadata: null };
+const task = { status: "to-do", priority: "low" };
+
+it("ignores labels already confirmed on the provider", () => {
+ const known = ["status:to-do", "priority:low"];
+ expect(changedLabelFields(link, known, known, task)).toEqual({
+ status: undefined,
+ priority: undefined,
+ });
+ expect(
+ changedLabelFields(link, ["status:in-review"], ["status:in-review"], task),
+ ).toEqual({ status: undefined, priority: undefined });
+});
+
+it("applies only labels added since the last confirmation", () => {
+ expect(
+ changedLabelFields(
+ link,
+ ["priority:low", "status:to-do", "status:in-review"],
+ ["priority:low", "status:to-do"],
+ task,
+ ),
+ ).toEqual({ status: "in-review", priority: undefined });
+ expect(
+ changedLabelFields(
+ link,
+ ["priority:high", "status:to-do"],
+ ["priority:low", "status:to-do"],
+ { status: "done", priority: "low" },
+ ),
+ ).toEqual({ status: undefined, priority: "high" });
+});
+
+it("falls back to the task value without a confirmation", () => {
+ expect(
+ changedLabelFields(
+ link,
+ ["status:to-do", "status:in-review"],
+ undefined,
+ task,
+ ),
+ ).toEqual({ status: "in-review", priority: undefined });
+});
+
+it("keeps fields unchanged since a resume", () => {
+ const resumed = {
+ id: "link",
+ metadata: JSON.stringify({ syncResumeLabelBaseline: ["status:to-do"] }),
+ };
+ expect(
+ changedLabelFields(resumed, ["status:to-do"], undefined, {
+ status: "planned",
+ priority: null,
+ }),
+ ).toEqual({ status: undefined, priority: undefined });
+});
diff --git a/apps/api/src/plugins/sync/changed-label-fields.ts b/apps/api/src/plugins/sync/changed-label-fields.ts
index fe3efb0ec..5d7c869d4 100644
--- a/apps/api/src/plugins/sync/changed-label-fields.ts
+++ b/apps/api/src/plugins/sync/changed-label-fields.ts
@@ -4,23 +4,36 @@ import {
} 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 const isFieldLabel = (name: string) =>
+ name.startsWith("status:") || name.startsWith("priority:");
+
+// Links synced before `known` was recorded fall back to every current label.
+const added = (labels: string[], known: string[] | undefined, prefix: string) =>
+ labels.filter(
+ (name) => name.startsWith(prefix) && !(known ?? []).includes(name),
+ );
+
+/**
+ * Status and priority set by the issue's current labels. `known` holds the
+ * field labels last confirmed on the provider; only labels added since then
+ * count, so echoes and redeliveries of the same labels change nothing.
+ */
export function changedLabelFields(
link: { id: string; metadata: string | null },
labels: string[],
+ known: string[] | undefined,
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,
- };
+ const resumed = resumeLabelChanges(link, labels);
+ const status = resumed.statusChanged
+ ? added(labels, known, "status:")
+ .map((name) => extractIssueStatus([name]))
+ .find((value) => value && value !== task.status)
+ : undefined;
+ const priority = resumed.priorityChanged
+ ? added(labels, known, "priority:")
+ .map((name) => extractIssuePriority([name]))
+ .find((value) => value && value !== task.priority)
+ : undefined;
+ return { status: status ?? undefined, priority: priority ?? undefined };
}
diff --git a/apps/api/src/plugins/sync/replay-deferred-label-fields.ts b/apps/api/src/plugins/sync/replay-deferred-label-fields.ts
new file mode 100644
index 000000000..0718af2c1
--- /dev/null
+++ b/apps/api/src/plugins/sync/replay-deferred-label-fields.ts
@@ -0,0 +1,59 @@
+import { and, asc, gt, sql } from "drizzle-orm";
+import db from "../../database";
+import { externalLinkTable } from "../../database/schema";
+import { withJobLease } from "../../scheduler/leader-lock";
+import { updateExternalLink } from "../github/services/link-manager";
+import { canSyncTask } from "./eligibility";
+import { syncLabelFieldsFromIssue } from "./sync-label-fields-from-issue";
+
+const BATCH = 20;
+let cursor: string | undefined;
+
+/** Replays label reads that a webhook delivery could not finish. */
+export function replayDeferredLabelFields() {
+ return withJobLease(
+ "deferred-label-fields",
+ replayClaimedLabelFields,
+ () => ({}),
+ );
+}
+
+async function replayClaimedLabelFields() {
+ let degraded = false;
+ const links = await db.query.externalLinkTable.findMany({
+ where: and(
+ sql`${externalLinkTable.resourceType} = 'issue' AND ${externalLinkTable.metadata} LIKE '%"syncLabelFieldsDeferred":"%'`,
+ cursor ? gt(externalLinkTable.id, cursor) : undefined,
+ ),
+ with: { integration: true },
+ orderBy: asc(externalLinkTable.id),
+ limit: BATCH,
+ });
+ // A short batch reached the end; the next run starts from the first link.
+ cursor = links.length === BATCH ? links.at(-1)!.id : undefined;
+ for (const link of links) {
+ const integration = link.integration;
+ try {
+ if (
+ !integration?.isActive ||
+ !["github", "gitea"].includes(integration.type) ||
+ !(await canSyncTask(
+ link.taskId,
+ integration.id,
+ undefined,
+ integration.config,
+ ))
+ ) {
+ await updateExternalLink(link.id, {
+ metadata: { syncLabelFieldsDeferred: null },
+ });
+ continue;
+ }
+ await syncLabelFieldsFromIssue(integration, link);
+ } catch {
+ degraded = true;
+ console.error("Deferred issue label replay failed", { linkId: link.id });
+ }
+ }
+ return { degraded };
+}
diff --git a/apps/api/src/plugins/sync/sync-label-fields-from-issue.ts b/apps/api/src/plugins/sync/sync-label-fields-from-issue.ts
new file mode 100644
index 000000000..fa158f325
--- /dev/null
+++ b/apps/api/src/plugins/sync/sync-label-fields-from-issue.ts
@@ -0,0 +1,168 @@
+import { randomUUID } from "node:crypto";
+import { setTimeout as delay } from "node:timers/promises";
+import { eq } from "drizzle-orm";
+import db from "../../database";
+import { externalLinkTable, taskTable } from "../../database/schema";
+import { publishEvent } from "../../events";
+import { linkedTaskScope } from "../github/services/integration-task-scope";
+import { updateExternalLink } from "../github/services/link-manager";
+import { updateTaskStatus } from "../github/services/task-service";
+import { withIntegrationLink } from "../github/services/with-integration-link";
+import { parseLinkMetadata } from "../github/utils/parse-link-metadata";
+import { changedLabelFields, isFieldLabel } from "./changed-label-fields";
+import { withSyncLease } from "./lease";
+import { SyncLeaseBusyError } from "./lease-busy-error";
+import { providerIssue } from "./provider-issue";
+import { isTransientProviderError } from "./transient-provider-error";
+
+type Integration = {
+ id: string;
+ projectId: string;
+ type: string;
+ config: string;
+};
+type Link = { id: string; taskId: string; externalId: string };
+type Metadata = {
+ syncFieldLabels?: unknown;
+ syncLabelFieldsDeferred?: unknown;
+};
+
+const metadataOf = (link: { id: string; metadata: string | null }) =>
+ parseLinkMetadata<Metadata>(link.metadata, {
+ externalLinkId: link.id,
+ source: "label_fields",
+ });
+
+async function readLabels(integration: Integration, link: Link) {
+ for (let attempt = 1; ; attempt++) {
+ try {
+ return (await (await providerIssue(integration, link)).read()).labels;
+ } catch (error) {
+ if (attempt === 3 || !isTransientProviderError(error)) throw error;
+ await delay(250 * attempt);
+ }
+ }
+}
+
+async function applyLabelFields(
+ integration: Integration,
+ link: Link,
+ labels: string[],
+ deferred: unknown,
+) {
+ await withIntegrationLink(
+ link,
+ integration,
+ async (tx, afterCommit, link) => {
+ const task = await tx.query.taskTable.findFirst({
+ where: linkedTaskScope(link.taskId, integration.projectId),
+ columns: { status: true, priority: true },
+ });
+ if (!task) return;
+ const metadata = metadataOf(link);
+ const known = Array.isArray(metadata.syncFieldLabels)
+ ? metadata.syncFieldLabels.filter((name) => typeof name === "string")
+ : undefined;
+ const { status, priority } = changedLabelFields(
+ link,
+ labels,
+ known,
+ task,
+ );
+ await updateExternalLink(
+ link.id,
+ {
+ metadata: {
+ syncFieldLabels: labels.filter(isFieldLabel),
+ // A delivery deferred after this read began still needs its own.
+ ...(deferred && metadata.syncLabelFieldsDeferred === deferred
+ ? { syncLabelFieldsDeferred: null }
+ : {}),
+ },
+ },
+ tx,
+ );
+
+ if (priority) {
+ await tx
+ .update(taskTable)
+ .set({ priority })
+ .where(linkedTaskScope(link.taskId, integration.projectId));
+ afterCommit(() =>
+ publishEvent("task.updated", {
+ projectId: integration.projectId,
+ taskId: link.taskId,
+ }),
+ );
+ }
+
+ if (status) {
+ const result = await updateTaskStatus(link.taskId, status, tx);
+ if (result.applied && result.before.status !== result.after.status)
+ afterCommit(() =>
+ publishEvent("task.status_changed", {
+ taskId: result.after.id,
+ projectId: result.after.projectId,
+ userId: null,
+ oldStatus: result.before.status,
+ newStatus: result.after.status,
+ title: result.after.title,
+ assigneeId: result.after.userId,
+ type: "status_changed",
+ }),
+ );
+ }
+ },
+ );
+}
+
+/**
+ * Applies status and priority from the issue's current labels. Webhook label
+ * snapshots can predate Kaneo's latest write, so applying them echoed old
+ * values back (#1956). Reads under the lease outbound field-label sync holds
+ * while it rewrites labels. When that lease stays busy or the provider fails
+ * transiently, the scheduler replays the read instead of dropping it.
+ */
+export async function syncLabelFieldsFromIssue(
+ integration: Integration,
+ link: Link,
+) {
+ let defer = false;
+ try {
+ await withSyncLease(`sync-field-labels:${link.id}`, async () => {
+ const stored = await db.query.externalLinkTable.findFirst({
+ where: eq(externalLinkTable.id, link.id),
+ columns: { id: true, metadata: true },
+ });
+ if (!stored) return;
+ const deferred = metadataOf(stored).syncLabelFieldsDeferred;
+ let labels: string[];
+ try {
+ labels = await readLabels(integration, link);
+ } catch (error) {
+ if (isTransientProviderError(error)) {
+ defer = true;
+ return;
+ }
+ console.error("Issue labels could not be read", {
+ integrationId: integration.id,
+ linkId: link.id,
+ });
+ // Replaying a permanent failure cannot succeed.
+ if (deferred)
+ await updateExternalLink(link.id, {
+ metadata: { syncLabelFieldsDeferred: null },
+ });
+ return;
+ }
+ await applyLabelFields(integration, link, labels, deferred);
+ });
+ } catch (error) {
+ if (!(error instanceof SyncLeaseBusyError)) throw error;
+ defer = true;
+ }
+ if (defer)
+ await updateExternalLink(link.id, {
+ metadata: { syncLabelFieldsDeferred: randomUUID() },
+ });
+}
diff --git a/apps/api/src/plugins/sync/sync-task-field-labels.ts b/apps/api/src/plugins/sync/sync-task-field-labels.ts
index a40ec82d1..c67f4bd4d 100644
--- a/apps/api/src/plugins/sync/sync-task-field-labels.ts
+++ b/apps/api/src/plugins/sync/sync-task-field-labels.ts
@@ -7,6 +7,7 @@ import { parseLinkMetadata } from "../github/utils/parse-link-metadata";
import type { PluginContext } from "../types";
import { createIssueWrite } from "./dispatch-issue-write";
import { canSyncTask } from "./eligibility";
+import { isFieldLabel } from "./changed-label-fields";
import type { IssueWrite } from "./issue-write";
import { taskIssueLabels } from "./issue-labels";
import { withSyncLease } from "./lease";
@@ -75,25 +76,40 @@ export async function syncTaskFieldLabels(
if (!stored) return;
const metadata = parseLinkMetadata<{
syncResumeLabelBaseline?: string[];
+ syncFieldLabels?: string[];
}>(stored.metadata, {
externalLinkId: link.id,
source: "outbound_field_labels",
});
- if (Array.isArray(metadata.syncResumeLabelBaseline))
- await updateExternalLink(link.id, {
- metadata: {
- syncResumeLabelBaseline: [
- ...new Set([
- ...metadata.syncResumeLabelBaseline.filter(
- (name) =>
- typeof name === "string" &&
- !prefixes.some((prefix) => name.startsWith(prefix)),
+ const replace = (names: string[], added: string[]) => [
+ ...new Set([
+ ...names.filter(
+ (name) =>
+ typeof name === "string" &&
+ !prefixes.some((prefix) => name.startsWith(prefix)),
+ ),
+ ...added,
+ ]),
+ ];
+ await updateExternalLink(link.id, {
+ metadata: {
+ // Inbound label webhooks ignore field labels Kaneo confirmed here.
+ syncFieldLabels: replace(
+ Array.isArray(metadata.syncFieldLabels)
+ ? metadata.syncFieldLabels
+ : labels.filter(isFieldLabel),
+ add.filter(isFieldLabel),
+ ),
+ ...(Array.isArray(metadata.syncResumeLabelBaseline)
+ ? {
+ syncResumeLabelBaseline: replace(
+ metadata.syncResumeLabelBaseline,
+ add,
),
- ...add,
- ]),
- ],
- },
- });
+ }
+ : {}),
+ },
+ });
const current = await db.query.taskTable.findFirst({
where: linkedTaskScope(taskId, context.projectId),
columns: { priority: true, status: true },
diff --git a/apps/api/src/plugins/sync/transient-provider-error.test.ts b/apps/api/src/plugins/sync/transient-provider-error.test.ts
new file mode 100644
index 000000000..92c4d5e9d
--- /dev/null
+++ b/apps/api/src/plugins/sync/transient-provider-error.test.ts
@@ -0,0 +1,22 @@
+import { expect, it } from "vite-plus/test";
+import { isTransientProviderError } from "./transient-provider-error";
+
+const http = (status: number, headers: Record<string, string> = {}) =>
+ Object.assign(new Error("HTTP"), { status, response: { headers } });
+
+it.each([
+ [http(408), true],
+ [http(429), true],
+ [http(502), true],
+ [http(403, { "x-ratelimit-remaining": "0" }), true],
+ [http(403, { "retry-after": "30" }), true],
+ [new TypeError("fetch failed"), true],
+ [Object.assign(new Error("aborted"), { name: "AbortError" }), true],
+ [http(403), false],
+ [http(404), false],
+ [http(401), false],
+ [new Error("GitHub repository identity changed"), false],
+ [undefined, false],
+])("classifies %o as transient: %s", (error, transient) => {
+ expect(isTransientProviderError(error)).toBe(transient);
+});
diff --git a/apps/api/src/plugins/sync/transient-provider-error.ts b/apps/api/src/plugins/sync/transient-provider-error.ts
new file mode 100644
index 000000000..ff54cf9cd
--- /dev/null
+++ b/apps/api/src/plugins/sync/transient-provider-error.ts
@@ -0,0 +1,23 @@
+type ProviderError = {
+ name?: unknown;
+ status?: unknown;
+ response?: { headers?: Record<string, unknown> };
+};
+
+/** Timeouts, network failures, rate limits and 5xx responses may succeed later. */
+export function isTransientProviderError(error: unknown) {
+ if (!error || typeof error !== "object") return false;
+ const { name, status, response } = error as ProviderError;
+ if (typeof status !== "number")
+ return ["AbortError", "TimeoutError", "TypeError"].includes(String(name));
+ const headers = response?.headers ?? {};
+ return (
+ status === 408 ||
+ status === 429 ||
+ status >= 500 ||
+ // GitHub reports exhausted and secondary rate limits as 403.
+ (status === 403 &&
+ (headers["x-ratelimit-remaining"] === "0" ||
+ headers["retry-after"] !== 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
deleted file mode 100644
index 910fdc056..000000000
--- a/apps/api/src/plugins/sync/with-current-issue-labels.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-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/apps/api/src/scheduler/index.ts b/apps/api/src/scheduler/index.ts
index 0ecbd9226..ad32fb771 100644
--- a/apps/api/src/scheduler/index.ts
+++ b/apps/api/src/scheduler/index.ts
@@ -1,6 +1,7 @@
import { retryStorageCleanup } from "../storage/cleanup-queue";
import { cleanupDraftUploads } from "./draft-upload-cleanup";
import { replayDeferredIssueEdits } from "../plugins/github/services/deferred-issue-edits";
+import { replayDeferredLabelFields } from "../plugins/sync/replay-deferred-label-fields";
import * as Sentry from "@sentry/node";
import { Cron } from "croner";
import { checkDueDateReminders } from "./due-date-reminders";
@@ -54,6 +55,13 @@ export function initializeScheduler(): void {
withCheckIn("deferred-issue-edits", replayDeferredIssueEdits),
),
);
+ jobs.push(
+ new Cron(
+ "* * * * *",
+ { protect: true },
+ withCheckIn("deferred-label-fields", replayDeferredLabelFields),
+ ),
+ );
jobs.push(
new Cron(
"*/5 * * * *",
diff --git a/tests/api-integration/gitlab-sync-boundaries.test.ts b/tests/api-integration/gitlab-sync-boundaries.test.ts
index 1da7e13ac..91eac1404 100644
--- a/tests/api-integration/gitlab-sync-boundaries.test.ts
+++ b/tests/api-integration/gitlab-sync-boundaries.test.ts
@@ -14,7 +14,6 @@ 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",
@@ -216,10 +215,6 @@ 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
index fc113297d..75a9d1026 100644
--- a/tests/api-integration/integration-label-echo-loop.test.ts
+++ b/tests/api-integration/integration-label-echo-loop.test.ts
@@ -1,56 +1,62 @@
import { eq } from "drizzle-orm";
-import { beforeEach, expect, it, vi } from "vite-plus/test";
+import { beforeAll, 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 {
+ broadcastTaskStatusChanged,
+ registerPlugin,
+} from "../../apps/api/src/plugins/registry";
+import { replayDeferredLabelFields } from "../../apps/api/src/plugins/sync/replay-deferred-label-fields";
+import type { TaskStatusChangedEvent } from "../../apps/api/src/plugins/types";
import { resetTestDatabase } from "./helpers/database";
import {
createProjectFixture,
createWorkspaceMember,
} from "./helpers/fixtures";
-type Delivery = {
- action: string;
- label: string;
- labels: string[];
- previous: string[];
-};
+type Delivery = { action: string; label: string; labels: 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[],
+ events: [] as Array<{ name: string; data: unknown }>,
+ readFailures: [] as unknown[],
+}));
+vi.mock("../../apps/api/src/events", () => ({
+ publishEvent: async (name: string, data: unknown) => {
+ mocks.events.push({ name, data });
+ },
}));
const names = [
"status:to-do",
"status:in-progress",
"status:in-review",
+ "priority:low",
+ "priority:high",
"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,
- });
+ mocks.deliveries.push({ action, label: name, labels: [...mocks.labels] });
}
-const issue = () => ({
- title: "Task",
- body: "",
- state: "open",
- labels: [...mocks.labels].map((name) => ({ name })),
- updated_at: "2026-10-07T04:00:00Z",
-});
+const issue = () => {
+ const failure = mocks.readFailures.shift();
+ if (failure) throw failure;
+ return {
+ 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 () => ({
@@ -93,68 +99,37 @@ vi.mock("../../apps/api/src/plugins/gitea/utils/gitea-api", () => ({
},
}),
}));
-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();
- },
- }),
-}));
+beforeAll(() => {
+ registerPlugin(githubPlugin);
+ registerPlugin(giteaPlugin);
+});
beforeEach(async () => {
await resetTestDatabase();
mocks.labels = new Set(["status:to-do"]);
mocks.deliveries = [];
+ mocks.events = [];
+ mocks.readFailures = [];
});
-async function setup(provider: "github" | "gitea" | "gitlab") {
+async function setup(provider: "github" | "gitea", metadata = {}) {
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,
- })
+ .values({ projectId: project.id, number: 1, title: "Task" })
.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)
@@ -165,104 +140,96 @@ async function setup(provider: "github" | "gitea" | "gitlab") {
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 () =>
+ const [link] = await db
+ .insert(schema.externalLinkTable)
+ .values({
+ taskId: task!.id,
+ integrationId: integration!.id,
+ resourceType: "issue",
+ externalId: "1",
+ url: "https://git.example/team/repo/issues/1",
+ metadata: JSON.stringify(metadata),
+ })
+ .returning();
+ const current = 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 status = async () => (await current()).status;
+ const metadataOf = async () =>
+ JSON.parse(
+ (await db.query.externalLinkTable.findFirst({
+ where: eq(schema.externalLinkTable.id, link!.id),
+ }))!.metadata!,
);
- const receive = ({ action, label, labels, previous }: Delivery) =>
- provider === "gitlab"
- ? handleGitlabIssueUpdated(
+ // A Kaneo user edit: the API commits it and broadcasts the event.
+ const edit = async (newStatus: string) => {
+ const oldStatus = await status();
+ await db
+ .update(schema.taskTable)
+ .set({ status: newStatus })
+ .where(eq(schema.taskTable.id, task!.id));
+ await broadcastTaskStatusChanged({
+ taskId: task!.id,
+ projectId: project.id,
+ userId: user.id,
+ title: task!.title,
+ oldStatus,
+ newStatus,
+ });
+ };
+ const receive = ({ action, label, labels }: Delivery) =>
+ 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(
{
- 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: {
+ action: "label_updated",
+ repository: {
+ owner: { login: "team" },
name: "repo",
- path_with_namespace: "team/repo",
- web_url: "https://git.example/team/repo",
+ html_url: "https://git.example/team/repo",
},
+ issue: { number: 1, labels: labels.map((name) => ({ name })) },
},
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.
+ );
+ // Deliver queued webhooks and pass the status events they publish to the
+ // real broadcaster, as the event bus would. Returns the inbound changes.
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);
+ for (const { name, data } of mocks.events.splice(0))
+ if (name === "task.status_changed") {
+ const event = data as TaskStatusChangedEvent;
+ flips.push(event.newStatus);
+ await broadcastTaskStatusChanged(event);
+ }
}
return flips;
};
- return { task: task!, workspace, status, syncStatus, drain };
+ return {
+ task: task!,
+ link: link!,
+ workspace,
+ current,
+ status,
+ metadataOf,
+ edit,
+ receive,
+ drain,
+ };
}
+const statusLabels = () =>
+ [...mocks.labels].filter((name) => name.startsWith("status:"));
-it.each(["github", "gitea", "gitlab"] as const)(
+it.each(["github", "gitea"] as const)(
"%s ignores stale label echoes after Kaneo changes the status (#1956)",
async (provider) => {
const f = await setup(provider);
@@ -277,42 +244,29 @@ it.each(["github", "gitea", "gitlab"] as const)(
});
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");
+ await f.edit("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"]);
+ expect(statusLabels()).toEqual(["status:in-progress"]);
},
);
-it.each(["github", "gitea", "gitlab"] as const)(
+it.each(["github", "gitea"] 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");
+ await f.edit("in-progress");
+ await f.edit("in-review");
expect(await f.drain()).toEqual([]);
expect(await f.status()).toBe("in-review");
+ expect(statusLabels()).toEqual(["status:in-review"]);
},
);
-it.each(["github", "gitea", "gitlab"] as const)(
+it.each(["github", "gitea"] as const)(
"%s still applies a status label changed on the provider",
async (provider) => {
const f = await setup(provider);
@@ -321,8 +275,111 @@ it.each(["github", "gitea", "gitlab"] as const)(
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"]);
+ expect(statusLabels()).toEqual(["status:in-review"]);
+ },
+);
+
+it.each(["github", "gitea"] as const)(
+ "%s keeps one value when the same conflicting labels are redelivered",
+ async (provider) => {
+ const f = await setup(provider);
+ change("labeled", "status:in-review");
+ const delivery = mocks.deliveries.shift()!;
+ // No broadcaster: the conflicting labels stay on the issue.
+ await f.receive(delivery);
+ expect(await f.status()).toBe("in-review");
+ await f.receive(delivery);
+ expect(await f.status()).toBe("in-review");
+ },
+);
+
+it.each(["github", "gitea"] as const)(
+ "%s leaves status alone when only priority labels change",
+ async (provider) => {
+ mocks.labels = new Set(["status:to-do", "priority:low"]);
+ const f = await setup(provider, {
+ syncFieldLabels: ["status:to-do", "priority:low"],
+ });
+ // A provider close moved the task to done without a status label edit.
+ await db
+ .update(schema.taskTable)
+ .set({ status: "done", priority: "low" })
+ .where(eq(schema.taskTable.id, f.task.id));
+ change("labeled", "priority:high");
+ await f.receive(mocks.deliveries.shift()!);
+
+ expect(await f.current()).toMatchObject({
+ status: "done",
+ priority: "high",
+ });
+ },
+);
+
+it.each(["github", "gitea"] as const)(
+ "%s replays a provider change when the label lease stays busy",
+ async (provider) => {
+ const f = await setup(provider);
+ const lease = `sync-field-labels:${f.link.id}`;
+ await db.insert(schema.jobLeaseTable).values({
+ name: lease,
+ owner: "slow-reader",
+ expiresAt: new Date(Date.now() + 60_000),
+ });
+ change("unlabeled", "status:to-do");
+ change("labeled", "status:in-review");
+ await f.receive(mocks.deliveries.pop()!);
+ expect(await f.status()).toBe("to-do");
+ expect((await f.metadataOf()).syncLabelFieldsDeferred).toEqual(
+ expect.any(String),
+ );
+
+ await db
+ .delete(schema.jobLeaseTable)
+ .where(eq(schema.jobLeaseTable.name, lease));
+ await replayDeferredLabelFields();
+ expect(await f.status()).toBe("in-review");
+ expect((await f.metadataOf()).syncLabelFieldsDeferred).toBeNull();
+ },
+ 15_000,
+);
+
+it.each(["github", "gitea"] as const)(
+ "%s retries transient read failures, then defers them",
+ async (provider) => {
+ const f = await setup(provider);
+ const unavailable = Object.assign(new Error("unavailable"), {
+ status: 503,
+ });
+ mocks.readFailures = [unavailable, unavailable];
+ change("labeled", "status:in-review");
+ await f.receive(mocks.deliveries.shift()!);
+ expect(await f.status()).toBe("in-review");
+ expect((await f.metadataOf()).syncLabelFieldsDeferred).toBeUndefined();
+
+ mocks.readFailures = [unavailable, unavailable, unavailable];
+ change("unlabeled", "status:in-review");
+ change("labeled", "status:in-progress");
+ await f.receive(mocks.deliveries.pop()!);
+ expect(await f.status()).toBe("in-review");
+ await replayDeferredLabelFields();
+ expect(await f.status()).toBe("in-progress");
},
);
+
+it("gitea still syncs ordinary labels when the issue cannot be read", async () => {
+ const f = await setup("gitea");
+ const errors = vi.spyOn(console, "error").mockImplementation(() => {});
+ try {
+ mocks.readFailures = [Object.assign(new Error("gone"), { status: 404 })];
+ change("labeled", "one");
+ await f.receive(mocks.deliveries.shift()!);
+ } finally {
+ errors.mockRestore();
+ }
+ const labels = await db.query.labelTable.findMany({
+ where: eq(schema.labelTable.taskId, f.task.id),
+ });
+ expect(labels.map((label) => label.name)).toEqual(["one"]);
+ // Replaying a permanent failure cannot succeed, so none is queued.
+ expect((await f.metadataOf()).syncLabelFieldsDeferred).toBeUndefined();
+});
diff --git a/tests/api-integration/provider-board-live-updates.test.ts b/tests/api-integration/provider-board-live-updates.test.ts
index c7f9be453..cc6b16395 100644
--- a/tests/api-integration/provider-board-live-updates.test.ts
+++ b/tests/api-integration/provider-board-live-updates.test.ts
@@ -55,6 +55,7 @@ vi.mock(
beforeEach(async () => {
await resetTestDatabase();
m.publish.mockReset();
+ m.labels = [];
});
it.each([
["github", "text"],