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): github install and label detachment bug

justin6cb37485ce62
diff --git a/apps/api/src/github-integration/controllers/verify-github-installation.ts b/apps/api/src/github-integration/controllers/verify-github-installation.ts
index 1e73f82de..093380442 100644
--- a/apps/api/src/github-integration/controllers/verify-github-installation.ts
+++ b/apps/api/src/github-integration/controllers/verify-github-installation.ts
@@ -1,138 +1,132 @@
import { HTTPException } from "hono/http-exception";
import { getGithubApp } from "../../plugins/github/utils/github-app";
+type VerificationResult = {
+ isInstalled: boolean;
+ installationId: number | null;
+ repositoryExists: boolean | null;
+ repositoryPrivate: boolean | null;
+ permissions: Record<string, string> | null;
+ hasRequiredPermissions: boolean;
+ missingPermissions: string[];
+ message: string;
+ settingsUrl?: string;
+ installationUrl?: string;
+};
+
+function isGithubNotFound(error: unknown): boolean {
+ const status = (error as { status?: number })?.status;
+ return status === 404;
+}
+
+function appInstallUrl(): string | undefined {
+ return process.env.GITHUB_APP_NAME
+ ? `https://github.com/apps/${process.env.GITHUB_APP_NAME}`
+ : undefined;
+}
+
+function newInstallUrl(targetId?: number): string | undefined {
+ if (!process.env.GITHUB_APP_NAME) return undefined;
+ const base = `https://github.com/apps/${process.env.GITHUB_APP_NAME}/installations/new`;
+ return typeof targetId === "number" && Number.isFinite(targetId)
+ ? `${base}/permissions?target_id=${targetId}`
+ : `${base}/permissions`;
+}
+
+function settingsUrlFor(installationId: number): string {
+ return `https://github.com/settings/installations/${installationId}`;
+}
+
async function verifyGithubInstallation({
repositoryOwner,
repositoryName,
}: {
repositoryOwner: string;
repositoryName: string;
-}) {
+}): Promise<VerificationResult> {
const githubApp = getGithubApp();
- try {
- if (!githubApp) {
- throw new HTTPException(500, {
- message: "GitHub app not configured",
- });
- }
-
- const { data: installation } =
- await githubApp.octokit.rest.apps.getRepoInstallation({
- owner: repositoryOwner,
- repo: repositoryName,
- });
+ if (!githubApp) {
+ throw new HTTPException(500, {
+ message: "GitHub app not configured",
+ });
+ }
- const octokit = await githubApp.getInstallationOctokit(installation.id);
- const { data: repo } = await octokit.rest.repos.get({
+ let installation: { id: number; permissions?: Record<string, string> };
+ try {
+ const { data } = await githubApp.octokit.rest.apps.getRepoInstallation({
owner: repositoryOwner,
repo: repositoryName,
});
-
- const requiredPermissions = ["issues"];
- const hasRequiredPermissions = checkPermissions(
- installation.permissions,
- requiredPermissions,
- );
- const missingPermissions = getMissingPermissions(
- installation.permissions,
- requiredPermissions,
- );
-
- if (!hasRequiredPermissions) {
+ installation = data;
+ } catch (error) {
+ if (isGithubNotFound(error)) {
return {
- isInstalled: true,
- installationId: installation.id,
- repositoryExists: true,
- repositoryPrivate: repo.private,
- permissions: installation.permissions,
+ isInstalled: false,
+ installationId: null,
+ repositoryExists: null,
+ repositoryPrivate: null,
+ permissions: null,
hasRequiredPermissions: false,
- missingPermissions,
- message: `GitHub App is installed but missing required permissions: ${missingPermissions.join(", ")}`,
- settingsUrl: `https://github.com/settings/installations/${installation.id}`,
- installationUrl: process.env.GITHUB_APP_NAME
- ? `https://github.com/apps/${process.env.GITHUB_APP_NAME}/installations/new/permissions?target_id=${repo.id}`
- : undefined,
+ missingPermissions: [],
+ message:
+ "GitHub App is not installed on this repository or the repository is not accessible",
+ installationUrl: newInstallUrl(),
+ settingsUrl: appInstallUrl(),
};
}
+ throw new HTTPException(500, {
+ message: `Failed to verify GitHub installation: ${(error as Error).message || "Unknown error"}`,
+ });
+ }
+
+ const installationOctokit = await githubApp.getInstallationOctokit(
+ installation.id,
+ );
+ const { data: repo } = await installationOctokit.rest.repos.get({
+ owner: repositoryOwner,
+ repo: repositoryName,
+ });
+
+ const requiredPermissions = ["issues"];
+ const hasRequiredPermissions = checkPermissions(
+ installation.permissions,
+ requiredPermissions,
+ );
+ const missingPermissions = getMissingPermissions(
+ installation.permissions,
+ requiredPermissions,
+ );
+
+ if (!hasRequiredPermissions) {
return {
isInstalled: true,
installationId: installation.id,
repositoryExists: true,
repositoryPrivate: repo.private,
permissions: installation.permissions,
- hasRequiredPermissions: true,
- missingPermissions: [],
- installationUrl: `https://github.com/apps/${process.env.GITHUB_APP_NAME}/installations/new/permissions?target_id=${repo.id}`,
- message:
- "GitHub App is properly installed and has all required permissions",
- settingsUrl: `https://github.com/settings/installations/${installation.id}`,
+ hasRequiredPermissions: false,
+ missingPermissions,
+ message: `GitHub App is installed but missing required permissions: ${missingPermissions.join(", ")}`,
+ settingsUrl: settingsUrlFor(installation.id),
+ installationUrl: newInstallUrl(repo.id),
};
- } catch (error) {
- const githubError = error as { status?: number; message?: string };
-
- if (githubError.status === 404) {
- try {
- if (!githubApp) {
- throw new HTTPException(500, {
- message: "GitHub app not configured",
- });
- }
-
- await githubApp.octokit.rest.repos.get({
- owner: repositoryOwner,
- repo: repositoryName,
- });
-
- const repoId = await getRepositoryId(repositoryOwner, repositoryName);
-
- return {
- isInstalled: false,
- installationId: null,
- repositoryExists: true,
- repositoryPrivate: null,
- permissions: null,
- hasRequiredPermissions: false,
- missingPermissions: [],
- message: "Repository exists but GitHub App is not installed",
- installationUrl: process.env.GITHUB_APP_NAME
- ? `https://github.com/apps/${process.env.GITHUB_APP_NAME}/installations/new/permissions?target_id=${repoId}`
- : undefined,
- settingsUrl: process.env.GITHUB_APP_NAME
- ? `https://github.com/apps/${process.env.GITHUB_APP_NAME}`
- : undefined,
- };
- } catch (repoError) {
- const repoGithubError = repoError as {
- status?: number;
- message?: string;
- };
-
- if (repoGithubError.status === 404) {
- return {
- isInstalled: false,
- installationId: null,
- repositoryExists: false,
- repositoryPrivate: null,
- permissions: null,
- hasRequiredPermissions: false,
- missingPermissions: [],
- settingsUrl: undefined,
- installationUrl: undefined,
- message: "Repository does not exist or is not accessible",
- };
- }
- throw new HTTPException(500, {
- message: `Failed to verify GitHub installation: ${repoGithubError.status || repoGithubError.message || "Unknown error"}`,
- });
- }
- }
-
- throw new HTTPException(500, {
- message: `Failed to verify GitHub installation: ${githubError.message || "Unknown error"}`,
- });
}
+
+ return {
+ isInstalled: true,
+ installationId: installation.id,
+ repositoryExists: true,
+ repositoryPrivate: repo.private,
+ permissions: installation.permissions,
+ hasRequiredPermissions: true,
+ missingPermissions: [],
+ message:
+ "GitHub App is properly installed and has all required permissions",
+ settingsUrl: settingsUrlFor(installation.id),
+ installationUrl: newInstallUrl(repo.id),
+ };
}
function checkPermissions(
@@ -159,24 +153,4 @@ function getMissingPermissions(
});
}
-async function getRepositoryId(owner: string, repo: string): Promise<number> {
- const githubApp = getGithubApp();
-
- try {
- if (!githubApp) {
- throw new HTTPException(500, {
- message: "GitHub app not configured",
- });
- }
-
- const { data } = await githubApp.octokit.rest.repos.get({
- owner,
- repo,
- });
- return data.id;
- } catch {
- return 0;
- }
-}
-
export default verifyGithubInstallation;
diff --git a/apps/api/src/github-integration/index.ts b/apps/api/src/github-integration/index.ts
index 39feb4c0d..d72e69b2f 100644
--- a/apps/api/src/github-integration/index.ts
+++ b/apps/api/src/github-integration/index.ts
@@ -38,8 +38,16 @@ const githubRepositorySchema = v.object({
});
const verificationResultSchema = v.object({
- installed: v.boolean(),
- message: v.optional(v.string()),
+ isInstalled: v.boolean(),
+ installationId: v.nullable(v.number()),
+ repositoryExists: v.nullable(v.boolean()),
+ repositoryPrivate: v.nullable(v.boolean()),
+ permissions: v.nullable(v.record(v.string(), v.string())),
+ hasRequiredPermissions: v.boolean(),
+ missingPermissions: v.array(v.string()),
+ message: v.string(),
+ settingsUrl: v.optional(v.string()),
+ installationUrl: v.optional(v.string()),
});
const importResultSchema = v.object({
diff --git a/apps/api/src/label/controllers/assign-label-to-task.ts b/apps/api/src/label/controllers/assign-label-to-task.ts
index c524b837c..1ec1fb218 100644
--- a/apps/api/src/label/controllers/assign-label-to-task.ts
+++ b/apps/api/src/label/controllers/assign-label-to-task.ts
@@ -1,4 +1,4 @@
-import { eq } from "drizzle-orm";
+import { and, eq } from "drizzle-orm";
import { HTTPException } from "hono/http-exception";
import db from "../../database";
import { labelTable, projectTable, taskTable } from "../../database/schema";
@@ -46,40 +46,61 @@ async function assignLabelToTask(id: string, taskId: string, userId: string) {
});
}
- const [updatedLabel] = await db
- .update(labelTable)
- .set({ taskId })
- .where(eq(labelTable.id, id))
- .returning();
-
- if (!updatedLabel) {
- throw new HTTPException(500, {
- message: "Failed to attach label to task",
- });
+ if (label.taskId === taskId) {
+ return label;
}
if (label.taskId && label.taskId !== taskId) {
- removeLabelFromGitHub(label.taskId, label.name).catch((error) => {
+ const previousTaskId = label.taskId;
+ const previousName = label.name;
+
+ await db.delete(labelTable).where(eq(labelTable.id, id));
+
+ removeLabelFromGitHub(previousTaskId, previousName).catch((error) => {
console.error("Failed to remove label from GitHub:", error);
});
- removeLabelFromGitea(label.taskId, label.name).catch((error) => {
+ removeLabelFromGitea(previousTaskId, previousName).catch((error) => {
console.error("Failed to remove label from Gitea:", error);
});
}
- syncLabelToGitHub(taskId, updatedLabel.name, updatedLabel.color).catch(
- (error) => {
- console.error("Failed to sync label to GitHub:", error);
- },
- );
- syncLabelToGitea(taskId, updatedLabel.name, updatedLabel.color).catch(
- (error) => {
- console.error("Failed to sync label to Gitea:", error);
- },
- );
+ const [inserted] = await db
+ .insert(labelTable)
+ .values({
+ name: label.name,
+ color: label.color,
+ taskId,
+ workspaceId: task.workspaceId,
+ })
+ .onConflictDoNothing({
+ target: [labelTable.taskId, labelTable.name],
+ })
+ .returning();
+
+ const taskLabel =
+ inserted ??
+ (await db.query.labelTable.findFirst({
+ where: and(
+ eq(labelTable.taskId, taskId),
+ eq(labelTable.name, label.name),
+ ),
+ }));
+
+ if (!taskLabel) {
+ throw new HTTPException(500, {
+ message: "Failed to attach label to task",
+ });
+ }
+
+ syncLabelToGitHub(taskId, taskLabel.name, taskLabel.color).catch((error) => {
+ console.error("Failed to sync label to GitHub:", error);
+ });
+ syncLabelToGitea(taskId, taskLabel.name, taskLabel.color).catch((error) => {
+ console.error("Failed to sync label to Gitea:", error);
+ });
await publishEvent("task.label_assigned", {
- label: updatedLabel,
+ label: taskLabel,
task,
projectId: task.projectId,
taskId: task.id,
@@ -87,7 +108,7 @@ async function assignLabelToTask(id: string, taskId: string, userId: string) {
type: "label_assigned",
});
- return updatedLabel;
+ return taskLabel;
}
export default assignLabelToTask;
diff --git a/apps/api/src/label/controllers/unassign-label-from-task.ts b/apps/api/src/label/controllers/unassign-label-from-task.ts
index 1163f464c..85475ae11 100644
--- a/apps/api/src/label/controllers/unassign-label-from-task.ts
+++ b/apps/api/src/label/controllers/unassign-label-from-task.ts
@@ -39,34 +39,35 @@ async function unassignLabelFromTask(id: string, userId: string) {
});
}
- const [updatedLabel] = await db
- .update(labelTable)
- .set({ taskId: null })
+ const [deletedLabel] = await db
+ .delete(labelTable)
.where(eq(labelTable.id, id))
.returning();
- if (!updatedLabel) {
+ if (!deletedLabel) {
throw new HTTPException(500, {
message: "Failed to detach label from task",
});
}
- if (label.taskId) {
- removeLabelFromGitHub(label.taskId, label.name).catch((error) => {
- console.error("Failed to remove label from GitHub:", error);
- });
+ if (deletedLabel.taskId) {
+ removeLabelFromGitHub(deletedLabel.taskId, deletedLabel.name).catch(
+ (error) => {
+ console.error("Failed to remove label from GitHub:", error);
+ },
+ );
}
await publishEvent("task.label_unassigned", {
- label: updatedLabel,
+ label: deletedLabel,
task,
projectId: task.projectId,
- taskId: label.taskId,
+ taskId: deletedLabel.taskId,
userId,
type: "label_unassigned",
});
- return updatedLabel;
+ return deletedLabel;
}
export default unassignLabelFromTask;
diff --git a/apps/api/src/task/controllers/bulk-update-tasks.ts b/apps/api/src/task/controllers/bulk-update-tasks.ts
index cabfbbc69..384c50166 100644
--- a/apps/api/src/task/controllers/bulk-update-tasks.ts
+++ b/apps/api/src/task/controllers/bulk-update-tasks.ts
@@ -1,4 +1,4 @@
-import { and, eq, inArray } from "drizzle-orm";
+import { and, eq, inArray, isNotNull } from "drizzle-orm";
import { HTTPException } from "hono/http-exception";
import db from "../../database";
import {
@@ -10,6 +10,8 @@ import {
workspaceUserTable,
} from "../../database/schema";
import { publishEvent } from "../../events";
+import { removeLabelFromGitea } from "../../plugins/gitea/utils/sync-label-to-gitea";
+import { removeLabelFromGitHub } from "../../plugins/github/utils/sync-label-to-github";
import {
assertValidPriority,
assertValidTaskStatus,
@@ -263,19 +265,51 @@ async function bulkUpdateTasks({
if (!value) {
throw new HTTPException(400, { message: "Label ID is required" });
}
- const result = await db
- .update(labelTable)
- .set({ taskId: null })
+
+ const label = await db.query.labelTable.findFirst({
+ where: eq(labelTable.id, value),
+ });
+
+ if (!label) {
+ throw new HTTPException(404, { message: "Label not found" });
+ }
+
+ const deletedLabels = await db
+ .delete(labelTable)
.where(
- and(eq(labelTable.id, value), inArray(labelTable.taskId, foundIds)),
+ and(
+ eq(labelTable.workspaceId, label.workspaceId),
+ eq(labelTable.name, label.name),
+ isNotNull(labelTable.taskId),
+ inArray(labelTable.taskId, foundIds),
+ ),
+ )
+ .returning();
+
+ updatedCount = deletedLabels.length;
+
+ for (const deletedLabel of deletedLabels) {
+ if (!deletedLabel.taskId) continue;
+
+ removeLabelFromGitHub(deletedLabel.taskId, deletedLabel.name).catch(
+ (error) => {
+ console.error("Failed to remove label from GitHub:", error);
+ },
+ );
+ removeLabelFromGitea(deletedLabel.taskId, deletedLabel.name).catch(
+ (error) => {
+ console.error("Failed to remove label from Gitea:", error);
+ },
);
- updatedCount = result.rowCount ?? foundIds.length;
+ const task = tasks.find((t) => t.id === deletedLabel.taskId);
+ if (!task) continue;
- for (const task of tasks) {
await publishEvent("task.label_unassigned", {
+ label: deletedLabel,
+ task,
projectId: task.projectId,
- taskId: task.id,
+ taskId: deletedLabel.taskId,
userId,
type: "label_unassigned",
});
diff --git a/tests/api-integration/label-detach.test.ts b/tests/api-integration/label-detach.test.ts
new file mode 100644
index 000000000..afd98a716
--- /dev/null
+++ b/tests/api-integration/label-detach.test.ts
@@ -0,0 +1,474 @@
+import { and, eq } from "drizzle-orm";
+import { beforeEach, describe, expect, it } from "vitest";
+import db, { schema } from "../../apps/api/src/database";
+import { createApp } from "../../apps/api/src/index";
+import { subscribeToEvent } from "../../apps/api/src/events";
+import { mockAuthenticatedSession } from "./helpers/auth";
+import { resetTestDatabase } from "./helpers/database";
+import {
+ createProjectFixture,
+ createWorkspaceMember,
+} from "./helpers/fixtures";
+
+type RecordedEvent = {
+ type: string;
+ data: unknown;
+};
+
+const recordedEvents: RecordedEvent[] = [];
+let subscribersInitialized = false;
+
+function initEventSubscribers() {
+ if (subscribersInitialized) return;
+ subscribersInitialized = true;
+ subscribeToEvent("task.label_assigned", async (data) => {
+ recordedEvents.push({ type: "task.label_assigned", data });
+ });
+ subscribeToEvent("task.label_unassigned", async (data) => {
+ recordedEvents.push({ type: "task.label_unassigned", data });
+ });
+}
+
+async function seedTask(
+ userId: string,
+ workspaceId: string,
+ projectId: string,
+) {
+ return db
+ .insert(schema.taskTable)
+ .values({
+ projectId,
+ userId,
+ title: "Seed",
+ status: "to-do",
+ priority: "medium",
+ number: 1,
+ position: 1,
+ })
+ .returning();
+}
+
+describe("API integration: label detach/attach", () => {
+ beforeEach(async () => {
+ await resetTestDatabase();
+ recordedEvents.length = 0;
+ initEventSubscribers();
+ });
+
+ it("allows a workspace definition and a task assignment with the same name to coexist", async () => {
+ const member = await createWorkspaceMember();
+ const { project } = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ });
+ const [task] = await seedTask(member.user.id, member.workspace.id, project.id);
+
+ const [workspaceLabel] = await db
+ .insert(schema.labelTable)
+ .values({
+ name: "Bug",
+ color: "#ef4444",
+ workspaceId: member.workspace.id,
+ taskId: null,
+ })
+ .returning();
+
+ const [taskCopy] = await db
+ .insert(schema.labelTable)
+ .values({
+ name: "Bug",
+ color: "#ef4444",
+ workspaceId: member.workspace.id,
+ taskId: task.id,
+ })
+ .returning();
+
+ const allLabels = await db.query.labelTable.findMany({
+ where: eq(schema.labelTable.workspaceId, member.workspace.id),
+ });
+ expect(allLabels).toHaveLength(2);
+ expect(workspaceLabel.taskId).toBeNull();
+ expect(taskCopy.taskId).toBe(task.id);
+ });
+
+ it("attaches a label to a task without mutating the workspace definition", async () => {
+ const member = await createWorkspaceMember();
+ const { project } = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ });
+ const [task] = await seedTask(member.user.id, member.workspace.id, project.id);
+
+ mockAuthenticatedSession(member.user);
+ const { app } = createApp();
+
+ const createResponse = await app.request("/api/label", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ name: "Feature",
+ color: "#3b82f6",
+ workspaceId: member.workspace.id,
+ }),
+ });
+ expect(createResponse.status).toBe(200);
+ const label = (await createResponse.json()) as {
+ id: string;
+ name: string;
+ color: string;
+ };
+
+ const attachResponse = await app.request(`/api/label/${label.id}/task`, {
+ method: "PUT",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ taskId: task.id }),
+ });
+ expect(attachResponse.status).toBe(200);
+
+ const allLabels = await db.query.labelTable.findMany({
+ where: and(
+ eq(schema.labelTable.workspaceId, member.workspace.id),
+ eq(schema.labelTable.name, "Feature"),
+ ),
+ });
+
+ const workspaceLabel = allLabels.find((l) => l.taskId === null);
+ const taskCopy = allLabels.find((l) => l.taskId === task.id);
+
+ expect(workspaceLabel).toBeDefined();
+ expect(taskCopy).toBeDefined();
+ expect(workspaceLabel?.id).toBe(label.id);
+ expect(workspaceLabel?.taskId).toBeNull();
+ expect(taskCopy?.taskId).toBe(task.id);
+ });
+
+ it("makes repeated attachment idempotent without creating duplicates", async () => {
+ const member = await createWorkspaceMember();
+ const { project } = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ });
+ const [task] = await seedTask(member.user.id, member.workspace.id, project.id);
+
+ const [label] = await db
+ .insert(schema.labelTable)
+ .values({
+ name: "Bug",
+ color: "#ef4444",
+ workspaceId: member.workspace.id,
+ taskId: null,
+ })
+ .returning();
+
+ mockAuthenticatedSession(member.user);
+ const { app } = createApp();
+
+ const first = await app.request(`/api/label/${label.id}/task`, {
+ method: "PUT",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ taskId: task.id }),
+ });
+ expect(first.status).toBe(200);
+
+ const second = await app.request(`/api/label/${label.id}/task`, {
+ method: "PUT",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ taskId: task.id }),
+ });
+ expect(second.status).toBe(200);
+
+ const allLabels = await db.query.labelTable.findMany({
+ where: and(
+ eq(schema.labelTable.workspaceId, member.workspace.id),
+ eq(schema.labelTable.name, "Bug"),
+ ),
+ });
+ expect(allLabels).toHaveLength(2);
+ expect(allLabels.filter((l) => l.taskId === task.id)).toHaveLength(1);
+ });
+
+ it("detaches a label by deleting the task assignment and leaves the workspace definition intact", async () => {
+ const member = await createWorkspaceMember();
+ const { project } = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ });
+ const [task] = await seedTask(member.user.id, member.workspace.id, project.id);
+
+ const [workspaceLabel] = await db
+ .insert(schema.labelTable)
+ .values({
+ name: "Bug",
+ color: "#ef4444",
+ workspaceId: member.workspace.id,
+ taskId: null,
+ })
+ .returning();
+
+ const [taskCopy] = await db
+ .insert(schema.labelTable)
+ .values({
+ name: "Bug",
+ color: "#ef4444",
+ workspaceId: member.workspace.id,
+ taskId: task.id,
+ })
+ .returning();
+
+ mockAuthenticatedSession(member.user);
+ const { app } = createApp();
+
+ const detachResponse = await app.request(
+ `/api/label/${taskCopy.id}/task`,
+ { method: "DELETE" },
+ );
+ expect(detachResponse.status).toBe(200);
+
+ const remaining = await db.query.labelTable.findMany({
+ where: eq(schema.labelTable.workspaceId, member.workspace.id),
+ });
+ expect(remaining).toHaveLength(1);
+ expect(remaining[0].id).toBe(workspaceLabel.id);
+ expect(remaining[0].taskId).toBeNull();
+ });
+
+ it("does not violate label_workspace_name_unique after detachment", async () => {
+ const member = await createWorkspaceMember();
+ const { project } = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ });
+ const [task] = await seedTask(member.user.id, member.workspace.id, project.id);
+
+ const [workspaceLabel] = await db
+ .insert(schema.labelTable)
+ .values({
+ name: "Bug",
+ color: "#ef4444",
+ workspaceId: member.workspace.id,
+ taskId: null,
+ })
+ .returning();
+
+ const [taskCopy] = await db
+ .insert(schema.labelTable)
+ .values({
+ name: "Bug",
+ color: "#ef4444",
+ workspaceId: member.workspace.id,
+ taskId: task.id,
+ })
+ .returning();
+
+ mockAuthenticatedSession(member.user);
+ const { app } = createApp();
+
+ const detachResponse = await app.request(
+ `/api/label/${taskCopy.id}/task`,
+ { method: "DELETE" },
+ );
+ expect(detachResponse.status).toBe(200);
+
+ const workspaceRows = await db.query.labelTable.findMany({
+ where: and(
+ eq(schema.labelTable.workspaceId, member.workspace.id),
+ eq(schema.labelTable.name, "Bug"),
+ ),
+ });
+ const workspaceDefinitions = workspaceRows.filter((l) => l.taskId === null);
+ expect(workspaceDefinitions).toHaveLength(1);
+ expect(workspaceDefinitions[0].id).toBe(workspaceLabel.id);
+
+ await expect(
+ db
+ .insert(schema.labelTable)
+ .values({
+ name: "Bug",
+ color: "#ef4444",
+ workspaceId: member.workspace.id,
+ taskId: task.id,
+ }),
+ ).resolves.toBeDefined();
+ });
+
+ it("emits task.label_assigned and task.label_unassigned events through detach/attach", async () => {
+ const member = await createWorkspaceMember();
+ const { project } = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ });
+ const [task] = await seedTask(member.user.id, member.workspace.id, project.id);
+
+ const [label] = await db
+ .insert(schema.labelTable)
+ .values({
+ name: "Bug",
+ color: "#ef4444",
+ workspaceId: member.workspace.id,
+ taskId: null,
+ })
+ .returning();
+
+ mockAuthenticatedSession(member.user);
+ const { app } = createApp();
+
+ const attachResponse = await app.request(`/api/label/${label.id}/task`, {
+ method: "PUT",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ taskId: task.id }),
+ });
+ expect(attachResponse.status).toBe(200);
+ const attachPayload = (await attachResponse.json()) as { id: string };
+
+ const detachResponse = await app.request(
+ `/api/label/${attachPayload.id}/task`,
+ { method: "DELETE" },
+ );
+ expect(detachResponse.status).toBe(200);
+
+ const assignedEvents = recordedEvents.filter(
+ (e) => e.type === "task.label_assigned",
+ );
+ const unassignedEvents = recordedEvents.filter(
+ (e) => e.type === "task.label_unassigned",
+ );
+
+ expect(assignedEvents).toHaveLength(1);
+ expect(unassignedEvents).toHaveLength(1);
+
+ const assignedPayload = assignedEvents[0].data as {
+ taskId: string;
+ label: { id: string; name: string };
+ task: { id: string };
+ projectId: string;
+ userId: string;
+ type: string;
+ };
+ expect(assignedPayload.taskId).toBe(task.id);
+ expect(assignedPayload.task.id).toBe(task.id);
+ expect(assignedPayload.label.name).toBe("Bug");
+ expect(assignedPayload.userId).toBe(member.user.id);
+ expect(assignedPayload.type).toBe("label_assigned");
+
+ const unassignedPayload = unassignedEvents[0].data as {
+ taskId: string;
+ label: { id: string; name: string };
+ task: { id: string };
+ projectId: string;
+ userId: string;
+ type: string;
+ };
+ expect(unassignedPayload.taskId).toBe(task.id);
+ expect(unassignedPayload.label.id).toBe(attachPayload.id);
+ expect(unassignedPayload.label.name).toBe("Bug");
+ expect(unassignedPayload.type).toBe("label_unassigned");
+ });
+
+ it("bulk removeLabel deletes task-level copies without touching the workspace definition or unrelated labels", async () => {
+ const member = await createWorkspaceMember();
+ const { project, columns } = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ });
+
+ const [taskA] = await db
+ .insert(schema.taskTable)
+ .values({
+ projectId: project.id,
+ userId: member.user.id,
+ title: "Task A",
+ status: "to-do",
+ columnId: columns.todo.id,
+ priority: "medium",
+ number: 1,
+ position: 1,
+ })
+ .returning();
+
+ const [taskB] = await db
+ .insert(schema.taskTable)
+ .values({
+ projectId: project.id,
+ userId: member.user.id,
+ title: "Task B",
+ status: "to-do",
+ columnId: columns.todo.id,
+ priority: "medium",
+ number: 2,
+ position: 2,
+ })
+ .returning();
+
+ const [bugLabel] = await db
+ .insert(schema.labelTable)
+ .values({
+ name: "Bug",
+ color: "#ef4444",
+ workspaceId: member.workspace.id,
+ taskId: null,
+ })
+ .returning();
+
+ const [featureLabel] = await db
+ .insert(schema.labelTable)
+ .values({
+ name: "Feature",
+ color: "#3b82f6",
+ workspaceId: member.workspace.id,
+ taskId: null,
+ })
+ .returning();
+
+ await db.insert(schema.labelTable).values({
+ name: "Bug",
+ color: "#ef4444",
+ workspaceId: member.workspace.id,
+ taskId: taskA.id,
+ });
+
+ await db.insert(schema.labelTable).values({
+ name: "Bug",
+ color: "#ef4444",
+ workspaceId: member.workspace.id,
+ taskId: taskB.id,
+ });
+
+ await db.insert(schema.labelTable).values({
+ name: "Feature",
+ color: "#3b82f6",
+ workspaceId: member.workspace.id,
+ taskId: taskA.id,
+ });
+
+ mockAuthenticatedSession(member.user);
+ const { app } = createApp();
+
+ const response = await app.request("/api/task/bulk", {
+ method: "PATCH",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ taskIds: [taskA.id, taskB.id],
+ operation: "removeLabel",
+ value: bugLabel.id,
+ }),
+ });
+ expect(response.status).toBe(200);
+
+ const remaining = await db.query.labelTable.findMany({
+ where: eq(schema.labelTable.workspaceId, member.workspace.id),
+ });
+
+ const bugWorkspace = remaining.find(
+ (l) => l.name === "Bug" && l.taskId === null,
+ );
+ const featureWorkspace = remaining.find(
+ (l) => l.name === "Feature" && l.taskId === null,
+ );
+ const featureCopyA = remaining.find(
+ (l) => l.name === "Feature" && l.taskId === taskA.id,
+ );
+ const bugCopies = remaining.filter(
+ (l) => l.name === "Bug" && l.taskId !== null,
+ );
+
+ expect(bugWorkspace).toBeDefined();
+ expect(bugWorkspace?.id).toBe(bugLabel.id);
+ expect(bugCopies).toHaveLength(0);
+ expect(featureWorkspace).toBeDefined();
+ expect(featureWorkspace?.id).toBe(featureLabel.id);
+ expect(featureCopyA).toBeDefined();
+ });
+});
diff --git a/tests/api/github-integration/verify-github-installation.test.ts b/tests/api/github-integration/verify-github-installation.test.ts
new file mode 100644
index 000000000..20e9f740a
--- /dev/null
+++ b/tests/api/github-integration/verify-github-installation.test.ts
@@ -0,0 +1,299 @@
+import {
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from "vitest";
+import * as v from "valibot";
+
+const mockGetRepoInstallation = vi.fn();
+const mockReposGet = vi.fn();
+const mockGetInstallationOctokit = vi.fn();
+
+const mockApp = {
+ octokit: {
+ rest: {
+ apps: {
+ getRepoInstallation: (...args: unknown[]) =>
+ mockGetRepoInstallation(...args),
+ },
+ repos: {
+ get: (...args: unknown[]) => mockReposGet(...args),
+ },
+ },
+ },
+ getInstallationOctokit: (...args: unknown[]) =>
+ mockGetInstallationOctokit(...args),
+};
+
+const mockGetGithubApp = vi.fn(() => mockApp);
+
+vi.mock("../../../apps/api/src/plugins/github/utils/github-app", () => ({
+ getGithubApp: () => mockGetGithubApp(),
+}));
+
+import verifyGithubInstallation from "../../../apps/api/src/github-integration/controllers/verify-github-installation";
+
+function makeInstallationOctokit() {
+ return {
+ rest: {
+ repos: {
+ get: (...args: unknown[]) => mockReposGet(...args),
+ },
+ },
+ };
+}
+
+const originalAppName = process.env.GITHUB_APP_NAME;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mockGetGithubApp.mockReturnValue(mockApp);
+ process.env.GITHUB_APP_NAME = "kaneo-app";
+});
+
+afterEach(() => {
+ if (originalAppName === undefined) {
+ delete process.env.GITHUB_APP_NAME;
+ } else {
+ process.env.GITHUB_APP_NAME = originalAppName;
+ }
+});
+
+describe("verifyGithubInstallation", () => {
+ it("throws HTTP 500 when the GitHub App is not configured", async () => {
+ mockGetGithubApp.mockReturnValueOnce(null);
+
+ await expect(
+ verifyGithubInstallation({
+ repositoryOwner: "usekaneo",
+ repositoryName: "kaneo",
+ }),
+ ).rejects.toMatchObject({
+ status: 500,
+ });
+
+ expect(mockGetRepoInstallation).not.toHaveBeenCalled();
+ expect(mockReposGet).not.toHaveBeenCalled();
+ });
+
+ it("returns success when installation is found and has required permissions", async () => {
+ mockGetRepoInstallation.mockResolvedValue({
+ data: {
+ id: 4242,
+ permissions: { issues: "write", metadata: "read" },
+ },
+ });
+ mockGetInstallationOctokit.mockResolvedValue(makeInstallationOctokit());
+ mockReposGet.mockResolvedValue({
+ data: { id: 99, private: false },
+ });
+
+ const result = await verifyGithubInstallation({
+ repositoryOwner: "usekaneo",
+ repositoryName: "kaneo",
+ });
+
+ expect(result).toEqual({
+ isInstalled: true,
+ installationId: 4242,
+ repositoryExists: true,
+ repositoryPrivate: false,
+ permissions: { issues: "write", metadata: "read" },
+ hasRequiredPermissions: true,
+ missingPermissions: [],
+ message:
+ "GitHub App is properly installed and has all required permissions",
+ settingsUrl: "https://github.com/settings/installations/4242",
+ installationUrl:
+ "https://github.com/apps/kaneo-app/installations/new/permissions?target_id=99",
+ });
+
+ expect(mockGetRepoInstallation).toHaveBeenCalledWith({
+ owner: "usekaneo",
+ repo: "kaneo",
+ });
+ expect(mockGetInstallationOctokit).toHaveBeenCalledWith(4242);
+ expect(mockReposGet).toHaveBeenCalledTimes(1);
+ expect(mockReposGet).toHaveBeenCalledWith({
+ owner: "usekaneo",
+ repo: "kaneo",
+ });
+ });
+
+ it("reports missing permissions without surfacing an error", async () => {
+ mockGetRepoInstallation.mockResolvedValue({
+ data: {
+ id: 7777,
+ permissions: { metadata: "read" },
+ },
+ });
+ mockGetInstallationOctokit.mockResolvedValue(makeInstallationOctokit());
+ mockReposGet.mockResolvedValue({
+ data: { id: 12, private: true },
+ });
+
+ const result = await verifyGithubInstallation({
+ repositoryOwner: "usekaneo",
+ repositoryName: "kaneo",
+ });
+
+ expect(result.isInstalled).toBe(true);
+ expect(result.installationId).toBe(7777);
+ expect(result.repositoryPrivate).toBe(true);
+ expect(result.hasRequiredPermissions).toBe(false);
+ expect(result.missingPermissions).toEqual(["issues"]);
+ expect(result.message).toContain("issues");
+ expect(result.settingsUrl).toBe(
+ "https://github.com/settings/installations/7777",
+ );
+ expect(result.installationUrl).toContain("target_id=12");
+ });
+
+ it("returns a deterministic negative result when getRepoInstallation responds with 404", async () => {
+ const error = Object.assign(new Error("Not Found"), { status: 404 });
+ mockGetRepoInstallation.mockRejectedValue(error);
+
+ const result = await verifyGithubInstallation({
+ repositoryOwner: "usekaneo",
+ repositoryName: "kaneo",
+ });
+
+ expect(result).toEqual({
+ isInstalled: false,
+ installationId: null,
+ repositoryExists: null,
+ repositoryPrivate: null,
+ permissions: null,
+ hasRequiredPermissions: false,
+ missingPermissions: [],
+ message:
+ "GitHub App is not installed on this repository or the repository is not accessible",
+ installationUrl:
+ "https://github.com/apps/kaneo-app/installations/new/permissions",
+ settingsUrl: "https://github.com/apps/kaneo-app",
+ });
+
+ expect(mockReposGet).not.toHaveBeenCalled();
+ expect(mockGetInstallationOctokit).not.toHaveBeenCalled();
+ });
+
+ it("never calls repos.get on the base app octokit after a 404 from getRepoInstallation", async () => {
+ const error = Object.assign(new Error("Not Found"), { status: 404 });
+ mockGetRepoInstallation.mockRejectedValue(error);
+
+ await verifyGithubInstallation({
+ repositoryOwner: "usekaneo",
+ repositoryName: "kaneo",
+ });
+
+ expect(mockReposGet).not.toHaveBeenCalled();
+ expect(mockGetInstallationOctokit).not.toHaveBeenCalled();
+ });
+
+ it("throws HTTP 500 when the GitHub API fails with an unexpected status", async () => {
+ const error = Object.assign(new Error("Server Error"), { status: 500 });
+ mockGetRepoInstallation.mockRejectedValue(error);
+
+ await expect(
+ verifyGithubInstallation({
+ repositoryOwner: "usekaneo",
+ repositoryName: "kaneo",
+ }),
+ ).rejects.toMatchObject({
+ status: 500,
+ });
+ });
+
+ it("omits install URLs when GITHUB_APP_NAME is not configured and installation is missing", async () => {
+ delete process.env.GITHUB_APP_NAME;
+ const error = Object.assign(new Error("Not Found"), { status: 404 });
+ mockGetRepoInstallation.mockRejectedValue(error);
+
+ const result = await verifyGithubInstallation({
+ repositoryOwner: "usekaneo",
+ repositoryName: "kaneo",
+ });
+
+ expect(result.isInstalled).toBe(false);
+ expect(result.installationUrl).toBeUndefined();
+ expect(result.settingsUrl).toBeUndefined();
+ expect(result.message).toContain("not installed");
+ });
+
+ it("matches the OpenAPI verification result schema for every returned shape", async () => {
+ const verificationResultSchema = v.object({
+ isInstalled: v.boolean(),
+ installationId: v.nullable(v.number()),
+ repositoryExists: v.nullable(v.boolean()),
+ repositoryPrivate: v.nullable(v.boolean()),
+ permissions: v.nullable(v.record(v.string(), v.string())),
+ hasRequiredPermissions: v.boolean(),
+ missingPermissions: v.array(v.string()),
+ message: v.string(),
+ settingsUrl: v.optional(v.string()),
+ installationUrl: v.optional(v.string()),
+ });
+
+ const scenarios: Array<{
+ name: string;
+ mock: () => Promise<Awaited<ReturnType<typeof verifyGithubInstallation>>>;
+ }> = [];
+
+ mockGetRepoInstallation.mockResolvedValue({
+ data: {
+ id: 1,
+ permissions: { issues: "write" },
+ },
+ });
+ mockGetInstallationOctokit.mockResolvedValue(makeInstallationOctokit());
+ mockReposGet.mockResolvedValue({ data: { id: 2, private: false } });
+ scenarios.push({
+ name: "happy path",
+ mock: () =>
+ verifyGithubInstallation({
+ repositoryOwner: "usekaneo",
+ repositoryName: "kaneo",
+ }),
+ });
+
+ mockGetRepoInstallation.mockResolvedValue({
+ data: {
+ id: 2,
+ permissions: { metadata: "read" },
+ },
+ });
+ mockGetInstallationOctokit.mockResolvedValue(makeInstallationOctokit());
+ mockReposGet.mockResolvedValue({ data: { id: 3, private: true } });
+ scenarios.push({
+ name: "missing permissions",
+ mock: () =>
+ verifyGithubInstallation({
+ repositoryOwner: "usekaneo",
+ repositoryName: "kaneo",
+ }),
+ });
+
+ mockGetRepoInstallation.mockRejectedValueOnce(
+ Object.assign(new Error("Not Found"), { status: 404 }),
+ );
+ scenarios.push({
+ name: "missing installation",
+ mock: () =>
+ verifyGithubInstallation({
+ repositoryOwner: "usekaneo",
+ repositoryName: "kaneo",
+ }),
+ });
+
+ for (const scenario of scenarios) {
+ const response = await scenario.mock();
+ expect(
+ v.safeParse(verificationResultSchema, response),
+ `scenario "${scenario.name}" should match the OpenAPI schema`,
+ ).toMatchObject({ success: true });
+ }
+ });
+});
diff --git a/tests/api/label/assign-and-unassign-label.test.ts b/tests/api/label/assign-and-unassign-label.test.ts
new file mode 100644
index 000000000..d07e1e30c
--- /dev/null
+++ b/tests/api/label/assign-and-unassign-label.test.ts
@@ -0,0 +1,252 @@
+import {
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ type Mock,
+ vi,
+} from "vitest";
+
+const mockFindFirst = vi.fn();
+const mockSelect = vi.fn();
+const mockDelete = vi.fn();
+const mockInsert = vi.fn();
+const mockPublishEvent = vi.fn();
+const mockRemoveLabelFromGitHub = vi.fn();
+const mockRemoveLabelFromGitea = vi.fn();
+const mockSyncLabelToGitHub = vi.fn();
+const mockSyncLabelToGitea = vi.fn();
+
+vi.mock("../../../apps/api/src/database", () => ({
+ default: {
+ query: {
+ labelTable: {
+ findFirst: (...args: unknown[]) => mockFindFirst(...args),
+ },
+ },
+ select: (...args: unknown[]) => mockSelect(...args),
+ insert: (...args: unknown[]) => mockInsert(...args),
+ delete: (...args: unknown[]) => mockDelete(...args),
+ },
+}));
+
+vi.mock("../../../apps/api/src/events", () => ({
+ publishEvent: (...args: unknown[]) => mockPublishEvent(...args),
+}));
+
+vi.mock(
+ "../../../apps/api/src/plugins/github/utils/sync-label-to-github",
+ () => ({
+ removeLabelFromGitHub: (...args: unknown[]) =>
+ mockRemoveLabelFromGitHub(...args),
+ syncLabelToGitHub: (...args: unknown[]) => mockSyncLabelToGitHub(...args),
+ }),
+);
+
+vi.mock(
+ "../../../apps/api/src/plugins/gitea/utils/sync-label-to-gitea",
+ () => ({
+ removeLabelFromGitea: (...args: unknown[]) =>
+ mockRemoveLabelFromGitea(...args),
+ syncLabelToGitea: (...args: unknown[]) => mockSyncLabelToGitea(...args),
+ }),
+);
+
+import unassignLabelFromTask from "../../../apps/api/src/label/controllers/unassign-label-from-task";
+import assignLabelToTask from "../../../apps/api/src/label/controllers/assign-label-to-task";
+
+const WORKSPACE_LABEL = {
+ id: "label-ws-1",
+ name: "bug",
+ color: "EF4444",
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ taskId: null,
+ workspaceId: "ws-1",
+};
+
+const TASK_LABEL = {
+ id: "label-task-1",
+ name: "bug",
+ color: "EF4444",
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ taskId: "task-1",
+ workspaceId: "ws-1",
+};
+
+const TASK = {
+ id: "task-1",
+ projectId: "proj-1",
+ workspaceId: "ws-1",
+};
+
+function makeSelectMock(rows: unknown[]) {
+ const chain: Record<string, Mock> = {
+ from: vi.fn(() => chain),
+ innerJoin: vi.fn(() => chain),
+ where: vi.fn(() => chain),
+ limit: vi.fn(() => Promise.resolve(rows)),
+ };
+ return chain;
+}
+
+function makeDeleteMock(deletedRow: unknown) {
+ const whereResult = Object.assign(Promise.resolve(undefined), {
+ returning: vi.fn(() => Promise.resolve([deletedRow])),
+ });
+ return {
+ where: vi.fn(() => whereResult),
+ };
+}
+
+function makeInsertMock(insertedRow: unknown) {
+ const onConflictResult = Object.assign(Promise.resolve(undefined), {
+ returning: vi.fn(() => Promise.resolve([insertedRow])),
+ });
+ const onConflict = vi.fn(() => onConflictResult);
+ const values = vi.fn(() => ({ onConflictDoNothing: onConflict }));
+ return { values, onConflict };
+}
+
+describe("unassignLabelFromTask", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("deletes the task assignment instead of nulling taskId", async () => {
+ mockFindFirst.mockResolvedValue(TASK_LABEL);
+ mockSelect.mockReturnValue(makeSelectMock([TASK]));
+ mockDelete.mockReturnValue(makeDeleteMock(TASK_LABEL));
+ mockRemoveLabelFromGitHub.mockResolvedValue(undefined);
+
+ await unassignLabelFromTask("label-task-1", "user-1");
+
+ expect(mockDelete).toHaveBeenCalledTimes(1);
+ expect(mockPublishEvent).toHaveBeenCalledWith("task.label_unassigned", {
+ label: TASK_LABEL,
+ task: TASK,
+ projectId: TASK.projectId,
+ taskId: TASK_LABEL.taskId,
+ userId: "user-1",
+ type: "label_unassigned",
+ });
+ });
+
+ it("calls removeLabelFromGitHub with the deleted task's id and name", async () => {
+ mockFindFirst.mockResolvedValue(TASK_LABEL);
+ mockSelect.mockReturnValue(makeSelectMock([TASK]));
+ mockDelete.mockReturnValue(makeDeleteMock(TASK_LABEL));
+ mockRemoveLabelFromGitHub.mockResolvedValue(undefined);
+
+ await unassignLabelFromTask("label-task-1", "user-1");
+
+ expect(mockRemoveLabelFromGitHub).toHaveBeenCalledWith("task-1", "bug");
+ });
+
+ it("rejects when the label is a workspace definition (taskId is null)", async () => {
+ mockFindFirst.mockResolvedValue(WORKSPACE_LABEL);
+
+ await expect(unassignLabelFromTask("label-ws-1", "user-1")).rejects.toMatchObject(
+ {
+ status: 400,
+ },
+ );
+ expect(mockDelete).not.toHaveBeenCalled();
+ expect(mockPublishEvent).not.toHaveBeenCalled();
+ });
+});
+
+describe("assignLabelToTask", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("creates a task-level copy without mutating the workspace definition", async () => {
+ mockFindFirst.mockResolvedValueOnce(WORKSPACE_LABEL);
+ mockSelect.mockReturnValue(makeSelectMock([TASK]));
+ const insertedCopy = { ...TASK_LABEL, id: "label-task-2" };
+ const insertChain = makeInsertMock(insertedCopy);
+ mockInsert.mockReturnValue(insertChain);
+ mockSyncLabelToGitHub.mockResolvedValue(undefined);
+ mockSyncLabelToGitea.mockResolvedValue(undefined);
+
+ const result = await assignLabelToTask("label-ws-1", "task-1", "user-1");
+
+ expect(result).toEqual(insertedCopy);
+ expect(mockInsert).toHaveBeenCalledTimes(1);
+ expect(mockDelete).not.toHaveBeenCalled();
+ expect(insertChain.onConflict).toHaveBeenCalledWith({
+ target: [expect.anything(), expect.anything()],
+ });
+ expect(mockPublishEvent).toHaveBeenCalledWith("task.label_assigned", {
+ label: insertedCopy,
+ task: TASK,
+ projectId: TASK.projectId,
+ taskId: TASK.id,
+ userId: "user-1",
+ type: "label_assigned",
+ });
+ expect(mockSyncLabelToGitHub).toHaveBeenCalledWith(
+ "task-1",
+ "bug",
+ "EF4444",
+ );
+ expect(mockSyncLabelToGitea).toHaveBeenCalledWith(
+ "task-1",
+ "bug",
+ "EF4444",
+ );
+ });
+
+ it("is idempotent when the same label is already attached to the same task", async () => {
+ mockFindFirst.mockResolvedValueOnce({ ...TASK_LABEL, taskId: "task-1" });
+ mockSelect.mockReturnValue(makeSelectMock([TASK]));
+
+ const result = await assignLabelToTask("label-task-1", "task-1", "user-1");
+
+ expect(result).toEqual({ ...TASK_LABEL, taskId: "task-1" });
+ expect(mockInsert).not.toHaveBeenCalled();
+ expect(mockDelete).not.toHaveBeenCalled();
+ expect(mockPublishEvent).not.toHaveBeenCalled();
+ });
+
+ it("removes the stale task copy when moving the label to a different task", async () => {
+ const stale = { ...TASK_LABEL, taskId: "task-old" };
+ mockFindFirst.mockResolvedValueOnce(stale);
+ mockSelect.mockReturnValue(makeSelectMock([TASK]));
+ mockDelete.mockReturnValue(makeDeleteMock(stale));
+ const insertedCopy = { ...TASK_LABEL, id: "label-task-2" };
+ const insertChain = makeInsertMock(insertedCopy);
+ mockInsert.mockReturnValue(insertChain);
+ mockRemoveLabelFromGitHub.mockResolvedValue(undefined);
+ mockRemoveLabelFromGitea.mockResolvedValue(undefined);
+ mockSyncLabelToGitHub.mockResolvedValue(undefined);
+ mockSyncLabelToGitea.mockResolvedValue(undefined);
+
+ await assignLabelToTask("label-task-1", "task-1", "user-1");
+
+ expect(mockRemoveLabelFromGitHub).toHaveBeenCalledWith("task-old", "bug");
+ expect(mockRemoveLabelFromGitea).toHaveBeenCalledWith("task-old", "bug");
+ expect(mockSyncLabelToGitHub).toHaveBeenCalledWith(
+ "task-1",
+ "bug",
+ "EF4444",
+ );
+ expect(mockPublishEvent).toHaveBeenCalledWith(
+ "task.label_assigned",
+ expect.objectContaining({
+ taskId: "task-1",
+ }),
+ );
+ });
+});