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): bound label scopes and sync custom final states

Tined62deb6ce2b
diff --git a/apps/api/src/integration-sync/controllers/preview-rules.ts b/apps/api/src/integration-sync/controllers/preview-rules.ts
index 10856c8a8..13b319b82 100644
--- a/apps/api/src/integration-sync/controllers/preview-rules.ts
+++ b/apps/api/src/integration-sync/controllers/preview-rules.ts
@@ -17,6 +17,7 @@ export async function previewSyncRules(
integration.project.workspaceId,
rules.outgoing,
database,
+ true,
);
const current = await outgoingPredicate(
integration.project.workspaceId,
diff --git a/apps/api/src/plugins/gitea/events/task-status-changed.ts b/apps/api/src/plugins/gitea/events/task-status-changed.ts
index b3f2a2cdd..0d9b65560 100644
--- a/apps/api/src/plugins/gitea/events/task-status-changed.ts
+++ b/apps/api/src/plugins/gitea/events/task-status-changed.ts
@@ -1,6 +1,7 @@
import { syncTaskFieldLabels } from "../../sync/sync-task-field-labels";
import { canSyncTask } from "../../sync/eligibility";
import { syncLatestTaskValue } from "../../github/services/sync-latest-task-value";
+import { isTaskInFinalState } from "../../github/services/task-service";
import { findExternalLinksByTask } from "../../github/services/link-manager";
import type { PluginContext, TaskStatusChangedEvent } from "../../types";
import type { GiteaConfig } from "../config";
@@ -56,13 +57,25 @@ export async function handleTaskStatusChanged(
},
);
if (currentValue === undefined) return;
- if (currentValue === "done" || event.oldStatus === "done") {
+ const closing = await isTaskInFinalState({
+ projectId: event.projectId,
+ status: currentValue,
+ columnId: null,
+ });
+ const reopening =
+ !closing &&
+ (await isTaskInFinalState({
+ projectId: event.projectId,
+ status: event.oldStatus,
+ columnId: null,
+ }));
+ if (closing || reopening) {
await syncLatestTaskValue(
event.taskId,
event.projectId,
issueLink,
"state",
- currentValue === "done" ? "closed" : "open",
+ closing ? "closed" : "open",
async (value) => {
const response = await client.updateIssue(
repositoryOwner,
diff --git a/apps/api/src/plugins/github/events/task-status-changed.ts b/apps/api/src/plugins/github/events/task-status-changed.ts
index 54ffc9f97..646615211 100644
--- a/apps/api/src/plugins/github/events/task-status-changed.ts
+++ b/apps/api/src/plugins/github/events/task-status-changed.ts
@@ -1,6 +1,7 @@
import { syncTaskFieldLabels } from "../../sync/sync-task-field-labels";
import { canSyncTask } from "../../sync/eligibility";
import { syncLatestTaskValue } from "../services/sync-latest-task-value";
+import { isTaskInFinalState } from "../services/task-service";
import type { PluginContext, TaskStatusChangedEvent } from "../../types";
import { type GitHubConfig, hasVerifiedGitHubBinding } from "../config";
import { findExternalLinksByTask } from "../services/link-manager";
@@ -76,13 +77,25 @@ export async function handleTaskStatusChanged(
},
);
if (currentValue === undefined) return;
- if (currentValue === "done" || event.oldStatus === "done") {
+ const closing = await isTaskInFinalState({
+ projectId: event.projectId,
+ status: currentValue,
+ columnId: null,
+ });
+ const reopening =
+ !closing &&
+ (await isTaskInFinalState({
+ projectId: event.projectId,
+ status: event.oldStatus,
+ columnId: null,
+ }));
+ if (closing || reopening) {
await syncLatestTaskValue(
event.taskId,
event.projectId,
issueLink,
"state",
- currentValue === "done" ? "closed" : "open",
+ closing ? "closed" : "open",
async (value) => {
const response = await octokit.rest.issues.update({
owner: repositoryOwner,
diff --git a/apps/api/src/plugins/gitlab/events/task-status-changed.ts b/apps/api/src/plugins/gitlab/events/task-status-changed.ts
index 9cc655173..7a1513c94 100644
--- a/apps/api/src/plugins/gitlab/events/task-status-changed.ts
+++ b/apps/api/src/plugins/gitlab/events/task-status-changed.ts
@@ -1,6 +1,7 @@
import { createIssueWrite } from "../../sync/dispatch-issue-write";
import { syncTaskFieldLabels } from "../../sync/sync-task-field-labels";
import { canSyncTask } from "../../sync/eligibility";
+import { isTaskInFinalState } from "../../github/services/task-service";
import {
findExternalLinksByTask,
updateExternalLink,
@@ -69,8 +70,18 @@ export async function handleTaskStatusChanged(
JSON.stringify(context.config),
);
- const closing = currentValue === "done";
- const reopening = event.oldStatus === "done" && currentValue !== "done";
+ const closing = await isTaskInFinalState({
+ projectId: event.projectId,
+ status: currentValue,
+ columnId: null,
+ });
+ const reopening =
+ !closing &&
+ (await isTaskInFinalState({
+ projectId: event.projectId,
+ status: event.oldStatus,
+ columnId: null,
+ }));
if (!closing && !reopening) {
return;
diff --git a/apps/api/src/plugins/sync/task-predicate.ts b/apps/api/src/plugins/sync/task-predicate.ts
index 72b9dcee9..48676c84a 100644
--- a/apps/api/src/plugins/sync/task-predicate.ts
+++ b/apps/api/src/plugins/sync/task-predicate.ts
@@ -1,4 +1,4 @@
-import { and, asc, eq, isNull, sql } from "drizzle-orm";
+import { and, asc, eq, inArray, isNull, sql } from "drizzle-orm";
import db from "../../database";
import { labelTable, taskTable } from "../../database/schema";
import type { IntegrationDatabase } from "../github/services/integration-task-scope";
@@ -8,22 +8,31 @@ export async function outgoingPredicate(
workspaceId: string,
rule: LabelRule,
database: IntegrationDatabase = db,
+ includeAllLabels = false,
) {
- const labels = await database
- .select({
- id: labelTable.id,
- name: labelTable.name,
- color: labelTable.color,
- })
- .from(labelTable)
- .where(
- and(
- eq(labelTable.workspaceId, workspaceId),
- isNull(labelTable.taskId),
- isNull(labelTable.deletionStartedAt),
- ),
- )
- .orderBy(asc(labelTable.id));
+ // Only the settings preview needs the full picker. Eligibility checks resolve
+ // selected roots afresh without loading unrelated workspace labels.
+ const labels =
+ rule.mode === "all" && !includeAllLabels
+ ? []
+ : await database
+ .select({
+ id: labelTable.id,
+ name: labelTable.name,
+ color: labelTable.color,
+ })
+ .from(labelTable)
+ .where(
+ and(
+ eq(labelTable.workspaceId, workspaceId),
+ isNull(labelTable.taskId),
+ isNull(labelTable.deletionStartedAt),
+ !includeAllLabels && rule.mode === "labels"
+ ? inArray(labelTable.id, rule.labels)
+ : undefined,
+ ),
+ )
+ .orderBy(asc(labelTable.id));
if (rule.mode === "all")
return { predicate: sql<boolean>`true`, labels, missing: [] as string[] };
const selected = labels.filter((label) => rule.labels.includes(label.id));
diff --git a/tests/api-integration/integration-sync-providers.test.ts b/tests/api-integration/integration-sync-providers.test.ts
index 8f8794eea..fe2e7d7fc 100644
--- a/tests/api-integration/integration-sync-providers.test.ts
+++ b/tests/api-integration/integration-sync-providers.test.ts
@@ -443,6 +443,66 @@ describe.each(["github", "gitea", "gitlab"] as const)(
expect(JSON.parse(link!.metadata!)).toMatchObject({ state: "closed" });
});
+ it("reopens and closes exported issues when moving out of and into a custom final column", async () => {
+ const f = await setup(type);
+ await f.assign();
+ const [final] = await db
+ .insert(schema.columnTable)
+ .values({
+ projectId: f.project.id,
+ name: "Shipped",
+ slug: "shipped",
+ position: 99,
+ isFinal: true,
+ })
+ .returning();
+ await db
+ .update(schema.taskTable)
+ .set({ status: final.slug, columnId: final.id })
+ .where(eq(schema.taskTable.id, f.task.id));
+ await reconcileProjectSync(f.project.id, f.integration.id);
+ expect(mocks.update.mock.calls[0]!.at(-1)).toMatchObject(
+ type === "gitlab" ? { state_event: "close" } : { state: "closed" },
+ );
+ mocks.update.mockClear();
+ const context = {
+ integrationId: f.integration.id,
+ projectId: f.project.id,
+ config: f.config,
+ };
+ const changeStatus = async (
+ oldStatus: string,
+ newStatus: string,
+ columnId: string,
+ ) => {
+ await db
+ .update(schema.taskTable)
+ .set({ status: newStatus, columnId })
+ .where(eq(schema.taskTable.id, f.task.id));
+ await plugin.onTaskStatusChanged!(
+ {
+ taskId: f.task.id,
+ projectId: f.project.id,
+ userId: null,
+ title: f.task.title,
+ oldStatus,
+ newStatus,
+ },
+ context,
+ );
+ };
+ await changeStatus(final.slug, f.columns.todo.slug, f.columns.todo.id);
+ expect(mocks.update).toHaveBeenCalledOnce();
+ expect(mocks.update.mock.calls[0]!.at(-1)).toMatchObject(
+ type === "gitlab" ? { state_event: "reopen" } : { state: "open" },
+ );
+ await changeStatus(f.columns.todo.slug, final.slug, final.id);
+ expect(mocks.update).toHaveBeenCalledTimes(2);
+ expect(mocks.update.mock.calls[1]!.at(-1)).toMatchObject(
+ type === "gitlab" ? { state_event: "close" } : { state: "closed" },
+ );
+ });
+
it.each([false, true])(
"replays edits made during creation and retries failed text initialization (failure=%s)",
async (failure) => {
diff --git a/tests/api-integration/integration-sync-rules.test.ts b/tests/api-integration/integration-sync-rules.test.ts
index efa8e5e6c..988b33f2e 100644
--- a/tests/api-integration/integration-sync-rules.test.ts
+++ b/tests/api-integration/integration-sync-rules.test.ts
@@ -10,11 +10,13 @@ import { getSyncIntegration } from "../../apps/api/src/integration-sync/controll
import { previewSyncRules } from "../../apps/api/src/integration-sync/controllers/preview-rules";
import { resumeSync } from "../../apps/api/src/integration-sync/controllers/resume-sync";
import { reviewSyncResume } from "../../apps/api/src/integration-sync/controllers/review-resume";
+import { lockResumeScope } from "../../apps/api/src/integration-sync/controllers/lock-resume-scope";
import { saveSyncRules } from "../../apps/api/src/integration-sync/controllers/save-rules";
import * as linkManager from "../../apps/api/src/plugins/github/services/link-manager";
import { createExternalLink } from "../../apps/api/src/plugins/github/services/link-manager";
import { withIntegrationLink } from "../../apps/api/src/plugins/github/services/with-integration-link";
import { withTaskSyncCreation } from "../../apps/api/src/plugins/sync/create-task-issue";
+import { outgoingPredicate } from "../../apps/api/src/plugins/sync/task-predicate";
import {
canSyncTask,
taskMatchesRule,
@@ -243,6 +245,36 @@ describe("integration label policies", () => {
).toBe(false);
});
+ it("limits eligibility scopes to selected roots while keeping the complete preview picker", async () => {
+ const f = await setup();
+ await f.assign();
+ await db.insert(schema.labelTable).values(
+ Array.from({ length: 200 }, (_, index) => ({
+ workspaceId: f.workspace.id,
+ name: `Unrelated label ${index}`,
+ color: "#123456",
+ })),
+ );
+ const scope = await outgoingPredicate(f.workspace.id, f.rules.outgoing);
+ expect(scope.labels.map((label) => label.id)).toEqual([f.label.id]);
+ expect((await f.preview()).labels).toHaveLength(201);
+ expect(
+ await taskMatchesRule(f.task.id, f.project.id, f.rules.outgoing),
+ ).toBe(true);
+ const unrestricted = await outgoingPredicate(f.workspace.id, {
+ mode: "all",
+ });
+ expect(unrestricted.labels).toEqual([]);
+ expect((await f.preview(defaultSyncRules)).labels).toHaveLength(201);
+ await db
+ .update(schema.labelTable)
+ .set({ deletionStartedAt: new Date() })
+ .where(eq(schema.labelTable.id, f.label.id));
+ expect(
+ await taskMatchesRule(f.task.id, f.project.id, f.rules.outgoing),
+ ).toBe(false);
+ });
+
it("rejects changed impact rather than applying a stale preview", async () => {
const f = await setup();
const preview = await f.preview();
@@ -479,6 +511,32 @@ describe("reviewed sync resume", () => {
const link = await f.link(true);
return { ...f, link };
}
+ it("returns not found when disconnect commits between the binding lookups", async () => {
+ const f = await paused();
+ await expect(
+ db.transaction(async (tx) => {
+ const load = tx.query.integrationTable.findFirst.bind(
+ tx.query.integrationTable,
+ );
+ vi.spyOn(tx.query.integrationTable, "findFirst").mockImplementationOnce(
+ async (config) => {
+ const integration = await load(config);
+ await db
+ .delete(schema.integrationTable)
+ .where(eq(schema.integrationTable.id, f.integration.id));
+ return integration;
+ },
+ );
+ await lockResumeScope(f.project.id, "gitea", f.link.id, tx);
+ }),
+ ).rejects.toMatchObject({ status: 404, message: "Linked task not found" });
+ expect(
+ await db.query.externalLinkTable.findFirst({
+ where: eq(schema.externalLinkTable.id, f.link.id),
+ }),
+ ).toBeUndefined();
+ expect(provider.write).not.toHaveBeenCalled();
+ });
it("returns a retryable conflict when another instance retains the resume lease", async () => {
const f = await paused();
await db.insert(schema.jobLeaseTable).values({
diff --git a/tests/api/plugins/gitlab/events/task-status-changed.test.ts b/tests/api/plugins/gitlab/events/task-status-changed.test.ts
index 018fb1e53..cd8e08f4d 100644
--- a/tests/api/plugins/gitlab/events/task-status-changed.test.ts
+++ b/tests/api/plugins/gitlab/events/task-status-changed.test.ts
@@ -130,6 +130,14 @@ describe("GitLab status webhook feedback", () => {
});
// Policy enforcement is covered by the PostgreSQL sync-rules integration tests.
+vi.mock(
+ "../../../../../apps/api/src/plugins/github/services/task-service",
+ () => ({
+ isTaskInFinalState: async (task: { status: string }) =>
+ task.status === "done",
+ }),
+);
+
vi.mock("../../../../../apps/api/src/plugins/sync/eligibility", () => ({
canSyncTask: async () => true,
}));