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(sync): verify resume values and reconcile pending comments

Tin514245539110
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 d9f799dc2..87b8fc0a7 100644
--- a/apps/api/src/gitea-integration/controllers/import-gitea-issues.ts
+++ b/apps/api/src/gitea-integration/controllers/import-gitea-issues.ts
@@ -265,6 +265,7 @@ async function importSingleIssue(
workspaceId,
database,
);
+ await canSyncTask(existingLink.taskId, integrationId, database);
await importCommentsForTask(comments, existingLink.taskId, database);
diff --git a/apps/api/src/integration-sync/controllers/resume-sync.ts b/apps/api/src/integration-sync/controllers/resume-sync.ts
index 7522cef51..f92d0fd48 100644
--- a/apps/api/src/integration-sync/controllers/resume-sync.ts
+++ b/apps/api/src/integration-sync/controllers/resume-sync.ts
@@ -135,10 +135,13 @@ async function resumeWithLease(
throw error;
}
let verificationError: unknown;
- // A label edit's only webhook may have been discarded while paused, in either
+ // An issue edit's only webhook may have been discarded while paused, in either
// resume direction. Read after unpausing so later webhooks can also run.
try {
- await verifyResumeProvider(snapshot, source);
+ await verifyResumeProvider(
+ snapshot,
+ source === "kaneo" ? initial.local : initial.remote,
+ );
} catch (error) {
verificationError = error;
console.error("Sync resume provider verification failed", {
diff --git a/apps/api/src/integration-sync/controllers/verify-resume-provider.ts b/apps/api/src/integration-sync/controllers/verify-resume-provider.ts
index aac942ad4..be8aed6d8 100644
--- a/apps/api/src/integration-sync/controllers/verify-resume-provider.ts
+++ b/apps/api/src/integration-sync/controllers/verify-resume-provider.ts
@@ -1,9 +1,10 @@
import { HTTPException } from "hono/http-exception";
import type { ResumeProviderSnapshot } from "./resume-provider-snapshot";
+import type { IssueValues } from "../../plugins/sync/provider-issue";
export async function verifyResumeProvider(
snapshot: ResumeProviderSnapshot,
- source: "kaneo" | "provider",
+ expected: IssueValues,
) {
let current: ResumeProviderSnapshot["remoteIssue"];
try {
@@ -16,10 +17,9 @@ export async function verifyResumeProvider(
const initialLabels = [...new Set(snapshot.remoteIssue.labels ?? [])].sort();
const currentLabels = [...new Set(current.labels ?? [])].sort();
if (
- (source === "provider" &&
- (current.title !== snapshot.remoteIssue.title ||
- current.description !== snapshot.remoteIssue.description ||
- current.state !== snapshot.remoteIssue.state)) ||
+ current.title !== expected.title ||
+ current.description !== expected.description ||
+ current.state !== expected.state ||
initialLabels.length !== currentLabels.length ||
initialLabels.some((label, index) => label !== currentLabels[index])
)
diff --git a/apps/api/src/plugins/github/events/task-created.ts b/apps/api/src/plugins/github/events/task-created.ts
index 995f859c7..61d09468b 100644
--- a/apps/api/src/plugins/github/events/task-created.ts
+++ b/apps/api/src/plugins/github/events/task-created.ts
@@ -16,6 +16,7 @@ import {
findExternalLinkByTaskAndType,
} from "../services/link-manager";
import { formatIssueBody, formatIssueTitle } from "../utils/format";
+import { taskLinkCommentExists } from "../services/task-link-comment-exists";
import {
getGithubApp,
getVerifiedInstallationOctokit,
@@ -165,6 +166,18 @@ async function createTaskIssue(
),
...(comment
? {
+ ...(existingLink
+ ? {
+ commentExists: () =>
+ taskLinkCommentExists(
+ octokit,
+ repositoryOwner,
+ repositoryName,
+ issueNumber,
+ comment!,
+ ),
+ }
+ : {}),
comment: () =>
octokit.rest.issues.createComment({
owner: repositoryOwner,
diff --git a/apps/api/src/plugins/github/services/task-link-comment-exists.ts b/apps/api/src/plugins/github/services/task-link-comment-exists.ts
new file mode 100644
index 000000000..86a595804
--- /dev/null
+++ b/apps/api/src/plugins/github/services/task-link-comment-exists.ts
@@ -0,0 +1,28 @@
+import type { Octokit } from "octokit";
+
+export async function taskLinkCommentExists(
+ octokit: Octokit,
+ owner: string,
+ repo: string,
+ issueNumber: number,
+ body: string,
+) {
+ // A failed create response can leave a delivered comment without its local
+ // completion marker. Read outside the write guard; any retry gets a fresh one.
+ for (let page = 1; ; page++) {
+ const { data } = await octokit.rest.issues
+ .listComments({
+ owner,
+ repo,
+ issue_number: issueNumber,
+ per_page: 100,
+ page,
+ request: { timeout: 10_000 },
+ })
+ .catch(() => {
+ throw new Error("Task-link comment could not be verified");
+ });
+ if (data.some((comment) => comment.body === body)) return true;
+ if (data.length < 100) return false;
+ }
+}
diff --git a/apps/api/src/plugins/gitlab/webhooks/issue-updated.ts b/apps/api/src/plugins/gitlab/webhooks/issue-updated.ts
index 5d23dc1a1..85ebe2b4d 100644
--- a/apps/api/src/plugins/gitlab/webhooks/issue-updated.ts
+++ b/apps/api/src/plugins/gitlab/webhooks/issue-updated.ts
@@ -126,7 +126,12 @@ async function syncGitlabLabelsToTask(
nonSystemLabels(previousLabels).map((label) => label.name),
);
const labelsToDelete = existingRows
- .filter((row) => previousNames.has(row.name) && !desiredNames.has(row.name))
+ .filter(
+ (row) =>
+ !isSystemLabelName(row.name) &&
+ previousNames.has(row.name) &&
+ !desiredNames.has(row.name),
+ )
.map((row) => row.id);
if (labelsToDelete.length > 0) {
diff --git a/apps/api/src/plugins/sync/initialize-task-issue.ts b/apps/api/src/plugins/sync/initialize-task-issue.ts
index dc5201497..e31f37505 100644
--- a/apps/api/src/plugins/sync/initialize-task-issue.ts
+++ b/apps/api/src/plugins/sync/initialize-task-issue.ts
@@ -33,6 +33,7 @@ export async function initializeTaskIssue(
state: (value: string) => Promise<string | undefined>;
labels: () => Promise<string | undefined>;
comment?: () => Promise<unknown>;
+ commentExists?: () => Promise<boolean>;
},
) {
const current = await initializeTaskText(event, context, link, actions.text);
@@ -53,7 +54,7 @@ export async function initializeTaskIssue(
});
}
if (!progress.syncInitializedComment && actions.comment) {
- await write(actions.comment);
+ if (!(await actions.commentExists?.())) await write(actions.comment);
await updateExternalLink(link.id, {
metadata: { syncInitializedComment: true },
});
diff --git a/apps/docs/core/integrations/index.mdx b/apps/docs/core/integrations/index.mdx
index 6a0d17ff2..1a3969989 100644
--- a/apps/docs/core/integrations/index.mdx
+++ b/apps/docs/core/integrations/index.mdx
@@ -34,7 +34,7 @@ Resuming leaves priority, detailed status, and custom labels unchanged. Later re
Kaneo rereads the issue when you resume and rejects a changed comparison. Local edits remain available while the repository responds; a task, rule, label, or link change during a resume write keeps synchronization paused for another review. When adopting a different open/closed state, resume uses the project's configured issue close or reopen workflow target. Gitea's content version, when available, also protects the body write from concurrent edits. Provider APIs do not offer an atomic version check for every issue field, so an edit made after the final read can still conflict with a resume write. Avoid editing the repository issue while resuming it. A rejected provider write leaves synchronization paused for another review.
-Kaneo checks repository labels again after either resume choice. A label change or failed verification pauses the link for another review, leaving priority and custom labels unchanged. When keeping repository values, this check also verifies the adopted title, description, and open/closed state. Adopted values remain visible in the next comparison if verification fails.
+Kaneo checks the repository again after either resume choice, verifying the selected title, description, and open/closed state along with the original labels. A mismatch or failed verification pauses the link for another review, leaving priority and custom labels unchanged. Adopted values remain visible in the next comparison if verification fails.
An issue creation request already sent to a repository may finish after its task stops matching. Kaneo keeps the returned issue link paused and stops further updates. Local edits remain available while the repository responds.
diff --git a/tests/api-integration/integration-sync-imported-link.test.ts b/tests/api-integration/integration-sync-imported-link.test.ts
index 1dc71b026..6444596a9 100644
--- a/tests/api-integration/integration-sync-imported-link.test.ts
+++ b/tests/api-integration/integration-sync-imported-link.test.ts
@@ -13,7 +13,7 @@ import {
createWorkspaceMember,
} from "./helpers/fixtures";
-const mocks = vi.hoisted(() => ({ issues: vi.fn() }));
+const mocks = vi.hoisted(() => ({ issues: vi.fn(), publish: vi.fn() }));
vi.mock("../../apps/api/src/plugins/gitea/utils/gitea-api", () => ({
createGiteaClient: () => ({
listIssues: mocks.issues,
@@ -28,7 +28,7 @@ vi.mock("../../apps/api/src/plugins/gitlab/utils/gitlab-api", () => ({
listIssueNotes: async () => [],
}),
}));
-vi.mock("../../apps/api/src/events", () => ({ publishEvent: async () => {} }));
+vi.mock("../../apps/api/src/events", () => ({ publishEvent: mocks.publish }));
vi.mock("../../apps/api/src/plugins/github/utils/github-app", () => ({
getGithubApp: () => ({
getInstallationOctokit: async () => ({
@@ -39,8 +39,116 @@ vi.mock("../../apps/api/src/plugins/github/utils/github-app", () => ({
beforeEach(async () => {
await resetTestDatabase();
mocks.issues.mockReset().mockResolvedValue([]);
+ mocks.publish.mockReset().mockResolvedValue(undefined);
});
+it.each(["gitea", "gitlab"] as const)(
+ "%s manual refresh commits its final label eligibility before publishing",
+ async (provider) => {
+ const { workspace } = await createWorkspaceMember();
+ const { project } = await createProjectFixture({
+ workspaceId: workspace.id,
+ });
+ const [root] = await db
+ .insert(schema.labelTable)
+ .values({
+ workspaceId: workspace.id,
+ name: "export",
+ color: "#123456",
+ })
+ .returning();
+ const [integration] = await db
+ .insert(schema.integrationTable)
+ .values({
+ projectId: project.id,
+ type: provider,
+ isActive: true,
+ config: JSON.stringify({
+ repositoryOwner: "team",
+ repositoryName: "repo",
+ baseUrl: "https://git.example",
+ projectPath: "team/repo",
+ accessToken: "fake-test-token",
+ syncRules: {
+ outgoing: { mode: "labels", match: "any", labels: [root.id] },
+ incoming: { mode: "all" },
+ },
+ }),
+ })
+ .returning();
+ const [task] = await db
+ .insert(schema.taskTable)
+ .values({
+ projectId: project.id,
+ title: "Existing task",
+ number: 1,
+ })
+ .returning();
+ await db.insert(schema.labelTable).values({
+ workspaceId: workspace.id,
+ taskId: task.id,
+ name: root.name,
+ color: root.color,
+ });
+ const [link] = await db
+ .insert(schema.externalLinkTable)
+ .values({
+ taskId: task.id,
+ integrationId: integration.id,
+ resourceType: "issue",
+ externalId: "9",
+ metadata: "{}",
+ url: "https://git.example/team/repo/issues/9",
+ })
+ .returning();
+ mocks.issues.mockResolvedValue([
+ provider === "gitea"
+ ? {
+ number: 9,
+ title: "Updated issue",
+ body: "Body",
+ state: "open",
+ html_url: link.url,
+ labels: [{ id: 2, name: "other", color: "123456" }],
+ }
+ : {
+ iid: 9,
+ title: "Updated issue",
+ description: "Body",
+ state: "opened",
+ web_url: link.url,
+ labels: ["other"],
+ },
+ ]);
+ const pausedAtPublish: boolean[] = [];
+ mocks.publish.mockImplementation(async () => {
+ const stored = await db.query.externalLinkTable.findFirst({
+ where: eq(schema.externalLinkTable.id, link.id),
+ });
+ pausedAtPublish.push(
+ JSON.parse(stored!.metadata!).syncFilterPaused === true,
+ );
+ });
+ expect(
+ await (provider === "gitea" ? importGiteaIssues : importGitlabIssues)(
+ project.id,
+ ),
+ ).toMatchObject({ updated: 1 });
+ expect(pausedAtPublish).toEqual(Array(3).fill(provider === "gitea"));
+ const labels = await db.query.labelTable.findMany({
+ where: eq(schema.labelTable.taskId, task.id),
+ });
+ expect(labels.map((label) => label.name).includes("export")).toBe(
+ provider === "gitlab",
+ );
+ expect(
+ await db.query.taskTable.findFirst({
+ where: eq(schema.taskTable.id, task.id),
+ }),
+ ).toMatchObject({ title: "Updated issue" });
+ },
+);
+
it.each(
(["github", "gitea", "gitlab"] as const).flatMap((provider) =>
[true, false].flatMap((qualifying) =>
diff --git a/tests/api-integration/integration-sync-providers.test.ts b/tests/api-integration/integration-sync-providers.test.ts
index 549373f7c..a2266ae29 100644
--- a/tests/api-integration/integration-sync-providers.test.ts
+++ b/tests/api-integration/integration-sync-providers.test.ts
@@ -50,6 +50,7 @@ const mocks = vi.hoisted(() => ({
update: vi.fn(),
labels: vi.fn(),
comment: vi.fn(),
+ comments: vi.fn(),
read: vi.fn(),
write: vi.fn(),
}));
@@ -68,6 +69,7 @@ vi.mock("../../apps/api/src/plugins/github/utils/github-app", () => ({
create: mocks.githubCreate,
update: mocks.update,
createComment: mocks.comment,
+ listComments: mocks.comments,
},
},
}),
@@ -115,6 +117,7 @@ beforeEach(async () => {
mocks.update.mockResolvedValue(undefined);
mocks.labels.mockResolvedValue(undefined);
mocks.comment.mockResolvedValue({ id: 123 });
+ mocks.comments.mockReset().mockResolvedValue({ data: [] });
mocks.read.mockResolvedValue({
title: "Repository title",
description: "Repository body",
@@ -122,7 +125,15 @@ beforeEach(async () => {
updatedAt: "2026-01-01T00:00:00Z",
labels: ["export", "priority:low", "status:to-do", "remote-old"],
});
- mocks.write.mockResolvedValue({ updatedAt: "2026-01-02T00:00:00Z" });
+ mocks.write.mockImplementation(async (values) => {
+ const current = await mocks.read.mock.results.at(-1)!.value;
+ mocks.read.mockResolvedValue({
+ ...current,
+ ...values,
+ updatedAt: "2026-01-02T00:00:00Z",
+ });
+ return { updatedAt: "2026-01-02T00:00:00Z" };
+ });
mocks.githubCreate.mockResolvedValue({
data: {
number: 12,
@@ -813,6 +824,164 @@ describe.each(["github", "gitea", "gitlab"] as const)(
},
);
+ if (type === "github")
+ it.each([
+ "first-page",
+ "later-page",
+ "read-failure",
+ "scope-loss",
+ ] as const)(
+ "reconciles an accepted comment with a lost response (%s) before retrying",
+ async (scenario) => {
+ const f = await setup(type);
+ await f.assign();
+ f.config.commentTaskLinkOnGitHubIssue = true;
+ await db
+ .update(schema.integrationTable)
+ .set({ config: JSON.stringify(f.config) })
+ .where(eq(schema.integrationTable.id, f.integration.id));
+ let deliveredBody = "";
+ mocks.comment.mockImplementationOnce(async ({ body }) => {
+ deliveredBody = body;
+ throw new Error("Comment accepted but its response was lost");
+ });
+ await reconcileTaskSync(f.project.id, f.task.id);
+ const link = (await db.query.externalLinkTable.findMany())[0]!;
+ expect(JSON.parse(link.metadata!)).toMatchObject({
+ syncInitializationPending: true,
+ });
+ mocks.comments.mockImplementation(async ({ page }) => {
+ const activity = await db.execute<{ count: number }>(sql`
+ select count(*)::int as count from pg_stat_activity
+ where datname = current_database() and state = 'idle in transaction'
+ `);
+ expect(activity.rows[0]!.count).toBe(0);
+ if (scenario === "scope-loss") {
+ await db
+ .delete(schema.labelTable)
+ .where(eq(schema.labelTable.taskId, f.task.id));
+ return { data: [] };
+ }
+ return {
+ data:
+ scenario === "later-page" && page === 1
+ ? Array.from({ length: 100 }, () => ({
+ body: "Other comment",
+ }))
+ : [{ body: deliveredBody }],
+ };
+ });
+ if (scenario === "read-failure") {
+ const log = vi.spyOn(console, "error").mockImplementation(() => {});
+ mocks.comments.mockRejectedValueOnce(
+ Object.assign(new Error("Read unavailable"), {
+ request: {
+ headers: { authorization: "private-provider-token" },
+ },
+ }),
+ );
+ try {
+ await reconcileTaskSync(f.project.id, f.task.id);
+ expect(JSON.stringify(log.mock.calls)).not.toContain(
+ "private-provider-token",
+ );
+ } finally {
+ log.mockRestore();
+ }
+ expect(mocks.comment).toHaveBeenCalledOnce();
+ const pending = await db.query.externalLinkTable.findFirst({
+ where: eq(schema.externalLinkTable.id, link.id),
+ });
+ expect(JSON.parse(pending!.metadata!)).toMatchObject({
+ syncInitializationPending: true,
+ });
+ }
+ await reconcileTaskSync(f.project.id, f.task.id);
+ expect(mocks.githubCreate).toHaveBeenCalledOnce();
+ expect(mocks.comment).toHaveBeenCalledOnce();
+ expect(mocks.comments).toHaveBeenCalled();
+ const completed = await db.query.externalLinkTable.findFirst({
+ where: eq(schema.externalLinkTable.id, link.id),
+ });
+ if (scenario === "scope-loss") {
+ expect(JSON.parse(completed!.metadata!)).toMatchObject({
+ syncInitializationPending: true,
+ syncFilterPaused: true,
+ });
+ return;
+ }
+ expect(JSON.parse(completed!.metadata!)).toMatchObject({
+ syncInitializationPending: false,
+ syncInitializedComment: true,
+ });
+ },
+ );
+
+ if (type === "gitlab")
+ it.each(["status:to-do", "priority:low"])(
+ "preserves the local %s scope label when the outbound baseline contains it",
+ async (name) => {
+ const f = await setup(type);
+ await f.assign();
+ const [root] = await db
+ .insert(schema.labelTable)
+ .values({
+ workspaceId: f.workspace.id,
+ name,
+ color: "#123456",
+ })
+ .returning();
+ await db.insert(schema.labelTable).values({
+ workspaceId: f.workspace.id,
+ taskId: f.task.id,
+ name,
+ color: root.color,
+ });
+ f.config.syncRules.outgoing.labels = [root.id];
+ await db
+ .update(schema.integrationTable)
+ .set({ config: JSON.stringify(f.config) })
+ .where(eq(schema.integrationTable.id, f.integration.id));
+ await reconcileTaskSync(f.project.id, f.task.id);
+ const link = (await db.query.externalLinkTable.findMany())[0]!;
+ await updateExternalLink(link.id, {
+ metadata: { syncResumeLabelBaseline: ["export", name] },
+ });
+ await handleGitlabIssueUpdated(
+ {
+ object_attributes: {
+ iid: 12,
+ title: f.task.title,
+ description: "",
+ state: "opened",
+ url: "https://gitlab.example/team/repo/-/issues/12",
+ },
+ changes: {
+ labels: {
+ previous: [{ title: "export" }, { title: name }],
+ current: [
+ { title: "export" },
+ { title: name },
+ { title: "new-remote" },
+ ],
+ },
+ },
+ project: {
+ name: "repo",
+ path_with_namespace: "team/repo",
+ web_url: "https://gitlab.example/team/repo",
+ },
+ },
+ f.integration.id,
+ );
+ const assigned = await db.query.labelTable.findMany({
+ where: eq(schema.labelTable.taskId, f.task.id),
+ });
+ expect(assigned.map((label) => label.name)).toContain(name);
+ expect(await canSyncTask(f.task.id, f.integration.id)).toBe(true);
+ },
+ );
+
it("does not dispatch a comment when its link is paused while the handler waits", async () => {
const f = await setup(type);
await f.assign();
diff --git a/tests/api-integration/integration-sync-rules.test.ts b/tests/api-integration/integration-sync-rules.test.ts
index bed621078..6818d8662 100644
--- a/tests/api-integration/integration-sync-rules.test.ts
+++ b/tests/api-integration/integration-sync-rules.test.ts
@@ -50,9 +50,15 @@ beforeEach(async () => {
state: "closed",
updatedAt: "2026-01-01T00:00:00Z",
});
- provider.write
- .mockReset()
- .mockResolvedValue({ updatedAt: "2026-01-02T00:00:00Z" });
+ provider.write.mockReset().mockImplementation(async (values) => {
+ const current = await provider.read.mock.results.at(-1)!.value;
+ provider.read.mockResolvedValue({
+ ...current,
+ ...values,
+ updatedAt: "2026-01-02T00:00:00Z",
+ });
+ return { updatedAt: "2026-01-02T00:00:00Z" };
+ });
});
async function setup(role = "owner") {
@@ -1221,6 +1227,73 @@ describe("reviewed sync resume", () => {
expect(followUp.remote.title).toBe("Edited after read");
});
+ it.each(
+ (["title", "description", "state"] as const).flatMap((field) =>
+ (["partial-write", "concurrent-edit"] as const).map((cause) => ({
+ field,
+ cause,
+ })),
+ ),
+ )(
+ "pauses Kaneo resume when $cause leaves $field different from the selected values",
+ async ({ field, cause }) => {
+ const f = await paused();
+ const review = await reviewSyncResume(
+ f.project.id,
+ "gitea",
+ f.link.id,
+ f.workspace.id,
+ );
+ let remote = review.snapshot.remoteIssue;
+ const webhook = vi.fn();
+ provider.read.mockImplementation(async () => {
+ const activity = await db.execute<{ count: number }>(sql`
+ select count(*)::int as count from pg_stat_activity
+ where datname = current_database() and state = 'idle in transaction'
+ `);
+ expect(activity.rows[0]!.count).toBe(0);
+ return remote;
+ });
+ provider.write.mockImplementationOnce(async (values) => {
+ remote = {
+ ...remote,
+ ...values,
+ [field]:
+ cause === "partial-write"
+ ? remote[field]
+ : field === "state"
+ ? "closed"
+ : "Concurrent repository edit",
+ updatedAt: "new-provider-version",
+ };
+ if (cause === "concurrent-edit")
+ await withIntegrationLink(f.link, f.integration, webhook);
+ return { updatedAt: remote.updatedAt };
+ });
+ await expect(
+ resumeSync(
+ f.project.id,
+ "gitea",
+ f.link.id,
+ review.token,
+ "kaneo",
+ f.workspace.id,
+ ),
+ ).rejects.toMatchObject({ status: 409 });
+ expect(provider.write).toHaveBeenCalledWith(review.local);
+ expect(webhook).not.toHaveBeenCalled();
+ expect(await canSyncTask(f.task.id, f.integration.id)).toBe(false);
+ const followUp = await reviewSyncResume(
+ f.project.id,
+ "gitea",
+ f.link.id,
+ f.workspace.id,
+ );
+ expect(followUp.local).toEqual(review.local);
+ expect(followUp.remote[field]).not.toBe(review.local[field]);
+ },
+ );
+
it("verifies adopted repository values outside locks without replaying labels", async () => {
const f = await paused();
provider.read.mockResolvedValue({