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): preserve resumed fields and isolate issue filters

Tin15bffc0e1654
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 2a012b3c0..bc2a21fd9 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 { canSyncTask } from "../../plugins/sync/eligibility";
import { sameConfig } from "../../plugins/sync/same-config";
import { and, eq, inArray, notInArray } from "drizzle-orm";
import { HTTPException } from "hono/http-exception";
@@ -239,7 +240,11 @@ async function importSingleIssue(
),
)
.for("update");
- if (!linked) return "skipped" as const;
+ if (
+ !linked ||
+ !(await canSyncTask(existingLink.taskId, integrationId, database))
+ )
+ return "skipped" as const;
const updateData: Record<string, unknown> = {
title: issue.title,
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 c53d9087c..890c5c20c 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 { canSyncTask } from "../../plugins/sync/eligibility";
import { sameConfig } from "../../plugins/sync/same-config";
import { and, eq, inArray } from "drizzle-orm";
import { HTTPException } from "hono/http-exception";
@@ -215,7 +216,11 @@ async function importSingleIssue(
),
)
.for("update");
- if (!linked) return "skipped" as const;
+ if (
+ !linked ||
+ !(await canSyncTask(existingLink.taskId, integrationId, database))
+ )
+ return "skipped" as const;
const updateData: Record<string, unknown> = {
title: issue.title,
diff --git a/apps/api/src/integration-sync/controllers/resume-sync.ts b/apps/api/src/integration-sync/controllers/resume-sync.ts
index 917d013e9..f09ad305e 100644
--- a/apps/api/src/integration-sync/controllers/resume-sync.ts
+++ b/apps/api/src/integration-sync/controllers/resume-sync.ts
@@ -124,6 +124,7 @@ async function resumeWithLease(
metadata: {
syncFilterPaused: false,
syncResumeUncertain: false,
+ syncResumeLabelBaseline: review.remoteIssueLabels,
...(provider === "gitlab"
? {
lastOutboundStateSyncAt: Date.now(),
diff --git a/apps/api/src/integration-sync/controllers/review-resume.ts b/apps/api/src/integration-sync/controllers/review-resume.ts
index 3b4b0b8ba..b3fe301e5 100644
--- a/apps/api/src/integration-sync/controllers/review-resume.ts
+++ b/apps/api/src/integration-sync/controllers/review-resume.ts
@@ -81,6 +81,7 @@ export async function reviewSyncResume(
access,
local,
remote,
+ remoteIssueLabels: remoteIssue.labels,
remoteIssueUpdatedAt: remoteIssue.updatedAt,
token,
};
diff --git a/apps/api/src/plugins/gitea/webhooks/issue-labeled.ts b/apps/api/src/plugins/gitea/webhooks/issue-labeled.ts
index 344097dee..4f3e3f469 100644
--- a/apps/api/src/plugins/gitea/webhooks/issue-labeled.ts
+++ b/apps/api/src/plugins/gitea/webhooks/issue-labeled.ts
@@ -1,3 +1,4 @@
+import { resumeLabelChanges } from "../../sync/resume-label-changes";
import { acceptsIssue, readSyncRules } from "../../sync/rules";
import { handleGiteaIssueOpened } from "./issue-opened";
import { withIntegrationLink } from "../../github/services/with-integration-link";
@@ -8,7 +9,10 @@ import {
import { eq, inArray } from "drizzle-orm";
import { labelTable, taskTable } from "../../../database/schema";
import { publishEvent } from "../../../events";
-import { findExternalLink } from "../../github/services/link-manager";
+import {
+ findExternalLink,
+ updateExternalLink,
+} from "../../github/services/link-manager";
import { updateTaskStatus } from "../../github/services/task-service";
import {
extractIssuePriority,
@@ -63,14 +67,20 @@ async function syncGiteaLabelsToTask(
workspaceId: string,
giteaLabels: Array<{ name: string; color?: string }>,
db: IntegrationDatabase,
+ previousNames?: string[],
) {
const desiredNames = new Set(giteaLabels.map((l) => l.name));
+ const previous = previousNames ? new Set(previousNames) : undefined;
const existingRows = await db.query.labelTable.findMany({
where: eq(labelTable.taskId, taskId),
});
const labelsToInsert = giteaLabels
- .filter((g) => !existingRows.some((row) => row.name === g.name))
+ .filter(
+ (g) =>
+ (!previous || !previous.has(g.name)) &&
+ !existingRows.some((row) => row.name === g.name),
+ )
.map((g) => ({
name: g.name,
color: normalizedGiteaLabelColor(g),
@@ -110,7 +120,10 @@ async function syncGiteaLabelsToTask(
const labelsToDelete = existingRows
.filter(
- (row) => !desiredNames.has(row.name) && !isSystemLabelName(row.name),
+ (row) =>
+ (!previous || previous.has(row.name)) &&
+ !desiredNames.has(row.name) &&
+ !isSystemLabelName(row.name),
)
.map((row) => row.id);
@@ -166,10 +179,21 @@ export async function handleGiteaIssueLabeled(
existingLink,
integration,
async (db, afterCommit, existingLink) => {
+ const names = (issue.labels ?? []).flatMap((label) => {
+ const name = typeof label === "string" ? label : label.name;
+ return name ? [name] : [];
+ });
+ const changes = resumeLabelChanges(existingLink, names);
+ if (changes.baseline && issue.labels !== undefined)
+ await updateExternalLink(
+ existingLink.id,
+ { metadata: { syncResumeLabelBaseline: names } },
+ db,
+ );
const priority = extractIssuePriority(issue.labels);
const status = extractIssueStatus(issue.labels);
- if (priority) {
+ if (priority && changes.priorityChanged) {
await db
.update(taskTable)
.set({ priority })
@@ -178,7 +202,7 @@ export async function handleGiteaIssueLabeled(
);
}
- if (status) {
+ if (status && changes.statusChanged) {
const statusResult = await updateTaskStatus(
existingLink.taskId,
status,
@@ -223,6 +247,7 @@ export async function handleGiteaIssueLabeled(
task.project.workspaceId,
giteaLabelsForSync(issue.labels),
db,
+ changes.baseline,
);
afterCommit(() =>
publishEvent("task.labels_updated", {
diff --git a/apps/api/src/plugins/github/services/integration-task-scope.ts b/apps/api/src/plugins/github/services/integration-task-scope.ts
index f70a386fa..5304e0d4e 100644
--- a/apps/api/src/plugins/github/services/integration-task-scope.ts
+++ b/apps/api/src/plugins/github/services/integration-task-scope.ts
@@ -1,4 +1,3 @@
-import { canSyncTask } from "../../sync/eligibility";
import { and, eq, sql } from "drizzle-orm";
import db from "../../../database";
import {
@@ -103,15 +102,6 @@ export async function withIntegrationTask<T>(
)
.for("no key update");
if (!task) return undefined;
- if (
- !(await canSyncTask(
- taskId,
- integration.id,
- tx,
- expectedBinding?.config,
- ))
- )
- return undefined;
}
return apply(tx, (effect) => effects.push(effect));
});
diff --git a/apps/api/src/plugins/github/services/with-integration-link.ts b/apps/api/src/plugins/github/services/with-integration-link.ts
index a718653f6..fc4f9307a 100644
--- a/apps/api/src/plugins/github/services/with-integration-link.ts
+++ b/apps/api/src/plugins/github/services/with-integration-link.ts
@@ -35,6 +35,7 @@ export function withIntegrationLink<T>(
.for("update");
if (!lockedLink) return;
if (
+ lockedLink.resourceType === "issue" &&
!(await canSyncTask(
link.taskId,
integration.id,
diff --git a/apps/api/src/plugins/github/webhooks/issue-labeled.ts b/apps/api/src/plugins/github/webhooks/issue-labeled.ts
index 34085dfd5..13af1ba2a 100644
--- a/apps/api/src/plugins/github/webhooks/issue-labeled.ts
+++ b/apps/api/src/plugins/github/webhooks/issue-labeled.ts
@@ -1,3 +1,4 @@
+import { resumeLabelChanges } from "../../sync/resume-label-changes";
import { acceptsIssue, readSyncRules } from "../../sync/rules";
import { handleIssueOpened } from "./issue-opened";
import { withIntegrationLink } from "../services/with-integration-link";
@@ -5,7 +6,7 @@ import { linkedTaskScope } from "../services/integration-task-scope";
import { eq } from "drizzle-orm";
import { labelTable, taskTable } from "../../../database/schema";
import { publishEvent } from "../../../events";
-import { findExternalLink } from "../services/link-manager";
+import { findExternalLink, updateExternalLink } from "../services/link-manager";
import {
findAllIntegrationsByRepo,
updateTaskStatus,
@@ -67,17 +68,28 @@ export async function handleIssueLabeled(payload: IssueLabeledPayload) {
existingLink,
integration,
async (db, afterCommit, existingLink) => {
+ const names = (issue.labels ?? []).flatMap((label) => {
+ const name = typeof label === "string" ? label : label.name;
+ return name ? [name] : [];
+ });
+ const changes = resumeLabelChanges(existingLink, names);
+ if (changes.baseline && issue.labels !== undefined)
+ await updateExternalLink(
+ existingLink.id,
+ { metadata: { syncResumeLabelBaseline: names } },
+ db,
+ );
const priority = extractIssuePriority(issue.labels);
const status = extractIssueStatus(issue.labels);
- if (priority) {
+ if (priority && changes.priorityChanged) {
await db
.update(taskTable)
.set({ priority })
.where(linkedTaskScope(existingLink.taskId, integration.projectId));
}
- if (status) {
+ if (status && changes.statusChanged) {
const statusResult = await updateTaskStatus(
existingLink.taskId,
status,
diff --git a/apps/api/src/plugins/gitlab/webhooks/issue-updated.ts b/apps/api/src/plugins/gitlab/webhooks/issue-updated.ts
index 88c0bf9f7..b95b95c6a 100644
--- a/apps/api/src/plugins/gitlab/webhooks/issue-updated.ts
+++ b/apps/api/src/plugins/gitlab/webhooks/issue-updated.ts
@@ -1,3 +1,4 @@
+import { resumeLabelChanges } from "../../sync/resume-label-changes";
import { acceptsIssue, readSyncRules } from "../../sync/rules";
import { handleGitlabIssueOpened } from "./issue-opened";
import { withIntegrationLink } from "../../github/services/with-integration-link";
@@ -71,6 +72,7 @@ async function syncGitlabLabelsToTask(
gitlabLabels: Array<{ name: string; color: string }>,
previousLabels: GitlabWebhookLabel[] | undefined,
db: IntegrationDatabase,
+ resumeBaseline?: string[],
) {
const desiredNames = new Set(gitlabLabels.map((l) => l.name));
const existingRows = await db.query.labelTable.findMany({
@@ -78,7 +80,11 @@ async function syncGitlabLabelsToTask(
});
const labelsToInsert = gitlabLabels
- .filter((g) => !existingRows.some((row) => row.name === g.name))
+ .filter(
+ (g) =>
+ (!resumeBaseline || !resumeBaseline.includes(g.name)) &&
+ !existingRows.some((row) => row.name === g.name),
+ )
.map((g) => ({
name: g.name,
color: g.color,
@@ -116,7 +122,8 @@ async function syncGitlabLabelsToTask(
// Absence from GitLab alone does not imply removal: local labels may not
// have synced yet. Only delete names explicitly removed by this event.
const previousNames = new Set(
- nonSystemLabels(previousLabels).map((label) => label.name),
+ resumeBaseline ??
+ nonSystemLabels(previousLabels).map((label) => label.name),
);
const labelsToDelete = existingRows
.filter((row) => previousNames.has(row.name) && !desiredNames.has(row.name))
@@ -258,10 +265,18 @@ export async function handleGitlabIssueUpdated(
}
const titles = labelTitles(currentLabels);
+ const labelChanges = resumeLabelChanges(externalLink, titles);
+ if (labelChanges.baseline)
+ await updateExternalLink(
+ externalLink.id,
+ { metadata: { syncResumeLabelBaseline: titles } },
+ db,
+ );
+
const priority = extractIssuePriority(titles);
const status = extractIssueStatus(titles);
- if (priority) {
+ if (priority && labelChanges.priorityChanged) {
await db
.update(taskTable)
.set({ priority })
@@ -273,7 +288,11 @@ export async function handleGitlabIssueUpdated(
const previousStatus = extractIssueStatus(
labelTitles(changes?.labels?.previous),
);
- if (status && status !== previousStatus) {
+ if (
+ status &&
+ labelChanges.statusChanged &&
+ status !== previousStatus
+ ) {
const statusResult = await updateTaskStatus(task.id, status, db);
if (
statusResult.applied &&
@@ -302,6 +321,7 @@ export async function handleGitlabIssueUpdated(
nonSystemLabels(currentLabels),
changes?.labels?.previous,
db,
+ labelChanges.baseline,
);
afterCommit(() =>
publishEvent("task.labels_updated", {
diff --git a/apps/api/src/plugins/sync/provider-issue.ts b/apps/api/src/plugins/sync/provider-issue.ts
index 0e192fb57..11a1856e2 100644
--- a/apps/api/src/plugins/sync/provider-issue.ts
+++ b/apps/api/src/plugins/sync/provider-issue.ts
@@ -32,6 +32,7 @@ export async function providerIssue(
state: string;
updated_at?: string;
content_version?: number;
+ labels?: Array<string | { name?: string }>;
}) => ({
title: issue.title,
description: formatTaskDescriptionFromIssue(
@@ -41,6 +42,10 @@ export async function providerIssue(
state: issue.state === "closed" ? ("closed" as const) : ("open" as const),
updatedAt: issue.updated_at ?? null,
contentVersion: issue.content_version ?? null,
+ labels: (issue.labels ?? []).flatMap((label) => {
+ const name = typeof label === "string" ? label : label.name;
+ return name ? [name] : [];
+ }),
});
if (integration.type === "gitea") {
const client = createGiteaClient(config as GiteaConfig);
diff --git a/apps/api/src/plugins/sync/resume-label-changes.ts b/apps/api/src/plugins/sync/resume-label-changes.ts
new file mode 100644
index 000000000..c2593d917
--- /dev/null
+++ b/apps/api/src/plugins/sync/resume-label-changes.ts
@@ -0,0 +1,30 @@
+import {
+ extractIssuePriority,
+ extractIssueStatus,
+} from "../github/utils/extract-priority";
+import { parseLinkMetadata } from "../github/utils/parse-link-metadata";
+
+export function resumeLabelChanges(
+ link: { id: string; metadata: string | null },
+ current: string[],
+) {
+ const value = parseLinkMetadata<{ syncResumeLabelBaseline?: unknown }>(
+ link.metadata,
+ {
+ externalLinkId: link.id,
+ source: "resume_labels",
+ },
+ ).syncResumeLabelBaseline;
+ const baseline =
+ Array.isArray(value) && value.every((name) => typeof name === "string")
+ ? (value as string[])
+ : undefined;
+ return {
+ baseline,
+ priorityChanged:
+ !baseline ||
+ extractIssuePriority(baseline) !== extractIssuePriority(current),
+ statusChanged:
+ !baseline || extractIssueStatus(baseline) !== extractIssueStatus(current),
+ };
+}
diff --git a/apps/docs/core/integrations/index.mdx b/apps/docs/core/integrations/index.mdx
index d979ae824..35efffb36 100644
--- a/apps/docs/core/integrations/index.mdx
+++ b/apps/docs/core/integrations/index.mdx
@@ -30,6 +30,8 @@ Enable **Advanced settings** in **Account → Preferences** or **Workspace → G
When a linked task loses its qualifying labels, synchronization pauses in both directions. Both records and their link remain. Reapplying the label does not overwrite either side: choose **Review and resume**, compare the current title, description, and open/closed state, then keep the Kaneo or repository values. Historical comments are not replayed. Missing or deleted workspace labels keep the filter closed until you repair the rule.
+Resuming leaves priority, detailed status, and custom labels unchanged. Later repository label events apply changes made after the comparison, so an unrelated label event does not restore stale values from the pause. Issue filters do not prevent branch or pull request linking and their configured status transitions.
+
Kaneo rereads the issue when you resume and rejects a changed comparison. 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.
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/github-import-bounds.test.ts b/tests/api-integration/github-import-bounds.test.ts
index c05e9941d..a56003bd4 100644
--- a/tests/api-integration/github-import-bounds.test.ts
+++ b/tests/api-integration/github-import-bounds.test.ts
@@ -158,6 +158,40 @@ async function saved() {
}
describe("bounded resumable GitHub import", () => {
+ it("rejects an incoming rule change while fetching a page before creating tasks or consuming its cursor", async () => {
+ const { integration, config, request } = await setup();
+ const started = deferred();
+ const release = deferred();
+ mocks.graphql.mockImplementationOnce(async () => {
+ started.resolve();
+ await release.promise;
+ return issuePage([issue(1)], true, "first", 2);
+ });
+ const importing = request();
+ await started.promise;
+ await db
+ .update(schema.integrationTable)
+ .set({
+ config: JSON.stringify({
+ ...config,
+ syncRules: {
+ outgoing: { mode: "all" },
+ incoming: { mode: "labels", labels: ["approved"], match: "any" },
+ },
+ }),
+ })
+ .where(eq(schema.integrationTable.id, integration.id));
+ release.resolve();
+ expect((await importing).status).toBe(409);
+ expect(await db.query.taskTable.findMany()).toHaveLength(0);
+ expect(await db.query.externalLinkTable.findMany()).toHaveLength(0);
+ expect((await saved())?.state).toMatchObject({
+ phase: "issues",
+ issueCursor: null,
+ imported: 0,
+ });
+ });
+
it("bounds each HTTP step, persists resumable state, imports every issue and retries completion without restarting", async () => {
const { request, app, project } = await setup();
serveIssues(9);
diff --git a/tests/api-integration/integration-pr-task-ownership.test.ts b/tests/api-integration/integration-pr-task-ownership.test.ts
index bf6b5bab5..c31946119 100644
--- a/tests/api-integration/integration-pr-task-ownership.test.ts
+++ b/tests/api-integration/integration-pr-task-ownership.test.ts
@@ -1,4 +1,4 @@
-import { eq } from "drizzle-orm";
+import { and, eq } from "drizzle-orm";
import { beforeEach, expect, it, vi } from "vite-plus/test";
import { publishEvent } from "../../apps/api/src/events";
import db, { getDatabase, schema } from "../../apps/api/src/database";
@@ -29,6 +29,7 @@ const cases = ["github", "gitea", "gitlab"].flatMap((provider) =>
action,
race,
sameStatus: false,
+ syncScope: "all",
})),
),
);
@@ -39,12 +40,26 @@ cases.push(
action,
race: "ordinary",
sameStatus: action !== "closed",
+ syncScope: "all",
})),
),
);
+cases.push(
+ ...["github", "gitea", "gitlab"].flatMap((provider) =>
+ ["opened", "merged", "closed"].flatMap((action) =>
+ ["excluded", "paused"].map((syncScope) => ({
+ provider,
+ action,
+ race: "ordinary",
+ sameStatus: false,
+ syncScope,
+ })),
+ ),
+ ),
+);
it.each(cases)(
- "$provider $action webhook respects task ownership ($race)",
- async ({ provider, action, race, sameStatus }) => {
+ "$provider $action webhook respects task ownership ($race, $syncScope issue sync)",
+ async ({ provider, action, race, sameStatus, syncScope }) => {
const { user, workspace } = await createWorkspaceMember();
const { project } = await createProjectFixture({
workspaceId: workspace.id,
@@ -87,10 +102,31 @@ it.each(cases)(
verifiedGithubAccountId: "123",
verifiedByUserId: user.id,
branchPattern: "{slug}-{number}",
+ ...(syncScope === "excluded"
+ ? {
+ syncRules: {
+ outgoing: {
+ mode: "labels",
+ match: "any",
+ labels: ["missing"],
+ },
+ incoming: { mode: "all" },
+ },
+ }
+ : {}),
statusTransitions: { onPROpen: "in-progress", onPRMerge: "done" },
}),
})
.returning();
+ if (syncScope === "paused")
+ await db.insert(schema.externalLinkTable).values({
+ taskId: task.id,
+ integrationId: integration.id,
+ resourceType: "issue",
+ externalId: "2",
+ url: "https://git.example/owner/repo/issues/2",
+ metadata: JSON.stringify({ syncFilterPaused: true }),
+ });
if (action !== "opened")
await db.insert(schema.externalLinkTable).values({
taskId: task.id,
@@ -155,7 +191,10 @@ it.each(cases)(
vi.mocked(publishEvent).mockImplementation(async (type) => {
if (type !== "task.updated") return;
const committed = await db.query.externalLinkTable.findFirst({
- where: eq(schema.externalLinkTable.taskId, task.id),
+ where: and(
+ eq(schema.externalLinkTable.taskId, task.id),
+ eq(schema.externalLinkTable.resourceType, "pull_request"),
+ ),
});
expect(committed).toBeDefined();
expect(JSON.parse(committed!.metadata!).state).toBe(
@@ -223,7 +262,10 @@ it.each(cases)(
race === "moved" ? destination.id : project.id,
);
const links = await db.query.externalLinkTable.findMany({
- where: eq(schema.externalLinkTable.taskId, task.id),
+ where: and(
+ eq(schema.externalLinkTable.taskId, task.id),
+ eq(schema.externalLinkTable.resourceType, "pull_request"),
+ ),
});
expect(links).toHaveLength(race === "ordinary" ? 1 : 0);
expect(
diff --git a/tests/api-integration/integration-push-task-ownership.test.ts b/tests/api-integration/integration-push-task-ownership.test.ts
index 3a5bd2eb6..36b3cc18c 100644
--- a/tests/api-integration/integration-push-task-ownership.test.ts
+++ b/tests/api-integration/integration-push-task-ownership.test.ts
@@ -1,4 +1,4 @@
-import { eq } from "drizzle-orm";
+import { and, eq } from "drizzle-orm";
import { beforeEach, expect, it, vi } from "vite-plus/test";
import db, { getDatabase, schema } from "../../apps/api/src/database";
import { publishEvent } from "../../apps/api/src/events";
@@ -20,7 +20,10 @@ beforeEach(async () => {
});
it.each(
["github", "gitea", "gitlab"].flatMap((provider) =>
- ["new", "existing", "moved"].map((race) => ({ provider, race })),
+ ["new", "existing", "moved", "excluded", "paused"].map((race) => ({
+ provider,
+ race,
+ })),
),
)(
"$provider branch push preserves ownership and final tasks ($race)",
@@ -58,10 +61,31 @@ it.each(
verifiedGithubAccountId: "123",
verifiedByUserId: user.id,
branchPattern: "{slug}-{number}",
+ ...(race === "excluded"
+ ? {
+ syncRules: {
+ outgoing: {
+ mode: "labels",
+ match: "any",
+ labels: ["missing"],
+ },
+ incoming: { mode: "all" },
+ },
+ }
+ : {}),
statusTransitions: { onBranchPush: "in-progress" },
}),
})
.returning();
+ if (race === "paused")
+ await db.insert(schema.externalLinkTable).values({
+ taskId: task.id,
+ integrationId: integration.id,
+ resourceType: "issue",
+ externalId: "2",
+ url: "https://git.example/owner/repo/issues/2",
+ metadata: JSON.stringify({ syncFilterPaused: true }),
+ });
if (race === "existing")
await db.insert(schema.externalLinkTable).values({
taskId: task.id,
@@ -98,7 +122,10 @@ it.each(
vi.mocked(publishEvent).mockImplementation(async (type) => {
if (type !== "task.updated") return;
const committed = await db.query.externalLinkTable.findFirst({
- where: eq(schema.externalLinkTable.taskId, task.id),
+ where: and(
+ eq(schema.externalLinkTable.taskId, task.id),
+ eq(schema.externalLinkTable.resourceType, "branch"),
+ ),
});
expect(committed?.resourceType).toBe("branch");
});
@@ -125,9 +152,14 @@ it.each(
expect(saved?.projectId).toBe(
race === "moved" ? destination.id : project.id,
);
- expect(saved?.status).toBe(race === "new" ? "in-progress" : "done");
+ expect(saved?.status).toBe(
+ ["new", "excluded", "paused"].includes(race) ? "in-progress" : "done",
+ );
const links = await db.query.externalLinkTable.findMany({
- where: eq(schema.externalLinkTable.taskId, task.id),
+ where: and(
+ eq(schema.externalLinkTable.taskId, task.id),
+ eq(schema.externalLinkTable.resourceType, "branch"),
+ ),
});
expect(links).toHaveLength(race === "moved" ? 0 : 1);
expect(
diff --git a/tests/api-integration/integration-sync-providers.test.ts b/tests/api-integration/integration-sync-providers.test.ts
index 6b95b107e..15b618ad7 100644
--- a/tests/api-integration/integration-sync-providers.test.ts
+++ b/tests/api-integration/integration-sync-providers.test.ts
@@ -27,6 +27,9 @@ import { getSyncIntegration } from "../../apps/api/src/integration-sync/controll
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 { resumeSync } from "../../apps/api/src/integration-sync/controllers/resume-sync";
+import { reviewSyncResume } from "../../apps/api/src/integration-sync/controllers/review-resume";
+import { updateExternalLink } from "../../apps/api/src/plugins/github/services/link-manager";
import deleteLabel from "../../apps/api/src/label/controllers/delete-label";
import { resetTestDatabase } from "./helpers/database";
import {
@@ -41,6 +44,11 @@ const mocks = vi.hoisted(() => ({
update: vi.fn(),
labels: vi.fn(),
comment: vi.fn(),
+ read: vi.fn(),
+ write: vi.fn(),
+}));
+vi.mock("../../apps/api/src/plugins/sync/provider-issue", () => ({
+ providerIssue: async () => ({ read: mocks.read, write: mocks.write }),
}));
vi.mock("../../apps/api/src/plugins/github/utils/github-app", () => ({
getGithubApp: () => ({
@@ -93,6 +101,14 @@ beforeEach(async () => {
mocks.update.mockResolvedValue(undefined);
mocks.labels.mockResolvedValue(undefined);
mocks.comment.mockResolvedValue({ id: 123 });
+ mocks.read.mockResolvedValue({
+ title: "Repository title",
+ description: "Repository body",
+ state: "open",
+ 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.githubCreate.mockResolvedValue({
data: {
number: 12,
@@ -520,6 +536,134 @@ describe.each(["github", "gitea", "gitlab"] as const)(
}
});
+ it.each(["kaneo", "provider"] as const)(
+ "preserves unreviewed fields after resuming with %s and accepts later label changes",
+ async (source) => {
+ const f = await setup(type);
+ await f.assign();
+ await reconcileTaskSync(f.project.id, f.task.id);
+ const link = (await db.query.externalLinkTable.findMany())[0]!;
+ await updateExternalLink(link.id, {
+ metadata: { syncFilterPaused: true },
+ });
+ const [planned] = await db
+ .insert(schema.columnTable)
+ .values({
+ projectId: f.project.id,
+ name: "Planned",
+ slug: "planned",
+ position: -1,
+ isFinal: false,
+ })
+ .returning();
+ await db
+ .update(schema.taskTable)
+ .set({
+ status: planned!.slug,
+ columnId: planned!.id,
+ priority: "urgent",
+ })
+ .where(eq(schema.taskTable.id, f.task.id));
+ await db.insert(schema.labelTable).values({
+ workspaceId: f.workspace.id,
+ taskId: f.task.id,
+ name: "local-only",
+ color: "#123456",
+ });
+ const review = await reviewSyncResume(f.project.id, type, link.id);
+ await resumeSync(f.project.id, type, link.id, review.token, source);
+ const baseline = [
+ "export",
+ "priority:low",
+ "status:to-do",
+ "remote-old",
+ ];
+ async function receive(
+ names: string[],
+ previous: string[],
+ added = "new-remote",
+ ) {
+ if (type === "github")
+ await handleIssueLabeled({
+ action: "labeled",
+ installation: { id: 2 },
+ repository: { id: 1, owner: { login: "team" }, name: "repo" },
+ issue: { number: 12, labels: names },
+ label: { name: added, color: "123456" },
+ });
+ else if (type === "gitea")
+ await handleGiteaIssueLabeled(
+ {
+ action: "label_updated",
+ repository: {
+ owner: { login: "team" },
+ name: "repo",
+ html_url: "https://git.example/team/repo",
+ },
+ issue: { number: 12, labels: names },
+ },
+ f.integration.id,
+ );
+ else
+ await handleGitlabIssueUpdated(
+ {
+ object_attributes: {
+ iid: 12,
+ title: "Repository title",
+ description: "Repository body",
+ state: "opened",
+ url: "https://gitlab.example/team/repo/-/issues/12",
+ },
+ changes: {
+ labels: {
+ previous: previous.map((title) => ({ title })),
+ current: names.map((title) => ({ title })),
+ },
+ },
+ project: {
+ name: "repo",
+ path_with_namespace: "team/repo",
+ web_url: "https://gitlab.example/team/repo",
+ },
+ },
+ f.integration.id,
+ );
+ }
+ const first = [...baseline, "new-remote"];
+ await receive(first, baseline);
+ expect(
+ await db.query.taskTable.findFirst({
+ where: eq(schema.taskTable.id, f.task.id),
+ }),
+ ).toMatchObject({
+ priority: "urgent",
+ status: "planned",
+ columnId: planned!.id,
+ });
+ const labels = await db.query.labelTable.findMany({
+ where: eq(schema.labelTable.taskId, f.task.id),
+ });
+ expect(labels.map((label) => label.name).sort()).toEqual([
+ "export",
+ "local-only",
+ "new-remote",
+ ]);
+ const changed = [
+ "export",
+ "priority:high",
+ "status:in-progress",
+ "remote-old",
+ "new-remote",
+ ];
+ await receive(changed, first, "priority:high");
+ expect(
+ await db.query.taskTable.findFirst({
+ where: eq(schema.taskTable.id, f.task.id),
+ }),
+ ).toMatchObject({ priority: "high", status: "in-progress" });
+ },
+ );
+
it("imports a closed issue gaining a label into a completed column", async () => {
const f = await setup(type);
if (type === "github") {
diff --git a/tests/api-integration/integration-sync-rules.test.ts b/tests/api-integration/integration-sync-rules.test.ts
index e33a1b063..07b21f927 100644
--- a/tests/api-integration/integration-sync-rules.test.ts
+++ b/tests/api-integration/integration-sync-rules.test.ts
@@ -13,7 +13,7 @@ import { reviewSyncResume } from "../../apps/api/src/integration-sync/controller
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 { withIntegrationTask } from "../../apps/api/src/plugins/github/services/integration-task-scope";
+import { withIntegrationLink } from "../../apps/api/src/plugins/github/services/with-integration-link";
import { withTaskSyncCreation } from "../../apps/api/src/plugins/sync/create-task-issue";
import {
canSyncTask,
@@ -324,7 +324,7 @@ describe("integration label policies", () => {
await f.assign();
expect(await canSyncTask(f.task.id, f.integration.id)).toBe(false);
expect(await f.preview()).toMatchObject({ needsReview: 1, willCreate: 0 });
- await withIntegrationTask(f.task.id, f.integration, async (tx) =>
+ await withIntegrationLink(link, f.integration, async (tx) =>
tx
.update(schema.taskTable)
.set({ title: "Should not be applied" })
diff --git a/tests/api-integration/integration-task-ownership.test.ts b/tests/api-integration/integration-task-ownership.test.ts
index 559ad46f3..5121c7b46 100644
--- a/tests/api-integration/integration-task-ownership.test.ts
+++ b/tests/api-integration/integration-task-ownership.test.ts
@@ -1,4 +1,4 @@
-import { eq } from "drizzle-orm";
+import { eq, sql } from "drizzle-orm";
import * as eligibility from "../../apps/api/src/plugins/sync/eligibility";
import {
afterEach,
@@ -665,24 +665,13 @@ it("does not apply a webhook after its link is paused while waiting for the link
const f = await setup();
let release!: () => void;
let locked!: () => void;
- let checked!: () => void;
const gate = new Promise<void>((resolve) => {
release = resolve;
});
const acquired = new Promise<void>((resolve) => {
locked = resolve;
});
- const eligibilityChecked = new Promise<void>((resolve) => {
- checked = resolve;
- });
- const original = eligibility.canSyncTask;
- const guard = vi
- .spyOn(eligibility, "canSyncTask")
- .mockImplementation(async (...args) => {
- const result = await original(...args);
- checked();
- return result;
- });
+ const guard = vi.spyOn(eligibility, "canSyncTask");
const pause = db.transaction(async (tx) => {
await tx
.select()
@@ -710,11 +699,22 @@ it("does not apply a webhook after its link is paused while waiting for the link
f.integration.id,
);
try {
- await eligibilityChecked;
+ await vi.waitFor(async () => {
+ const waiting = await db.execute<{ blocked: boolean }>(sql`
+ select exists (
+ select 1 from pg_stat_activity
+ where datname = current_database()
+ and wait_event_type = 'Lock'
+ and query like '%external_link%'
+ ) as blocked
+ `);
+ expect(waiting.rows[0]?.blocked).toBe(true);
+ });
+ expect(guard).not.toHaveBeenCalled();
release();
await pause;
await webhook;
- expect(guard).toHaveBeenCalledTimes(2);
+ expect(guard).toHaveBeenCalledOnce();
await expectPrivateTask(f.task.id);
} finally {
release();
diff --git a/tests/api/gitlab-integration/import-gitlab-issues.test.ts b/tests/api/gitlab-integration/import-gitlab-issues.test.ts
index 018b14524..623519766 100644
--- a/tests/api/gitlab-integration/import-gitlab-issues.test.ts
+++ b/tests/api/gitlab-integration/import-gitlab-issues.test.ts
@@ -6,6 +6,10 @@ const mocks = vi.hoisted(() => ({
insertValues: vi.fn(),
}));
+vi.mock("../../../apps/api/src/plugins/sync/eligibility", () => ({
+ canSyncTask: vi.fn(async () => true),
+}));
+
vi.mock("../../../apps/api/src/database", () => ({
default: {
select: () => ({