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): coderabbit/qodo reviews

justin22f6f8fc253c
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 093380442..e55d2db46 100644
--- a/apps/api/src/github-integration/controllers/verify-github-installation.ts
+++ b/apps/api/src/github-integration/controllers/verify-github-installation.ts
@@ -81,13 +81,41 @@ async function verifyGithubInstallation({
});
}
- const installationOctokit = await githubApp.getInstallationOctokit(
- installation.id,
- );
- const { data: repo } = await installationOctokit.rest.repos.get({
- owner: repositoryOwner,
- repo: repositoryName,
- });
+ let repo: {
+ id: number;
+ private: boolean;
+ owner: { id: number; login: string };
+ };
+ try {
+ const installationOctokit = await githubApp.getInstallationOctokit(
+ installation.id,
+ );
+ const { data } = await installationOctokit.rest.repos.get({
+ owner: repositoryOwner,
+ repo: repositoryName,
+ });
+ repo = data;
+ } catch (error) {
+ if (isGithubNotFound(error)) {
+ return {
+ isInstalled: true,
+ installationId: installation.id,
+ repositoryExists: false,
+ repositoryPrivate: null,
+ permissions: installation.permissions ?? null,
+ hasRequiredPermissions: false,
+ missingPermissions: [],
+ message:
+ "GitHub App is installed but the repository is no longer accessible",
+ settingsUrl: settingsUrlFor(installation.id),
+ installationUrl: appInstallUrl(),
+ };
+ }
+
+ throw new HTTPException(500, {
+ message: `Failed to verify GitHub installation: ${(error as Error).message || "Unknown error"}`,
+ });
+ }
const requiredPermissions = ["issues"];
const hasRequiredPermissions = checkPermissions(
@@ -98,6 +126,7 @@ async function verifyGithubInstallation({
installation.permissions,
requiredPermissions,
);
+ const accountId = repo.owner.id;
if (!hasRequiredPermissions) {
return {
@@ -105,12 +134,12 @@ async function verifyGithubInstallation({
installationId: installation.id,
repositoryExists: true,
repositoryPrivate: repo.private,
- permissions: installation.permissions,
+ permissions: installation.permissions ?? null,
hasRequiredPermissions: false,
missingPermissions,
message: `GitHub App is installed but missing required permissions: ${missingPermissions.join(", ")}`,
settingsUrl: settingsUrlFor(installation.id),
- installationUrl: newInstallUrl(repo.id),
+ installationUrl: newInstallUrl(accountId),
};
}
@@ -119,13 +148,13 @@ async function verifyGithubInstallation({
installationId: installation.id,
repositoryExists: true,
repositoryPrivate: repo.private,
- permissions: installation.permissions,
+ permissions: installation.permissions ?? null,
hasRequiredPermissions: true,
missingPermissions: [],
message:
"GitHub App is properly installed and has all required permissions",
settingsUrl: settingsUrlFor(installation.id),
- installationUrl: newInstallUrl(repo.id),
+ installationUrl: newInstallUrl(accountId),
};
}
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 1ec1fb218..fe6c4a825 100644
--- a/apps/api/src/label/controllers/assign-label-to-task.ts
+++ b/apps/api/src/label/controllers/assign-label-to-task.ts
@@ -1,7 +1,12 @@
import { and, eq } from "drizzle-orm";
import { HTTPException } from "hono/http-exception";
import db from "../../database";
-import { labelTable, projectTable, taskTable } from "../../database/schema";
+import {
+ labelTable,
+ type labelTable as labelTableType,
+ projectTable,
+ taskTable,
+} from "../../database/schema";
import { publishEvent } from "../../events";
import {
removeLabelFromGitea,
@@ -12,6 +17,8 @@ import {
syncLabelToGitHub,
} from "../../plugins/github/utils/sync-label-to-github";
+type LabelRow = typeof labelTableType.$inferSelect;
+
async function assignLabelToTask(id: string, taskId: string, userId: string) {
const label = await db.query.labelTable.findFirst({
where: (label, { eq }) => eq(label.id, id),
@@ -50,12 +57,52 @@ async function assignLabelToTask(id: string, taskId: string, userId: string) {
return label;
}
- if (label.taskId && label.taskId !== taskId) {
- const previousTaskId = label.taskId;
- const previousName = label.name;
-
- await db.delete(labelTable).where(eq(labelTable.id, id));
-
+ const previousTaskId =
+ label.taskId && label.taskId !== taskId ? label.taskId : null;
+ const previousName = label.name;
+
+ type InsertionResult = { taskLabel: LabelRow; inserted: boolean };
+ const { taskLabel, inserted } = await db.transaction<InsertionResult>(
+ async (tx) => {
+ if (previousTaskId) {
+ await tx.delete(labelTable).where(eq(labelTable.id, id));
+ }
+
+ const [insertedRow] = await tx
+ .insert(labelTable)
+ .values({
+ name: label.name,
+ color: label.color,
+ taskId,
+ workspaceId: task.workspaceId,
+ })
+ .onConflictDoNothing({
+ target: [labelTable.taskId, labelTable.name],
+ })
+ .returning();
+
+ if (insertedRow) {
+ return { taskLabel: insertedRow, inserted: true };
+ }
+
+ const existing = await tx.query.labelTable.findFirst({
+ where: and(
+ eq(labelTable.taskId, taskId),
+ eq(labelTable.name, label.name),
+ ),
+ });
+
+ if (!existing) {
+ throw new HTTPException(500, {
+ message: "Failed to attach label to task",
+ });
+ }
+
+ return { taskLabel: existing, inserted: false };
+ },
+ );
+
+ if (previousTaskId) {
removeLabelFromGitHub(previousTaskId, previousName).catch((error) => {
console.error("Failed to remove label from GitHub:", error);
});
@@ -64,32 +111,8 @@ async function assignLabelToTask(id: string, taskId: string, userId: string) {
});
}
- 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",
- });
+ if (!inserted) {
+ return taskLabel;
}
syncLabelToGitHub(taskId, taskLabel.name, taskLabel.color).catch((error) => {
diff --git a/apps/api/src/task/controllers/bulk-update-tasks.ts b/apps/api/src/task/controllers/bulk-update-tasks.ts
index 384c50166..146851860 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, isNotNull } from "drizzle-orm";
+import { and, eq, inArray } from "drizzle-orm";
import { HTTPException } from "hono/http-exception";
import db from "../../database";
import {
@@ -278,9 +278,8 @@ async function bulkUpdateTasks({
.delete(labelTable)
.where(
and(
- eq(labelTable.workspaceId, label.workspaceId),
+ eq(labelTable.workspaceId, workspaceId),
eq(labelTable.name, label.name),
- isNotNull(labelTable.taskId),
inArray(labelTable.taskId, foundIds),
),
)
diff --git a/tests/api-integration/label-detach.test.ts b/tests/api-integration/label-detach.test.ts
index 740fc6237..5fb0715bc 100644
--- a/tests/api-integration/label-detach.test.ts
+++ b/tests/api-integration/label-detach.test.ts
@@ -29,11 +29,7 @@ function initEventSubscribers() {
});
}
-async function seedTask(
- userId: string,
- workspaceId: string,
- projectId: string,
-) {
+async function seedTask(userId: string, projectId: string) {
return db
.insert(schema.taskTable)
.values({
@@ -60,11 +56,7 @@ describe("API integration: label detach/attach", () => {
const { project } = await createProjectFixture({
workspaceId: member.workspace.id,
});
- const [task] = await seedTask(
- member.user.id,
- member.workspace.id,
- project.id,
- );
+ const [task] = await seedTask(member.user.id, project.id);
const [workspaceLabel] = await db
.insert(schema.labelTable)
@@ -99,11 +91,7 @@ describe("API integration: label detach/attach", () => {
const { project } = await createProjectFixture({
workspaceId: member.workspace.id,
});
- const [task] = await seedTask(
- member.user.id,
- member.workspace.id,
- project.id,
- );
+ const [task] = await seedTask(member.user.id, project.id);
mockAuthenticatedSession(member.user);
const { app } = createApp();
@@ -153,11 +141,7 @@ describe("API integration: label detach/attach", () => {
const { project } = await createProjectFixture({
workspaceId: member.workspace.id,
});
- const [task] = await seedTask(
- member.user.id,
- member.workspace.id,
- project.id,
- );
+ const [task] = await seedTask(member.user.id, project.id);
const [label] = await db
.insert(schema.labelTable)
@@ -196,16 +180,54 @@ describe("API integration: label detach/attach", () => {
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 () => {
+ it("does not republish task.label_assigned when re-attaching the same workspace label", 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 [task] = await seedTask(member.user.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);
+
+ recordedEvents.length = 0;
+
+ 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 assignedEvents = recordedEvents.filter(
+ (e) => e.type === "task.label_assigned",
);
+ expect(assignedEvents).toHaveLength(0);
+ });
+
+ 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, project.id);
const [workspaceLabel] = await db
.insert(schema.labelTable)
@@ -248,11 +270,7 @@ describe("API integration: label detach/attach", () => {
const { project } = await createProjectFixture({
workspaceId: member.workspace.id,
});
- const [task] = await seedTask(
- member.user.id,
- member.workspace.id,
- project.id,
- );
+ const [task] = await seedTask(member.user.id, project.id);
const [workspaceLabel] = await db
.insert(schema.labelTable)
@@ -292,14 +310,28 @@ describe("API integration: label detach/attach", () => {
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();
+ await db.insert(schema.labelTable).values({
+ name: "Bug",
+ color: "#ef4444",
+ workspaceId: member.workspace.id,
+ taskId: task.id,
+ });
+
+ const reattachedRows = await db.query.labelTable.findMany({
+ where: and(
+ eq(schema.labelTable.workspaceId, member.workspace.id),
+ eq(schema.labelTable.name, "Bug"),
+ ),
+ });
+ const reattachedTaskRows = reattachedRows.filter((l) => l.taskId !== null);
+ const reattachedWorkspaceRows = reattachedRows.filter(
+ (l) => l.taskId === null,
+ );
+
+ expect(reattachedTaskRows).toHaveLength(1);
+ expect(reattachedTaskRows[0].taskId).toBe(task.id);
+ expect(reattachedWorkspaceRows).toHaveLength(1);
+ expect(reattachedWorkspaceRows[0].id).toBe(workspaceLabel.id);
});
it("emits task.label_assigned and task.label_unassigned events through detach/attach", async () => {
@@ -307,11 +339,7 @@ describe("API integration: label detach/attach", () => {
const { project } = await createProjectFixture({
workspaceId: member.workspace.id,
});
- const [task] = await seedTask(
- member.user.id,
- member.workspace.id,
- project.id,
- );
+ const [task] = await seedTask(member.user.id, project.id);
const [label] = await db
.insert(schema.labelTable)
@@ -466,6 +494,12 @@ describe("API integration: label detach/attach", () => {
}),
});
expect(response.status).toBe(200);
+ const payload = (await response.json()) as {
+ success: boolean;
+ updatedCount: number;
+ };
+ expect(payload.success).toBe(true);
+ expect(payload.updatedCount).toBe(2);
const remaining = await db.query.labelTable.findMany({
where: eq(schema.labelTable.workspaceId, member.workspace.id),
@@ -490,5 +524,25 @@ describe("API integration: label detach/attach", () => {
expect(featureWorkspace).toBeDefined();
expect(featureWorkspace?.id).toBe(featureLabel.id);
expect(featureCopyA).toBeDefined();
+
+ const unassignedEvents = recordedEvents.filter(
+ (e) => e.type === "task.label_unassigned",
+ );
+ expect(unassignedEvents).toHaveLength(2);
+
+ const eventTaskIds = unassignedEvents
+ .map((e) => (e.data as { taskId: string }).taskId)
+ .sort();
+ expect(eventTaskIds).toEqual([taskA.id, taskB.id].sort());
+
+ for (const event of unassignedEvents) {
+ const data = event.data as {
+ label: { id: string; name: string };
+ taskId: string;
+ userId: string;
+ };
+ expect(data.label.name).toBe("Bug");
+ expect(data.userId).toBe(member.user.id);
+ }
});
});
diff --git a/tests/api/github-integration/verify-github-installation.test.ts b/tests/api/github-integration/verify-github-installation.test.ts
index 8b26ee7c8..b10caf53e 100644
--- a/tests/api/github-integration/verify-github-installation.test.ts
+++ b/tests/api/github-integration/verify-github-installation.test.ts
@@ -81,7 +81,7 @@ describe("verifyGithubInstallation", () => {
});
mockGetInstallationOctokit.mockResolvedValue(makeInstallationOctokit());
mockReposGet.mockResolvedValue({
- data: { id: 99, private: false },
+ data: { id: 99, private: false, owner: { id: 555, login: "usekaneo" } },
});
const result = await verifyGithubInstallation({
@@ -101,7 +101,7 @@ describe("verifyGithubInstallation", () => {
"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",
+ "https://github.com/apps/kaneo-app/installations/new/permissions?target_id=555",
});
expect(mockGetRepoInstallation).toHaveBeenCalledWith({
@@ -125,7 +125,7 @@ describe("verifyGithubInstallation", () => {
});
mockGetInstallationOctokit.mockResolvedValue(makeInstallationOctokit());
mockReposGet.mockResolvedValue({
- data: { id: 12, private: true },
+ data: { id: 12, private: true, owner: { id: 888, login: "usekaneo" } },
});
const result = await verifyGithubInstallation({
@@ -142,7 +142,7 @@ describe("verifyGithubInstallation", () => {
expect(result.settingsUrl).toBe(
"https://github.com/settings/installations/7777",
);
- expect(result.installationUrl).toContain("target_id=12");
+ expect(result.installationUrl).toContain("target_id=888");
});
it("returns a deterministic negative result when getRepoInstallation responds with 404", async () => {
@@ -200,6 +200,74 @@ describe("verifyGithubInstallation", () => {
});
});
+ it("wraps getInstallationOctokit failures as HTTP 500", async () => {
+ mockGetRepoInstallation.mockResolvedValue({
+ data: { id: 4242, permissions: { issues: "write" } },
+ });
+ mockGetInstallationOctokit.mockRejectedValue(
+ Object.assign(new Error("token exchange failed"), { status: 500 }),
+ );
+
+ await expect(
+ verifyGithubInstallation({
+ repositoryOwner: "usekaneo",
+ repositoryName: "kaneo",
+ }),
+ ).rejects.toMatchObject({
+ status: 500,
+ });
+
+ expect(mockReposGet).not.toHaveBeenCalled();
+ });
+
+ it("returns a deterministic negative result when repos.get responds with 404", async () => {
+ mockGetRepoInstallation.mockResolvedValue({
+ data: { id: 4242, permissions: { issues: "write" } },
+ });
+ mockGetInstallationOctokit.mockResolvedValue(makeInstallationOctokit());
+ mockReposGet.mockRejectedValue(
+ Object.assign(new Error("Not Found"), { status: 404 }),
+ );
+
+ const result = await verifyGithubInstallation({
+ repositoryOwner: "usekaneo",
+ repositoryName: "kaneo",
+ });
+
+ expect(result).toEqual({
+ isInstalled: true,
+ installationId: 4242,
+ repositoryExists: false,
+ repositoryPrivate: null,
+ permissions: { issues: "write" },
+ hasRequiredPermissions: false,
+ missingPermissions: [],
+ message:
+ "GitHub App is installed but the repository is no longer accessible",
+ settingsUrl: "https://github.com/settings/installations/4242",
+ installationUrl: "https://github.com/apps/kaneo-app",
+ });
+ });
+
+ it("wraps repos.get failures as HTTP 500 when the status is not 404", async () => {
+ mockGetRepoInstallation.mockResolvedValue({
+ data: { id: 4242, permissions: { issues: "write" } },
+ });
+ mockGetInstallationOctokit.mockResolvedValue(makeInstallationOctokit());
+ mockReposGet.mockRejectedValue(
+ Object.assign(new Error("Server Error"), { status: 500 }),
+ );
+
+ 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 });
@@ -216,6 +284,24 @@ describe("verifyGithubInstallation", () => {
expect(result.message).toContain("not installed");
});
+ it("normalizes a missing installation.permissions to null on the success path", async () => {
+ mockGetRepoInstallation.mockResolvedValue({
+ data: { id: 4242, permissions: undefined },
+ });
+ mockGetInstallationOctokit.mockResolvedValue(makeInstallationOctokit());
+ mockReposGet.mockResolvedValue({
+ data: { id: 99, private: false, owner: { id: 555, login: "usekaneo" } },
+ });
+
+ const result = await verifyGithubInstallation({
+ repositoryOwner: "usekaneo",
+ repositoryName: "kaneo",
+ });
+
+ expect(result.permissions).toBeNull();
+ expect(result.hasRequiredPermissions).toBe(false);
+ });
+
it("matches the OpenAPI verification result schema for every returned shape", async () => {
const verificationResultSchema = v.object({
isInstalled: v.boolean(),
@@ -242,7 +328,9 @@ describe("verifyGithubInstallation", () => {
},
});
mockGetInstallationOctokit.mockResolvedValue(makeInstallationOctokit());
- mockReposGet.mockResolvedValue({ data: { id: 2, private: false } });
+ mockReposGet.mockResolvedValue({
+ data: { id: 2, private: false, owner: { id: 100, login: "usekaneo" } },
+ });
scenarios.push({
name: "happy path",
mock: () =>
@@ -259,7 +347,9 @@ describe("verifyGithubInstallation", () => {
},
});
mockGetInstallationOctokit.mockResolvedValue(makeInstallationOctokit());
- mockReposGet.mockResolvedValue({ data: { id: 3, private: true } });
+ mockReposGet.mockResolvedValue({
+ data: { id: 3, private: true, owner: { id: 200, login: "usekaneo" } },
+ });
scenarios.push({
name: "missing permissions",
mock: () =>
@@ -281,6 +371,22 @@ describe("verifyGithubInstallation", () => {
}),
});
+ mockGetRepoInstallation.mockResolvedValue({
+ data: { id: 4, permissions: { issues: "write" } },
+ });
+ mockGetInstallationOctokit.mockResolvedValue(makeInstallationOctokit());
+ mockReposGet.mockRejectedValueOnce(
+ Object.assign(new Error("Not Found"), { status: 404 }),
+ );
+ scenarios.push({
+ name: "installed but repo inaccessible",
+ mock: () =>
+ verifyGithubInstallation({
+ repositoryOwner: "usekaneo",
+ repositoryName: "kaneo",
+ }),
+ });
+
for (const scenario of scenarios) {
const response = await scenario.mock();
expect(
diff --git a/tests/api/label/assign-and-unassign-label.test.ts b/tests/api/label/assign-and-unassign-label.test.ts
index 579ef782a..f4a93119c 100644
--- a/tests/api/label/assign-and-unassign-label.test.ts
+++ b/tests/api/label/assign-and-unassign-label.test.ts
@@ -18,6 +18,18 @@ const mockRemoveLabelFromGitea = vi.fn();
const mockSyncLabelToGitHub = vi.fn();
const mockSyncLabelToGitea = vi.fn();
+const mockTransaction = vi.fn(async (cb: (tx: unknown) => unknown) =>
+ cb({
+ insert: (...args: unknown[]) => mockInsert(...args),
+ delete: (...args: unknown[]) => mockDelete(...args),
+ query: {
+ labelTable: {
+ findFirst: (...args: unknown[]) => mockFindFirst(...args),
+ },
+ },
+ }),
+);
+
vi.mock("../../../apps/api/src/database", () => ({
default: {
query: {
@@ -28,6 +40,7 @@ vi.mock("../../../apps/api/src/database", () => ({
select: (...args: unknown[]) => mockSelect(...args),
insert: (...args: unknown[]) => mockInsert(...args),
delete: (...args: unknown[]) => mockDelete(...args),
+ transaction: (...args: unknown[]) => mockTransaction(...args),
},
}));
@@ -112,7 +125,18 @@ function makeInsertMock(insertedRow: unknown) {
describe("unassignLabelFromTask", () => {
beforeEach(() => {
- vi.clearAllMocks();
+ vi.resetAllMocks();
+ mockTransaction.mockImplementation(async (cb: (tx: unknown) => unknown) =>
+ cb({
+ insert: (...args: unknown[]) => mockInsert(...args),
+ delete: (...args: unknown[]) => mockDelete(...args),
+ query: {
+ labelTable: {
+ findFirst: (...args: unknown[]) => mockFindFirst(...args),
+ },
+ },
+ }),
+ );
});
afterEach(() => {
@@ -164,7 +188,18 @@ describe("unassignLabelFromTask", () => {
describe("assignLabelToTask", () => {
beforeEach(() => {
- vi.clearAllMocks();
+ vi.resetAllMocks();
+ mockTransaction.mockImplementation(async (cb: (tx: unknown) => unknown) =>
+ cb({
+ insert: (...args: unknown[]) => mockInsert(...args),
+ delete: (...args: unknown[]) => mockDelete(...args),
+ query: {
+ labelTable: {
+ findFirst: (...args: unknown[]) => mockFindFirst(...args),
+ },
+ },
+ }),
+ );
});
afterEach(() => {
@@ -249,4 +284,52 @@ describe("assignLabelToTask", () => {
}),
);
});
+
+ it("is idempotent when the workspace label is re-attached to the same task", async () => {
+ mockFindFirst.mockResolvedValueOnce(WORKSPACE_LABEL);
+ mockSelect.mockReturnValue(makeSelectMock([TASK]));
+ const insertChain = makeInsertMock(undefined);
+ mockInsert.mockReturnValue(insertChain);
+ mockFindFirst.mockResolvedValueOnce(TASK_LABEL);
+
+ const result = await assignLabelToTask("label-ws-1", "task-1", "user-1");
+
+ expect(result).toEqual(TASK_LABEL);
+ expect(mockInsert).toHaveBeenCalledTimes(1);
+ expect(mockSyncLabelToGitHub).not.toHaveBeenCalled();
+ expect(mockSyncLabelToGitea).not.toHaveBeenCalled();
+ expect(mockPublishEvent).not.toHaveBeenCalled();
+ });
+
+ it("falls back to the existing task label when the workspace insert returns no row", async () => {
+ mockFindFirst.mockResolvedValueOnce(WORKSPACE_LABEL);
+ mockSelect.mockReturnValue(makeSelectMock([TASK]));
+ const insertChain = makeInsertMock(undefined);
+ mockInsert.mockReturnValue(insertChain);
+ mockFindFirst.mockResolvedValueOnce(TASK_LABEL);
+
+ await assignLabelToTask("label-ws-1", "task-1", "user-1");
+
+ expect(mockTransaction).toHaveBeenCalledTimes(1);
+ expect(mockInsert).toHaveBeenCalledTimes(1);
+ expect(mockFindFirst).toHaveBeenCalledTimes(2);
+ });
+
+ it("throws HTTP 500 when the insert and fallback lookup both return no row", async () => {
+ mockFindFirst.mockResolvedValueOnce(WORKSPACE_LABEL);
+ mockSelect.mockReturnValue(makeSelectMock([TASK]));
+ const insertChain = makeInsertMock(undefined);
+ mockInsert.mockReturnValue(insertChain);
+ mockFindFirst.mockResolvedValueOnce(undefined);
+
+ await expect(
+ assignLabelToTask("label-ws-1", "task-1", "user-1"),
+ ).rejects.toMatchObject({
+ status: 500,
+ });
+
+ expect(mockSyncLabelToGitHub).not.toHaveBeenCalled();
+ expect(mockSyncLabelToGitea).not.toHaveBeenCalled();
+ expect(mockPublishEvent).not.toHaveBeenCalled();
+ });
});