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: preserve sync scope through settings and export failures

Tin112915aec8f6
diff --git a/apps/api/src/gitea-integration/controllers/import-gitea-issues.ts b/apps/api/src/gitea-integration/controllers/import-gitea-issues.ts
index ae2fde150..2a012b3c0 100644
--- a/apps/api/src/gitea-integration/controllers/import-gitea-issues.ts
+++ b/apps/api/src/gitea-integration/controllers/import-gitea-issues.ts
@@ -1,4 +1,5 @@
import { acceptsIssue } from "../../plugins/sync/rules";
+import { sameConfig } from "../../plugins/sync/same-config";
import { and, eq, inArray, notInArray } from "drizzle-orm";
import { HTTPException } from "hono/http-exception";
import db from "../../database";
@@ -288,7 +289,7 @@ async function importSingleIssue(
});
if (
!binding ||
- binding.config !== JSON.stringify(config) ||
+ !sameConfig(binding.config, JSON.stringify(config)) ||
!acceptsIssue(binding.config, issue.labels) ||
(await findExternalLink(
integrationId,
diff --git a/apps/api/src/gitea-integration/index.ts b/apps/api/src/gitea-integration/index.ts
index a9bb42ac7..0f55f08f3 100644
--- a/apps/api/src/gitea-integration/index.ts
+++ b/apps/api/src/gitea-integration/index.ts
@@ -171,6 +171,7 @@ const updateIntegrationRoute = createRoute({
"No workspace access, or missing workspace:manage_settings",
),
404: jsonResponse("Integration not found", integrationNotFoundSchema),
+ 409: errorResponse("Integration changed; refresh before updating settings"),
},
});
@@ -306,7 +307,7 @@ const giteaIntegration = apiRouter<BaseVariables & { workspaceId: string }>()
});
}
- await db
+ const [saved] = await db
.update(integrationTable)
.set({
config: JSON.stringify(config),
@@ -316,10 +317,15 @@ const giteaIntegration = apiRouter<BaseVariables & { workspaceId: string }>()
})
.where(
and(
- eq(integrationTable.projectId, projectId),
- eq(integrationTable.type, "gitea"),
+ eq(integrationTable.id, row.id),
+ eq(integrationTable.config, row.config),
),
- );
+ )
+ .returning({ id: integrationTable.id });
+ if (!saved)
+ throw new HTTPException(409, {
+ message: "Integration changed; refresh before updating settings",
+ });
const updated = await getGiteaIntegration(projectId, true);
if (!updated) {
diff --git a/apps/api/src/gitlab-integration/controllers/import-gitlab-issues.ts b/apps/api/src/gitlab-integration/controllers/import-gitlab-issues.ts
index d346e4bfd..c53d9087c 100644
--- a/apps/api/src/gitlab-integration/controllers/import-gitlab-issues.ts
+++ b/apps/api/src/gitlab-integration/controllers/import-gitlab-issues.ts
@@ -1,4 +1,5 @@
import { acceptsIssue } from "../../plugins/sync/rules";
+import { sameConfig } from "../../plugins/sync/same-config";
import { and, eq, inArray } from "drizzle-orm";
import { HTTPException } from "hono/http-exception";
import db from "../../database";
@@ -263,7 +264,7 @@ async function importSingleIssue(
});
if (
!binding ||
- binding.config !== JSON.stringify(config) ||
+ !sameConfig(binding.config, JSON.stringify(config)) ||
!acceptsIssue(binding.config, issue.labels) ||
(await findExternalLink(integrationId, "issue", String(issue.iid), tx))
)
diff --git a/apps/api/src/gitlab-integration/index.ts b/apps/api/src/gitlab-integration/index.ts
index 1152716ac..950d2eabb 100644
--- a/apps/api/src/gitlab-integration/index.ts
+++ b/apps/api/src/gitlab-integration/index.ts
@@ -175,6 +175,7 @@ const updateIntegrationRoute = createRoute({
"No workspace access, or missing workspace:manage_settings",
),
404: jsonResponse("Integration not found", integrationNotFoundSchema),
+ 409: errorResponse("Integration changed; refresh before updating settings"),
},
});
@@ -313,7 +314,7 @@ const gitlabIntegration = apiRouter<BaseVariables & { workspaceId: string }>()
});
}
- await db
+ const [saved] = await db
.update(integrationTable)
.set({
config: JSON.stringify(config),
@@ -323,10 +324,15 @@ const gitlabIntegration = apiRouter<BaseVariables & { workspaceId: string }>()
})
.where(
and(
- eq(integrationTable.projectId, projectId),
- eq(integrationTable.type, "gitlab"),
+ eq(integrationTable.id, row.id),
+ eq(integrationTable.config, row.config),
),
- );
+ )
+ .returning({ id: integrationTable.id });
+ if (!saved)
+ throw new HTTPException(409, {
+ message: "Integration changed; refresh before updating settings",
+ });
const updated = await getGitlabIntegration(projectId, true);
if (!updated) {
diff --git a/apps/api/src/integration-sync/controllers/resume-sync.ts b/apps/api/src/integration-sync/controllers/resume-sync.ts
index d4795b309..917d013e9 100644
--- a/apps/api/src/integration-sync/controllers/resume-sync.ts
+++ b/apps/api/src/integration-sync/controllers/resume-sync.ts
@@ -67,28 +67,28 @@ async function resumeWithLease(
}
}
if (source === "provider") {
- const final = review.remote.state === "closed";
- const columns = await tx
- .select()
- .from(columnTable)
- .where(eq(columnTable.projectId, projectId))
- .orderBy(asc(columnTable.position));
- const current = columns.find((column) => column.id === task.columnId);
- const target =
- current?.isFinal === final
- ? current
- : columns.find((column) => column.isFinal === final);
- if (!target)
- throw new HTTPException(409, {
- message: "A matching open or completed column is required",
- });
+ let status = { status: task.status, columnId: task.columnId };
+ if (review.local.state !== review.remote.state) {
+ const columns = await tx
+ .select()
+ .from(columnTable)
+ .where(eq(columnTable.projectId, projectId))
+ .orderBy(asc(columnTable.position));
+ const target = columns.find(
+ (column) => column.isFinal === (review.remote.state === "closed"),
+ );
+ if (!target)
+ throw new HTTPException(409, {
+ message: "A matching open or completed column is required",
+ });
+ status = { status: target.slug, columnId: target.id };
+ }
const [after] = await tx
.update(taskTable)
.set({
title: review.remote.title,
description: review.remote.description,
- status: target.slug,
- columnId: target.id,
+ ...status,
})
.where(eq(taskTable.id, task.id))
.returning();
diff --git a/apps/api/src/plugins/sync/eligibility.ts b/apps/api/src/plugins/sync/eligibility.ts
index 22bdcff56..cebdccbb2 100644
--- a/apps/api/src/plugins/sync/eligibility.ts
+++ b/apps/api/src/plugins/sync/eligibility.ts
@@ -1,4 +1,5 @@
import { outgoingPredicate } from "./task-predicate";
+import { sameConfig } from "./same-config";
import { and, eq } from "drizzle-orm";
import db from "../../database";
import {
@@ -57,7 +58,8 @@ export async function canSyncTask(
});
if (
!integration?.isActive ||
- (expectedConfig !== undefined && integration.config !== expectedConfig)
+ (expectedConfig !== undefined &&
+ !sameConfig(integration.config, expectedConfig))
)
return false;
const rules = readSyncRules(integration.config);
diff --git a/apps/api/src/plugins/sync/reconcile.ts b/apps/api/src/plugins/sync/reconcile.ts
index 09d0099b7..e11e820ef 100644
--- a/apps/api/src/plugins/sync/reconcile.ts
+++ b/apps/api/src/plugins/sync/reconcile.ts
@@ -32,35 +32,46 @@ async function reconcileTaskWithIntegrations(
});
const before = await links();
for (const integration of integrations) {
- const config = integration.parsedConfig;
- if (
- !(await canSyncTask(
- taskId,
- integration.id,
- undefined,
- integration.config,
- ))
- )
- continue;
- const plugin = getPlugin(integration.type);
- if (!plugin?.onTaskCreated) continue;
- const task = await db.query.taskTable.findFirst({
- where: and(eq(taskTable.id, taskId), eq(taskTable.projectId, projectId)),
- });
- if (!task || task.number === null) continue;
- await plugin.onTaskCreated(
- {
- taskId: task.id,
+ try {
+ const config = integration.parsedConfig;
+ if (
+ !(await canSyncTask(
+ taskId,
+ integration.id,
+ undefined,
+ integration.config,
+ ))
+ )
+ continue;
+ const plugin = getPlugin(integration.type);
+ if (!plugin?.onTaskCreated) continue;
+ const task = await db.query.taskTable.findFirst({
+ where: and(
+ eq(taskTable.id, taskId),
+ eq(taskTable.projectId, projectId),
+ ),
+ });
+ if (!task || task.number === null) continue;
+ await plugin.onTaskCreated(
+ {
+ taskId: task.id,
+ projectId,
+ userId: task.userId ?? "",
+ title: task.title,
+ description: task.description,
+ priority: task.priority,
+ status: task.status,
+ number: task.number,
+ },
+ { integrationId: integration.id, projectId, config },
+ );
+ } catch {
+ console.error("Task sync reconciliation failed", {
projectId,
- userId: task.userId ?? "",
- title: task.title,
- description: task.description,
- priority: task.priority,
- status: task.status,
- number: task.number,
- },
- { integrationId: integration.id, projectId, config },
- );
+ taskId,
+ integrationId: integration.id,
+ });
+ }
}
if (JSON.stringify(before) !== JSON.stringify(await links()))
await publishEvent("task.updated", { projectId, taskId });
@@ -86,8 +97,17 @@ export async function reconcileProjectSync(
.orderBy(asc(taskTable.id))
.limit(50);
if (!tasks.length) return;
- for (const task of tasks)
- await reconcileTaskWithIntegrations(projectId, task.id, integrations);
+ for (const task of tasks) {
+ try {
+ await reconcileTaskWithIntegrations(projectId, task.id, integrations);
+ } catch {
+ console.error("Task sync reconciliation failed", {
+ projectId,
+ taskId: task.id,
+ integrationId,
+ });
+ }
+ }
cursor = tasks.at(-1)?.id;
}
}
diff --git a/apps/api/src/plugins/sync/same-config.ts b/apps/api/src/plugins/sync/same-config.ts
new file mode 100644
index 000000000..28d992232
--- /dev/null
+++ b/apps/api/src/plugins/sync/same-config.ts
@@ -0,0 +1,9 @@
+import { isDeepStrictEqual } from "node:util";
+
+export function sameConfig(stored: string, expected: string): boolean {
+ try {
+ return isDeepStrictEqual(JSON.parse(stored), JSON.parse(expected));
+ } catch {
+ return false;
+ }
+}
diff --git a/apps/docs/openapi.json b/apps/docs/openapi.json
index 4097ad7e0..7dd6f3d07 100644
--- a/apps/docs/openapi.json
+++ b/apps/docs/openapi.json
@@ -15573,6 +15573,16 @@
}
}
}
+ },
+ "409": {
+ "description": "Integration changed; refresh before updating settings",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
}
}
},
@@ -16128,6 +16138,16 @@
}
}
}
+ },
+ "409": {
+ "description": "Integration changed; refresh before updating settings",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
}
}
},
diff --git a/tests/api-integration/integration-sync-providers.test.ts b/tests/api-integration/integration-sync-providers.test.ts
index 3057a8a17..b76935727 100644
--- a/tests/api-integration/integration-sync-providers.test.ts
+++ b/tests/api-integration/integration-sync-providers.test.ts
@@ -23,6 +23,9 @@ import {
reconcileProjectSync,
reconcileTaskSync,
} from "../../apps/api/src/plugins/sync/reconcile";
+import { getSyncIntegration } from "../../apps/api/src/integration-sync/controllers/get-integration";
+import { previewSyncRules } from "../../apps/api/src/integration-sync/controllers/preview-rules";
+import type { SyncRules } from "../../apps/api/src/plugins/sync/rules";
import { canSyncTask } from "../../apps/api/src/plugins/sync/eligibility";
import { resetTestDatabase } from "./helpers/database";
import {
@@ -189,6 +192,44 @@ describe.each(["github", "gitea", "gitlab"] as const)(
gitea: mocks.giteaCreate,
gitlab: mocks.gitlabCreate,
}[type];
+ it("exports equivalent formatted configurations while rejecting real changes", async () => {
+ const f = await setup(type);
+ await f.assign();
+ await db
+ .update(schema.integrationTable)
+ .set({ config: JSON.stringify(f.config, null, 2) })
+ .where(eq(schema.integrationTable.id, f.integration.id));
+ const reordered = Object.fromEntries(Object.entries(f.config).reverse());
+ expect(
+ await canSyncTask(
+ f.task.id,
+ f.integration.id,
+ undefined,
+ JSON.stringify(reordered),
+ ),
+ ).toBe(true);
+ expect(
+ await canSyncTask(
+ f.task.id,
+ f.integration.id,
+ undefined,
+ JSON.stringify({ ...f.config, accessToken: "changed-test-token" }),
+ ),
+ ).toBe(false);
+ expect(
+ await canSyncTask(
+ f.task.id,
+ f.integration.id,
+ undefined,
+ JSON.stringify({
+ ...f.config,
+ syncRules: { ...f.config.syncRules, outgoing: { mode: "all" } },
+ }),
+ ),
+ ).toBe(false);
+ await reconcileProjectSync(f.project.id, f.integration.id);
+ expect(create).toHaveBeenCalledOnce();
+ });
it("exports newly eligible tasks once, including their custom labels", async () => {
const f = await setup(type);
await reconcileProjectSync(f.project.id, f.integration.id);
@@ -662,3 +703,58 @@ it("broadcasts only changed links and avoids task scans for unconfigured integra
).toBe(true);
expect(publish).not.toHaveBeenCalled();
});
+
+it("continues after a task export throws and leaves failed tasks available for explicit retry", async () => {
+ const f = await setup("gitea");
+ await f.assign();
+ const [other] = await db
+ .insert(schema.taskTable)
+ .values({
+ projectId: f.project.id,
+ title: "Other task",
+ number: 2,
+ status: f.columns.todo.slug,
+ columnId: f.columns.todo.id,
+ })
+ .returning();
+ await db.insert(schema.labelTable).values({
+ taskId: other!.id,
+ workspaceId: f.workspace.id,
+ name: "export",
+ color: "#123456",
+ });
+ const handler = vi
+ .spyOn(giteaPlugin, "onTaskCreated")
+ .mockRejectedValueOnce(new Error("Test creation lease failed"));
+ const log = vi.spyOn(console, "error").mockImplementation(() => {});
+ try {
+ await reconcileProjectSync(f.project.id, f.integration.id);
+ expect(mocks.giteaCreate).toHaveBeenCalledOnce();
+ expect(log).toHaveBeenCalledWith(
+ "Task sync reconciliation failed",
+ expect.objectContaining({ integrationId: f.integration.id }),
+ );
+ const integration = await getSyncIntegration(f.project.id, "gitea");
+ expect(
+ (await previewSyncRules(integration, f.config.syncRules as SyncRules))
+ .willCreate,
+ ).toBe(1);
+ const linked = await db.query.externalLinkTable.findMany();
+ expect(linked).toHaveLength(1);
+ mocks.giteaCreate.mockResolvedValueOnce({
+ number: 13,
+ html_url: "https://git.example/team/repo/issues/13",
+ title: "Retried task",
+ state: "open",
+ });
+ await reconcileProjectSync(f.project.id, f.integration.id);
+ expect(mocks.giteaCreate).toHaveBeenCalledTimes(2);
+ expect(
+ (await previewSyncRules(integration, f.config.syncRules as SyncRules))
+ .willCreate,
+ ).toBe(0);
+ } finally {
+ handler.mockRestore();
+ log.mockRestore();
+ }
+});
diff --git a/tests/api-integration/integration-sync-rules.test.ts b/tests/api-integration/integration-sync-rules.test.ts
index 840ef608e..e33a1b063 100644
--- a/tests/api-integration/integration-sync-rules.test.ts
+++ b/tests/api-integration/integration-sync-rules.test.ts
@@ -717,6 +717,47 @@ describe("reviewed sync resume", () => {
expect(await canSyncTask(f.task.id, f.integration.id)).toBe(true);
});
+ it.each(["planned", "archived"])(
+ "keeps an open %s task in its virtual status when adopting repository text",
+ async (status) => {
+ const f = await paused();
+ await db
+ .update(schema.taskTable)
+ .set({ status, columnId: null })
+ .where(eq(schema.taskTable.id, f.task.id));
+ provider.read.mockResolvedValue({
+ title: "Repository title",
+ description: "Repository body",
+ state: "open",
+ updatedAt: "2026-01-01T00:00:00Z",
+ });
+ const publish = vi
+ .spyOn(events, "publishEvent")
+ .mockResolvedValue(undefined);
+ const review = await reviewSyncResume(f.project.id, "gitea", f.link.id);
+ expect(review.local.state).toBe("open");
+ await resumeSync(
+ f.project.id,
+ "gitea",
+ f.link.id,
+ review.token,
+ "provider",
+ );
+ expect(
+ await db.query.taskTable.findFirst({
+ where: eq(schema.taskTable.id, f.task.id),
+ }),
+ ).toMatchObject({
+ status,
+ columnId: null,
+ title: "Repository title",
+ description: "Repository body",
+ });
+ expect(
+ publish.mock.calls.some(([name]) => name === "task.status_changed"),
+ ).toBe(false);
+ },
+ );
it("adopts repository values and completion state using the existing link", async () => {
const publish = vi
.spyOn(events, "publishEvent")
diff --git a/tests/api-integration/integration-sync-settings.test.ts b/tests/api-integration/integration-sync-settings.test.ts
new file mode 100644
index 000000000..3bc954765
--- /dev/null
+++ b/tests/api-integration/integration-sync-settings.test.ts
@@ -0,0 +1,103 @@
+import { eq } from "drizzle-orm";
+import { beforeEach, expect, it, vi } from "vite-plus/test";
+import db, { schema } from "../../apps/api/src/database";
+import * as events from "../../apps/api/src/events";
+import { createApp } from "../../apps/api/src/index";
+import { getSyncIntegration } from "../../apps/api/src/integration-sync/controllers/get-integration";
+import { previewSyncRules } from "../../apps/api/src/integration-sync/controllers/preview-rules";
+import { saveSyncRules } from "../../apps/api/src/integration-sync/controllers/save-rules";
+import * as giteaConfig from "../../apps/api/src/plugins/gitea/config";
+import * as gitlabConfig from "../../apps/api/src/plugins/gitlab/config";
+import {
+ defaultSyncRules,
+ type SyncRules,
+} from "../../apps/api/src/plugins/sync/rules";
+import { mockAuthenticatedSession } from "./helpers/auth";
+import { resetTestDatabase } from "./helpers/database";
+import {
+ createProjectFixture,
+ createWorkspaceMember,
+} from "./helpers/fixtures";
+
+beforeEach(async () => {
+ await resetTestDatabase();
+ vi.spyOn(events, "publishEvent").mockResolvedValue(undefined);
+});
+
+it.each(["gitea", "gitlab"] as const)(
+ "%s settings cannot overwrite rules saved during validation",
+ async (type) => {
+ const member = await createWorkspaceMember({ role: "owner" });
+ const { project } = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ });
+ const [integration] = await db
+ .insert(schema.integrationTable)
+ .values({
+ projectId: project.id,
+ type,
+ isActive: true,
+ config: JSON.stringify({
+ baseUrl: "https://git.example",
+ accessToken: "test-only",
+ repositoryOwner: "team",
+ repositoryName: "repo",
+ projectPath: "team/repo",
+ syncRules: defaultSyncRules,
+ }),
+ })
+ .returning();
+ mockAuthenticatedSession(member.user);
+ const { app } = createApp();
+ const property =
+ type === "gitea"
+ ? "commentTaskLinkOnGiteaIssue"
+ : "commentTaskLinkOnGitlabIssue";
+ const patch = () =>
+ app.request(`/api/${type}-integration/project/${project.id}`, {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ [property]: false }),
+ });
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const validation =
+ type === "gitea"
+ ? vi.spyOn(giteaConfig, "validateGiteaConfig")
+ : vi.spyOn(gitlabConfig, "validateGitlabConfig");
+ validation.mockImplementationOnce(async () => {
+ await gate;
+ return { valid: true };
+ });
+ const pending = patch();
+ const rules: SyncRules = {
+ ...defaultSyncRules,
+ incoming: { mode: "labels", match: "all", labels: ["ready"] },
+ };
+ try {
+ await vi.waitFor(() => expect(validation).toHaveBeenCalledOnce());
+ const preview = await previewSyncRules(
+ await getSyncIntegration(project.id, type),
+ rules,
+ );
+ await saveSyncRules(project.id, type, rules, preview.previewToken);
+ } finally {
+ release();
+ }
+ expect((await pending).status).toBe(409);
+ const readConfig = async () =>
+ JSON.parse(
+ (await db.query.integrationTable.findFirst({
+ where: eq(schema.integrationTable.id, integration!.id),
+ }))!.config,
+ );
+ expect((await readConfig()).syncRules).toEqual(rules);
+ expect((await patch()).status).toBe(200);
+ expect(await readConfig()).toMatchObject({
+ syncRules: rules,
+ [property]: false,
+ });
+ },
+);
diff --git a/tests/api-integration/integration-task-ownership.test.ts b/tests/api-integration/integration-task-ownership.test.ts
index 04d7a6a95..af2adabeb 100644
--- a/tests/api-integration/integration-task-ownership.test.ts
+++ b/tests/api-integration/integration-task-ownership.test.ts
@@ -163,6 +163,31 @@ async function expectPrivateTask(taskId: string) {
).toEqual([]);
}
describe("integration task ownership", () => {
+ it.each(["gitea", "gitlab"])(
+ "%s imports new issues from formatted configuration JSON",
+ async (type) => {
+ const f = await setup(type);
+ await db
+ .update(schema.projectTable)
+ .set({ lastTaskNumber: 1 })
+ .where(eq(schema.projectTable.id, f.project.id));
+ await db
+ .delete(schema.externalLinkTable)
+ .where(eq(schema.externalLinkTable.id, f.link.id));
+ await db
+ .update(schema.integrationTable)
+ .set({
+ config: JSON.stringify(JSON.parse(f.integration.config), null, 2),
+ })
+ .where(eq(schema.integrationTable.id, f.integration.id));
+ expect(
+ await (type === "gitea" ? importGiteaIssues : importGitlabIssues)(
+ f.project.id,
+ ),
+ ).toMatchObject({ imported: 1, skipped: 0 });
+ },
+ );
+
it.each(["gitea", "gitlab"])(
"%s import cannot modify a moved task through an old link",
async (type) => {