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(integrations): coordinate initial issue label writes

Tin934c876b1db3
diff --git a/apps/api/src/plugins/gitea/events/task-created.ts b/apps/api/src/plugins/gitea/events/task-created.ts
index e65c39b36..741d1359f 100644
--- a/apps/api/src/plugins/gitea/events/task-created.ts
+++ b/apps/api/src/plugins/gitea/events/task-created.ts
@@ -4,6 +4,7 @@ import {
} from "../../sync/initialize-task-issue";
import { canSyncTask } from "../../sync/eligibility";
import { withTaskSyncCreation } from "../../sync/create-task-issue";
+import { syncTaskFieldLabels } from "../../sync/sync-task-field-labels";
import {
createExternalLink,
updateExternalLink,
@@ -13,7 +14,7 @@ import { formatIssueBody, formatIssueTitle } from "../../github/utils/format";
import type { PluginContext, TaskCreatedEvent } from "../../types";
import type { GiteaConfig } from "../config";
import { createGiteaClient } from "../utils/gitea-api";
-import { addLabelsToIssueGitea } from "../utils/labels";
+import { addLabelsToIssueGitea, removeLabelGitea } from "../utils/labels";
async function createTaskIssue(
event: TaskCreatedEvent,
@@ -111,8 +112,19 @@ async function createTaskIssue(
client.updateIssue(repositoryOwner, repositoryName, issueNumber, {
state: "closed",
}),
- labels: (labels, write) =>
- addLabelsToIssueGitea(config, issueNumber, labels, true, write),
+ labels: () =>
+ syncTaskFieldLabels(
+ event.taskId,
+ context,
+ { id: createdLink.id, externalId: String(issueNumber) },
+ "gitea",
+ "initialization",
+ async ({ add, remove }, write) => {
+ for (const name of remove)
+ await removeLabelGitea(config, issueNumber, name, write);
+ await addLabelsToIssueGitea(config, issueNumber, add, true, write);
+ },
+ ),
});
} catch (error) {
console.error("Failed to create Gitea issue:", error);
diff --git a/apps/api/src/plugins/github/events/task-created.ts b/apps/api/src/plugins/github/events/task-created.ts
index cdd06c7d9..8f3f53493 100644
--- a/apps/api/src/plugins/github/events/task-created.ts
+++ b/apps/api/src/plugins/github/events/task-created.ts
@@ -4,6 +4,7 @@ import {
} from "../../sync/initialize-task-issue";
import { canSyncTask } from "../../sync/eligibility";
import { withTaskSyncCreation } from "../../sync/create-task-issue";
+import { syncTaskFieldLabels } from "../../sync/sync-task-field-labels";
import { eq } from "drizzle-orm";
import db from "../../../database";
import { projectTable } from "../../../database/schema";
@@ -19,7 +20,7 @@ import {
getGithubApp,
getVerifiedInstallationOctokit,
} from "../utils/github-app";
-import { addLabelsToIssue } from "../utils/labels";
+import { addLabelsToIssue, removeLabel } from "../utils/labels";
async function createTaskIssue(
event: TaskCreatedEvent,
@@ -132,15 +133,33 @@ async function createTaskIssue(
issue_number: issueNumber,
state: "closed",
}),
- labels: (labels, write) =>
- addLabelsToIssue(
- octokit,
- repositoryOwner,
- repositoryName,
- issueNumber,
- labels,
- true,
- write,
+ labels: () =>
+ syncTaskFieldLabels(
+ event.taskId,
+ context,
+ { id: createdLink.id, externalId: String(issueNumber) },
+ "github",
+ "initialization",
+ async ({ add, remove }, write) => {
+ for (const name of remove)
+ await removeLabel(
+ octokit,
+ repositoryOwner,
+ repositoryName,
+ issueNumber,
+ name,
+ write,
+ );
+ await addLabelsToIssue(
+ octokit,
+ repositoryOwner,
+ repositoryName,
+ issueNumber,
+ add,
+ true,
+ write,
+ );
+ },
),
...(comment
? {
diff --git a/apps/api/src/plugins/gitlab/events/task-created.ts b/apps/api/src/plugins/gitlab/events/task-created.ts
index e9f885ac2..15e1585fa 100644
--- a/apps/api/src/plugins/gitlab/events/task-created.ts
+++ b/apps/api/src/plugins/gitlab/events/task-created.ts
@@ -4,6 +4,7 @@ import {
} from "../../sync/initialize-task-issue";
import { canSyncTask } from "../../sync/eligibility";
import { withTaskSyncCreation } from "../../sync/create-task-issue";
+import { syncTaskFieldLabels } from "../../sync/sync-task-field-labels";
import {
createExternalLink,
updateExternalLink,
@@ -13,7 +14,7 @@ import { formatIssueBody, formatIssueTitle } from "../../github/utils/format";
import type { PluginContext, TaskCreatedEvent } from "../../types";
import type { GitlabConfig } from "../config";
import { createGitlabClient } from "../utils/gitlab-api";
-import { addLabelsToIssueGitlab } from "../utils/labels";
+import { updateIssueLabelsGitlab } from "../utils/labels";
async function createTaskIssue(
event: TaskCreatedEvent,
@@ -104,8 +105,16 @@ async function createTaskIssue(
client.updateIssue(config.projectPath, issueNumber, {
state_event: "close",
}),
- labels: (labels, write) =>
- addLabelsToIssueGitlab(config, issueNumber, labels, true, write),
+ labels: () =>
+ syncTaskFieldLabels(
+ event.taskId,
+ context,
+ { id: createdLink.id, externalId: String(issueNumber) },
+ "gitlab",
+ "initialization",
+ (changes, write) =>
+ updateIssueLabelsGitlab(config, issueNumber, changes, true, write),
+ ),
});
} catch (error) {
console.error("Failed to create GitLab issue:", error);
diff --git a/apps/api/src/plugins/sync/initialize-task-issue.ts b/apps/api/src/plugins/sync/initialize-task-issue.ts
index daaf1c23a..944848965 100644
--- a/apps/api/src/plugins/sync/initialize-task-issue.ts
+++ b/apps/api/src/plugins/sync/initialize-task-issue.ts
@@ -3,8 +3,6 @@ import { isTaskInFinalState } from "../github/services/task-service";
import { parseLinkMetadata } from "../github/utils/parse-link-metadata";
import type { PluginContext, TaskCreatedEvent } from "../types";
import { createIssueWrite } from "./dispatch-issue-write";
-import type { IssueWrite } from "./issue-write";
-import { taskIssueLabels } from "./issue-labels";
import { initializeTaskText } from "./initialize-task-text";
type Initialization = {
@@ -34,7 +32,7 @@ export async function initializeTaskIssue(
value: string,
) => Promise<string | undefined>;
close: () => Promise<unknown>;
- labels: (names: string[], write: IssueWrite) => Promise<void>;
+ labels: () => Promise<string | undefined>;
comment?: () => Promise<unknown>;
},
) {
@@ -65,10 +63,8 @@ export async function initializeTaskIssue(
});
}
if (!progress.syncInitializedLabels) {
- await actions.labels(
- await taskIssueLabels(event.taskId, current.priority, current.status),
- write,
- );
+ if ((await actions.labels()) === undefined)
+ throw new Error("Issue sync scope changed");
await updateExternalLink(link.id, {
metadata: { syncInitializedLabels: true },
});
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 7d275a4eb..a40ec82d1 100644
--- a/apps/api/src/plugins/sync/sync-task-field-labels.ts
+++ b/apps/api/src/plugins/sync/sync-task-field-labels.ts
@@ -8,6 +8,7 @@ import type { PluginContext } from "../types";
import { createIssueWrite } from "./dispatch-issue-write";
import { canSyncTask } from "./eligibility";
import type { IssueWrite } from "./issue-write";
+import { taskIssueLabels } from "./issue-labels";
import { withSyncLease } from "./lease";
import { providerIssue } from "./provider-issue";
@@ -16,13 +17,15 @@ export async function syncTaskFieldLabels(
context: PluginContext,
link: { id: string; externalId: string },
provider: string,
- field: "priority" | "status",
+ field: "priority" | "status" | "initialization",
send: (
changes: { add: string[]; remove: string[] },
write: IssueWrite,
) => Promise<void>,
) {
const config = JSON.stringify(context.config);
+ const prefixes =
+ field === "initialization" ? ["priority:", "status:"] : [`${field}:`];
return withSyncLease(`sync-field-labels:${link.id}`, async () => {
const remote = await providerIssue(
{ type: provider, config },
@@ -41,15 +44,22 @@ export async function syncTaskFieldLabels(
where: linkedTaskScope(taskId, context.projectId),
});
if (!task) return;
- const value = task[field] ?? "no-priority";
const labels = (await remote.read()).labels;
- const prefix = `${field}:`;
const add =
- field === "priority" && value === "no-priority"
- ? []
- : [`${prefix}${value}`];
+ field === "initialization"
+ ? (await taskIssueLabels(taskId, task.priority, task.status)).sort()
+ : field === "priority" &&
+ (!task.priority || task.priority === "no-priority")
+ ? []
+ : [`${field}:${task[field]}`];
+ const value =
+ field === "initialization"
+ ? JSON.stringify(add)
+ : (task[field] ?? "no-priority");
const remove = labels.filter(
- (name) => name.startsWith(prefix) && !add.includes(name),
+ (name) =>
+ prefixes.some((prefix) => name.startsWith(prefix)) &&
+ !add.includes(name),
);
await send({ add, remove }, write);
if (
@@ -73,10 +83,14 @@ export async function syncTaskFieldLabels(
await updateExternalLink(link.id, {
metadata: {
syncResumeLabelBaseline: [
- ...metadata.syncResumeLabelBaseline.filter(
- (name) => typeof name === "string" && !name.startsWith(prefix),
- ),
- ...add,
+ ...new Set([
+ ...metadata.syncResumeLabelBaseline.filter(
+ (name) =>
+ typeof name === "string" &&
+ !prefixes.some((prefix) => name.startsWith(prefix)),
+ ),
+ ...add,
+ ]),
],
},
});
@@ -87,7 +101,15 @@ export async function syncTaskFieldLabels(
if (!current) return;
// A later event may time out waiting for this lease. The current owner
// repairs edits made during its provider request before releasing it.
- if ((current[field] ?? "no-priority") === value) return value;
+ const currentValue =
+ field === "initialization"
+ ? JSON.stringify(
+ (
+ await taskIssueLabels(taskId, current.priority, current.status)
+ ).sort(),
+ )
+ : (current[field] ?? "no-priority");
+ if (currentValue === value) return value;
}
}).catch(() => {
console.error("Issue field label synchronization failed", {
diff --git a/tests/api-integration/integration-label-dispatch.test.ts b/tests/api-integration/integration-label-dispatch.test.ts
index 4fee7fee8..86558fc1a 100644
--- a/tests/api-integration/integration-label-dispatch.test.ts
+++ b/tests/api-integration/integration-label-dispatch.test.ts
@@ -1,4 +1,5 @@
import { initializeTaskIssue } from "../../apps/api/src/plugins/sync/initialize-task-issue";
+import { syncTaskFieldLabels } from "../../apps/api/src/plugins/sync/sync-task-field-labels";
import { addLabelsToIssue } from "../../apps/api/src/plugins/github/utils/labels";
import { addLabelsToIssueGitea } from "../../apps/api/src/plugins/gitea/utils/labels";
import { addLabelsToIssueGitlab } from "../../apps/api/src/plugins/gitlab/utils/labels";
@@ -39,6 +40,7 @@ vi.mock("../../apps/api/src/plugins/github/utils/github-app", () => ({
getVerifiedInstallationOctokit: async () => ({
rest: {
issues: {
+ get: async () => ({ data: { labels: [] } }),
getLabel: async () => {
await mocks.lookup();
throw new Error("Label does not exist");
@@ -136,33 +138,45 @@ it.each(["github", "gitea", "gitlab"] as const)(
{
text: async () => undefined,
close: mocks.addLabel,
- labels: (names, write) => {
- if (provider === "github")
- return addLabelsToIssue(
- octokit,
- "team",
- "repo",
- 12,
- names,
- true,
- write,
- );
- if (provider === "gitea")
- return addLabelsToIssueGitea(
- f.config as GiteaConfig,
- 12,
- names,
- true,
- write,
- );
- return addLabelsToIssueGitlab(
- f.config as GitlabConfig,
- 12,
- names,
- true,
- write,
- );
- },
+ labels: () =>
+ syncTaskFieldLabels(
+ f.task.id,
+ {
+ integrationId: f.integration.id,
+ projectId: f.project.id,
+ config: f.config,
+ },
+ f.link,
+ provider,
+ "initialization",
+ ({ add: names }, write) => {
+ if (provider === "github")
+ return addLabelsToIssue(
+ octokit,
+ "team",
+ "repo",
+ 12,
+ names,
+ true,
+ write,
+ );
+ if (provider === "gitea")
+ return addLabelsToIssueGitea(
+ f.config as GiteaConfig,
+ 12,
+ names,
+ true,
+ write,
+ );
+ return addLabelsToIssueGitlab(
+ f.config as GitlabConfig,
+ 12,
+ names,
+ true,
+ write,
+ );
+ },
+ ),
},
).then(
() => undefined,
diff --git a/tests/api-integration/integration-sync-field-labels.test.ts b/tests/api-integration/integration-sync-field-labels.test.ts
index b91cb9db4..7bdf42f5c 100644
--- a/tests/api-integration/integration-sync-field-labels.test.ts
+++ b/tests/api-integration/integration-sync-field-labels.test.ts
@@ -102,8 +102,15 @@ it.each(
(["github", "gitea", "gitlab"] as const).flatMap((provider) =>
(["status", "priority"] as const).flatMap((field) =>
(field === "priority"
- ? [false, true, "clear", "read-error"]
- : [false, true]
+ ? [
+ false,
+ true,
+ "clear",
+ "read-error",
+ "initialization",
+ "initialization-waits",
+ ]
+ : [false, true, "initialization", "initialization-waits"]
).map((overlap) => ({ provider, field, overlap })),
),
),
@@ -115,7 +122,9 @@ it.each(
workspaceId: workspace.id,
});
const clearing = overlap === "clear";
- const overlapping = overlap === true;
+ const initializing =
+ overlap === "initialization" || overlap === "initialization-waits";
+ const overlapping = overlap === true || initializing;
const first =
field === "status" ? "in-progress" : clearing ? "no-priority" : "high";
const last = field === "status" ? "in-review" : "urgent";
@@ -139,6 +148,7 @@ it.each(
repositoryId: 2,
verifiedGithubAccountId: "3",
verifiedByUserId: user.id,
+ commentTaskLinkOnGitHubIssue: false,
};
const [integration] = await db
.insert(schema.integrationTable)
@@ -159,6 +169,13 @@ it.each(
url: "https://git.example/team/repo/issues/1",
metadata: JSON.stringify({
syncResumeLabelBaseline: [...mocks.labels],
+ ...(initializing
+ ? {
+ syncInitializationPending: true,
+ syncInitializedState: true,
+ syncCreatedText: { title: "Task", description: "" },
+ }
+ : {}),
}),
})
.returning();
@@ -197,6 +214,20 @@ it.each(
},
context,
);
+ const initialize = () =>
+ plugin.onTaskCreated!(
+ {
+ taskId: task.id,
+ projectId: project.id,
+ userId: user.id,
+ title: task.title,
+ description: null,
+ status: task.status,
+ priority: task.priority,
+ number: 1,
+ },
+ context,
+ );
let release!: () => void;
let started!: () => void;
const gate = new Promise<void>((resolve) => {
@@ -237,7 +268,10 @@ it.each(
errors.mockRestore();
}
}
- const initial = sync(field === "status" ? "to-do" : "urgent", first);
+ const initial =
+ overlap === "initialization"
+ ? initialize()
+ : sync(field === "status" ? "to-do" : "urgent", first);
if (overlapping) {
await writing;
// A slow provider request must not hold task or project row locks.
@@ -245,7 +279,8 @@ it.each(
.update(schema.taskTable)
.set({ [field]: last })
.where(eq(schema.taskTable.id, task.id));
- const later = sync(first, last);
+ const later =
+ overlap === "initialization-waits" ? initialize() : sync(first, last);
release();
await Promise.all([initial, later]);
} else await initial;
@@ -255,11 +290,24 @@ it.each(
).toEqual(clearing ? [] : [expected]);
expect(mocks.labels.has("keep")).toBe(true);
expect(
- mocks.labels.has(field === "status" ? "priority:low" : "status:planned"),
+ mocks.labels.has(
+ field === "status"
+ ? initializing
+ ? "priority:high"
+ : "priority:low"
+ : initializing
+ ? "status:in-progress"
+ : "status:planned",
+ ),
).toBe(true);
const saved = await db.query.externalLinkTable.findFirst({
where: eq(schema.externalLinkTable.id, link.id),
});
+ if (initializing)
+ expect(JSON.parse(saved!.metadata!)).toMatchObject({
+ syncInitializedLabels: true,
+ syncInitializationPending: false,
+ });
if (!clearing)
expect(JSON.parse(saved!.metadata!).syncResumeLabelBaseline).toContain(
expected,
diff --git a/tests/api-integration/integration-sync-providers.test.ts b/tests/api-integration/integration-sync-providers.test.ts
index f94a1022a..d381e04d5 100644
--- a/tests/api-integration/integration-sync-providers.test.ts
+++ b/tests/api-integration/integration-sync-providers.test.ts
@@ -88,12 +88,20 @@ vi.mock("../../apps/api/src/plugins/gitlab/utils/gitlab-api", () => ({
}));
vi.mock("../../apps/api/src/plugins/github/utils/labels", () => ({
addLabelsToIssue: mocks.labels,
+ removeLabel: async () => {},
}));
vi.mock("../../apps/api/src/plugins/gitea/utils/labels", () => ({
addLabelsToIssueGitea: mocks.labels,
+ removeLabelGitea: async () => {},
}));
vi.mock("../../apps/api/src/plugins/gitlab/utils/labels", () => ({
addLabelsToIssueGitlab: mocks.labels,
+ updateIssueLabelsGitlab: (
+ config: unknown,
+ number: number,
+ changes: { add: string[] },
+ ...args: unknown[]
+ ) => mocks.labels(config, number, changes.add, ...args),
}));
beforeAll(() => {