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): guard label writes and bound sync refreshes

Tin1d63fa6b09b0
diff --git a/apps/api/src/plugins/gitea/utils/sync-label-to-gitea.ts b/apps/api/src/plugins/gitea/utils/sync-label-to-gitea.ts
index fe1af5133..abe06e9b1 100644
--- a/apps/api/src/plugins/gitea/utils/sync-label-to-gitea.ts
+++ b/apps/api/src/plugins/gitea/utils/sync-label-to-gitea.ts
@@ -1,3 +1,4 @@
+import { dispatchIssueWrite } from "../../sync/dispatch-issue-write";
import { canSyncTask } from "../../sync/eligibility";
import { eq } from "drizzle-orm";
import db from "../../../database";
@@ -92,6 +93,8 @@ async function getGiteaIssueContext(taskId: string) {
}
return {
+ externalLink,
+ expectedConfig: integration.config,
client,
config,
issueNumber,
@@ -117,12 +120,19 @@ export async function syncLabelToGitea(
if (!label) {
try {
- label = await client.createLabel(
- config.repositoryOwner,
- config.repositoryName,
- labelName,
- color,
+ const created = await dispatchIssueWrite(
+ ctx.externalLink,
+ ctx.expectedConfig,
+ () =>
+ client.createLabel(
+ config.repositoryOwner,
+ config.repositoryName,
+ labelName,
+ color,
+ ),
);
+ if (!created) return;
+ label = created.value;
} catch (error) {
console.error(`Failed to create label "${labelName}" in Gitea:`, error);
return;
@@ -139,11 +149,14 @@ export async function syncLabelToGitea(
if (existingIds.includes(label.id)) {
return;
}
- await client.addLabelsToIssue(
- config.repositoryOwner,
- config.repositoryName,
- issueNumber,
- [label.id],
+ const labelId = label.id;
+ await dispatchIssueWrite(ctx.externalLink, ctx.expectedConfig, () =>
+ client.addLabelsToIssue(
+ config.repositoryOwner,
+ config.repositoryName,
+ issueNumber,
+ [labelId],
+ ),
);
} catch (error) {
console.error(`Failed to add label "${labelName}" to Gitea issue:`, error);
@@ -164,11 +177,13 @@ export async function removeLabelFromGitea(taskId: string, labelName: string) {
if (!label) return;
try {
- await client.removeLabelFromIssue(
- config.repositoryOwner,
- config.repositoryName,
- issueNumber,
- label.id,
+ await dispatchIssueWrite(ctx.externalLink, ctx.expectedConfig, () =>
+ client.removeLabelFromIssue(
+ config.repositoryOwner,
+ config.repositoryName,
+ issueNumber,
+ label.id,
+ ),
);
} catch (error) {
console.error(
diff --git a/apps/api/src/plugins/github/utils/sync-label-to-github.ts b/apps/api/src/plugins/github/utils/sync-label-to-github.ts
index 0e5ef9236..c489e8f2f 100644
--- a/apps/api/src/plugins/github/utils/sync-label-to-github.ts
+++ b/apps/api/src/plugins/github/utils/sync-label-to-github.ts
@@ -1,3 +1,4 @@
+import { dispatchIssueWrite } from "../../sync/dispatch-issue-write";
import { canSyncTask } from "../../sync/eligibility";
import { eq } from "drizzle-orm";
import db from "../../../database";
@@ -83,6 +84,8 @@ async function getGitHubContext(taskId: string) {
}
return {
+ externalLink,
+ expectedConfig: integration.config,
octokit,
owner: config.repositoryOwner,
repo: config.repositoryName,
@@ -109,12 +112,18 @@ export async function syncLabelToGitHub(
});
} catch {
try {
- await octokit.rest.issues.createLabel({
- owner,
- repo,
- name: labelName,
- color,
- });
+ const created = await dispatchIssueWrite(
+ ctx.externalLink,
+ ctx.expectedConfig,
+ () =>
+ octokit.rest.issues.createLabel({
+ owner,
+ repo,
+ name: labelName,
+ color,
+ }),
+ );
+ if (!created) return;
} catch (createError) {
console.error(
`Failed to create label "${labelName}" in GitHub:`,
@@ -125,12 +134,14 @@ export async function syncLabelToGitHub(
}
try {
- await octokit.rest.issues.addLabels({
- owner,
- repo,
- issue_number: issueNumber,
- labels: [labelName],
- });
+ await dispatchIssueWrite(ctx.externalLink, ctx.expectedConfig, () =>
+ octokit.rest.issues.addLabels({
+ owner,
+ repo,
+ issue_number: issueNumber,
+ labels: [labelName],
+ }),
+ );
} catch (error) {
console.error(`Failed to add label "${labelName}" to GitHub issue:`, error);
}
@@ -143,12 +154,14 @@ export async function removeLabelFromGitHub(taskId: string, labelName: string) {
const { octokit, owner, repo, issueNumber } = ctx;
try {
- await octokit.rest.issues.removeLabel({
- owner,
- repo,
- issue_number: issueNumber,
- name: labelName,
- });
+ await dispatchIssueWrite(ctx.externalLink, ctx.expectedConfig, () =>
+ octokit.rest.issues.removeLabel({
+ owner,
+ repo,
+ issue_number: issueNumber,
+ name: labelName,
+ }),
+ );
} catch (error) {
console.error(
`Failed to remove label "${labelName}" from GitHub issue:`,
diff --git a/apps/api/src/plugins/gitlab/utils/sync-label-to-gitlab.ts b/apps/api/src/plugins/gitlab/utils/sync-label-to-gitlab.ts
index 3900dd2f9..167fc2144 100644
--- a/apps/api/src/plugins/gitlab/utils/sync-label-to-gitlab.ts
+++ b/apps/api/src/plugins/gitlab/utils/sync-label-to-gitlab.ts
@@ -1,3 +1,4 @@
+import { dispatchIssueWrite } from "../../sync/dispatch-issue-write";
import { canSyncTask } from "../../sync/eligibility";
import { eq } from "drizzle-orm";
import db from "../../../database";
@@ -89,6 +90,8 @@ async function getGitlabIssueContext(taskId: string) {
}
return {
+ externalLink,
+ expectedConfig: externalLink.integration.config,
client: createGitlabClient(config),
config,
issueIid,
@@ -120,11 +123,17 @@ export async function syncLabelToGitlab(
if (!labels.some((l) => l.name === labelName)) {
try {
- await client.createLabel(
- config.projectPath,
- labelName,
- toHexColor(labelColor),
+ const created = await dispatchIssueWrite(
+ ctx.externalLink,
+ ctx.expectedConfig,
+ () =>
+ client.createLabel(
+ config.projectPath,
+ labelName,
+ toHexColor(labelColor),
+ ),
);
+ if (!created) return;
} catch (error) {
console.error(`Failed to create label "${labelName}" in GitLab:`, error);
return;
@@ -136,9 +145,11 @@ export async function syncLabelToGitlab(
if (issue.labels?.includes(labelName)) {
return;
}
- await client.updateIssue(config.projectPath, issueIid, {
- add_labels: labelName,
- });
+ await dispatchIssueWrite(ctx.externalLink, ctx.expectedConfig, () =>
+ client.updateIssue(config.projectPath, issueIid, {
+ add_labels: labelName,
+ }),
+ );
} catch (error) {
console.error(`Failed to add label "${labelName}" to GitLab issue:`, error);
}
@@ -152,9 +163,11 @@ export async function removeLabelFromGitlab(taskId: string, labelName: string) {
const { client, config, issueIid } = ctx;
try {
- await client.updateIssue(config.projectPath, issueIid, {
- remove_labels: labelName,
- });
+ await dispatchIssueWrite(ctx.externalLink, ctx.expectedConfig, () =>
+ client.updateIssue(config.projectPath, issueIid, {
+ remove_labels: labelName,
+ }),
+ );
} catch (error) {
console.error(
`Failed to remove label "${labelName}" from GitLab issue:`,
diff --git a/apps/api/src/plugins/sync/reconcile.ts b/apps/api/src/plugins/sync/reconcile.ts
index e11e820ef..b7cda90c2 100644
--- a/apps/api/src/plugins/sync/reconcile.ts
+++ b/apps/api/src/plugins/sync/reconcile.ts
@@ -1,10 +1,17 @@
import { and, asc, eq, gt } from "drizzle-orm";
import db from "../../database";
-import { externalLinkTable, taskTable } from "../../database/schema";
+import {
+ externalLinkTable,
+ projectTable,
+ taskTable,
+} from "../../database/schema";
import { publishEvent } from "../../events";
import { getPlugin } from "../registry";
import { canSyncTask } from "./eligibility";
import { getSyncIntegrations } from "./integrations";
+import { readSyncRules } from "./rules";
+import { outgoingPredicate } from "./task-predicate";
+import { reconciliationPredicate } from "./reconciliation-predicate";
export async function reconcileTaskSync(
projectId: string,
@@ -12,7 +19,8 @@ export async function reconcileTaskSync(
onlyIntegrationId?: string,
) {
const integrations = await getSyncIntegrations(projectId, onlyIntegrationId);
- await reconcileTaskWithIntegrations(projectId, taskId, integrations);
+ if (await reconcileTaskWithIntegrations(projectId, taskId, integrations))
+ await publishEvent("project.updated", { projectId });
}
async function reconcileTaskWithIntegrations(
@@ -20,7 +28,7 @@ async function reconcileTaskWithIntegrations(
taskId: string,
integrations: Awaited<ReturnType<typeof getSyncIntegrations>>,
) {
- if (!integrations.length) return;
+ if (!integrations.length) return false;
const links = () =>
db.query.externalLinkTable.findMany({
where: and(
@@ -73,8 +81,11 @@ async function reconcileTaskWithIntegrations(
});
}
}
- if (JSON.stringify(before) !== JSON.stringify(await links()))
+ if (JSON.stringify(before) !== JSON.stringify(await links())) {
await publishEvent("task.updated", { projectId, taskId });
+ return true;
+ }
+ return false;
}
export async function reconcileProjectSync(
@@ -83,31 +94,53 @@ export async function reconcileProjectSync(
) {
const integrations = await getSyncIntegrations(projectId, integrationId);
if (!integrations.length) return;
- let cursor: string | undefined;
- for (;;) {
- const tasks = await db
- .select({ id: taskTable.id })
- .from(taskTable)
- .where(
- and(
- eq(taskTable.projectId, projectId),
- cursor ? gt(taskTable.id, cursor) : undefined,
- ),
- )
- .orderBy(asc(taskTable.id))
- .limit(50);
- if (!tasks.length) return;
- for (const task of tasks) {
- try {
- await reconcileTaskWithIntegrations(projectId, task.id, integrations);
- } catch {
- console.error("Task sync reconciliation failed", {
- projectId,
- taskId: task.id,
- integrationId,
- });
+ const project = await db.query.projectTable.findFirst({
+ where: eq(projectTable.id, projectId),
+ columns: { workspaceId: true },
+ });
+ if (!project) return;
+ let changed = false;
+ try {
+ for (const integration of integrations) {
+ const scope = await outgoingPredicate(
+ project.workspaceId,
+ readSyncRules(integration.config)!.outgoing,
+ );
+ let cursor: string | undefined;
+ for (;;) {
+ const tasks = await db
+ .select({ id: taskTable.id })
+ .from(taskTable)
+ .where(
+ and(
+ eq(taskTable.projectId, projectId),
+ reconciliationPredicate(integration.id, scope.predicate),
+ cursor ? gt(taskTable.id, cursor) : undefined,
+ ),
+ )
+ .orderBy(asc(taskTable.id))
+ .limit(50);
+ if (!tasks.length) break;
+ for (const task of tasks) {
+ try {
+ if (
+ await reconcileTaskWithIntegrations(projectId, task.id, [
+ integration,
+ ])
+ )
+ changed = true;
+ } catch {
+ console.error("Task sync reconciliation failed", {
+ projectId,
+ taskId: task.id,
+ integrationId: integration.id,
+ });
+ }
+ }
+ cursor = tasks.at(-1)?.id;
}
}
- cursor = tasks.at(-1)?.id;
+ } finally {
+ if (changed) await publishEvent("project.updated", { projectId });
}
}
diff --git a/apps/api/src/plugins/sync/reconciliation-predicate.ts b/apps/api/src/plugins/sync/reconciliation-predicate.ts
new file mode 100644
index 000000000..7f53eee2e
--- /dev/null
+++ b/apps/api/src/plugins/sync/reconciliation-predicate.ts
@@ -0,0 +1,32 @@
+import { and, not, or, sql, type SQL } from "drizzle-orm";
+import { externalLinkTable, taskTable } from "../../database/schema";
+
+export function reconciliationPredicate(integrationId: string, outgoing: SQL) {
+ const linked = sql<boolean>`exists (
+ select 1 from ${externalLinkTable} scoped_link
+ where scoped_link.task_id = ${taskTable.id}
+ and scoped_link.integration_id = ${integrationId}
+ and scoped_link.resource_type = 'issue'
+ )`;
+ const pending = sql<boolean>`exists (
+ select 1 from ${externalLinkTable} scoped_link
+ where scoped_link.task_id = ${taskTable.id}
+ and scoped_link.integration_id = ${integrationId}
+ and scoped_link.resource_type = 'issue'
+ and scoped_link.metadata ~ '"syncInitializationPending"[[:space:]]*:[[:space:]]*true'
+ and not coalesce(scoped_link.metadata ~ '"syncFilterPaused"[[:space:]]*:[[:space:]]*true', false)
+ )`;
+ const unpaused = sql<boolean>`exists (
+ select 1 from ${externalLinkTable} scoped_link
+ where scoped_link.task_id = ${taskTable.id}
+ and scoped_link.integration_id = ${integrationId}
+ and scoped_link.resource_type = 'issue'
+ and not coalesce(scoped_link.metadata ~ '"syncFilterPaused"[[:space:]]*:[[:space:]]*true', false)
+ )`;
+ // Label renames and reconnects also use reconciliation, so excluded links
+ // still need pausing even when no rule-save transaction ran beforehand.
+ return or(
+ and(outgoing, or(not(linked), pending)),
+ and(not(outgoing), unpaused),
+ );
+}
diff --git a/apps/web/src/hooks/use-project-websocket-cache.test.tsx b/apps/web/src/hooks/use-project-websocket-cache.test.tsx
index 3f3610a1a..f5bc5cce8 100644
--- a/apps/web/src/hooks/use-project-websocket-cache.test.tsx
+++ b/apps/web/src/hooks/use-project-websocket-cache.test.tsx
@@ -503,8 +503,22 @@ it.each([
expect(mocks.client.invalidateQueries).toHaveBeenCalledWith({
queryKey: ["integration-sync-preview", "p"],
});
- expect(mocks.client.invalidateQueries).toHaveBeenCalledWith({
+ expect(mocks.client.invalidateQueries).not.toHaveBeenCalledWith({
queryKey: ["integration-sync-review", "p"],
});
});
});
+
+it("keeps sync comparisons and scope queries stable during unrelated task edits", async () => {
+ renderHook(() => useProjectWebSocket("p"));
+ Socket.current.message("TASK_UPDATED", { taskId: "a" });
+ await vi.waitFor(() => expect(mocks.getTask).toHaveBeenCalled());
+ for (const key of [
+ "integration-sync",
+ "integration-sync-preview",
+ "integration-sync-review",
+ ])
+ expect(mocks.client.invalidateQueries).not.toHaveBeenCalledWith({
+ queryKey: [key, "p"],
+ });
+});
diff --git a/apps/web/src/hooks/use-project-websocket.ts b/apps/web/src/hooks/use-project-websocket.ts
index 34980613a..104ad6806 100644
--- a/apps/web/src/hooks/use-project-websocket.ts
+++ b/apps/web/src/hooks/use-project-websocket.ts
@@ -73,7 +73,6 @@ export function useProjectWebSocket(projectId: string) {
if (
[
"PROJECT_UPDATED",
- "TASK_UPDATED",
"TASK_LABEL_UPDATED",
"TASK_CREATED",
"TASK_DELETED",
@@ -86,9 +85,6 @@ export function useProjectWebSocket(projectId: string) {
queryClient.invalidateQueries({
queryKey: ["integration-sync-preview", projectId],
});
- queryClient.invalidateQueries({
- queryKey: ["integration-sync-review", projectId],
- });
}
if (message.type === "PROJECT_UPDATED") {
queryClient.invalidateQueries({ queryKey: ["projects"] });
diff --git a/tests/api-integration/integration-label-dispatch.test.ts b/tests/api-integration/integration-label-dispatch.test.ts
new file mode 100644
index 000000000..04d902c67
--- /dev/null
+++ b/tests/api-integration/integration-label-dispatch.test.ts
@@ -0,0 +1,186 @@
+import { eq } from "drizzle-orm";
+import { beforeEach, expect, it, vi } from "vite-plus/test";
+import db, { schema } from "../../apps/api/src/database";
+import * as eligibility from "../../apps/api/src/plugins/sync/eligibility";
+import { updateExternalLink } from "../../apps/api/src/plugins/github/services/link-manager";
+import {
+ removeLabelFromGitHub,
+ syncLabelToGitHub,
+} from "../../apps/api/src/plugins/github/utils/sync-label-to-github";
+import {
+ removeLabelFromGitea,
+ syncLabelToGitea,
+} from "../../apps/api/src/plugins/gitea/utils/sync-label-to-gitea";
+import {
+ removeLabelFromGitlab,
+ syncLabelToGitlab,
+} from "../../apps/api/src/plugins/gitlab/utils/sync-label-to-gitlab";
+import { resetTestDatabase } from "./helpers/database";
+import {
+ createProjectFixture,
+ createWorkspaceMember,
+} from "./helpers/fixtures";
+
+const mocks = vi.hoisted(() => ({
+ createLabel: vi.fn(),
+ addLabel: vi.fn(),
+ removeLabel: vi.fn(),
+}));
+vi.mock("../../apps/api/src/plugins/github/utils/github-app", () => ({
+ getVerifiedInstallationOctokit: async () => ({
+ rest: {
+ issues: {
+ getLabel: async () => {
+ throw new Error("Label does not exist");
+ },
+ createLabel: mocks.createLabel,
+ addLabels: mocks.addLabel,
+ removeLabel: mocks.removeLabel,
+ },
+ },
+ }),
+}));
+vi.mock("../../apps/api/src/plugins/gitea/utils/gitea-api", () => ({
+ createGiteaClient: () => ({
+ listLabels: async () => [{ id: 7, name: "bug" }],
+ getIssue: async () => ({ labels: [] }),
+ createLabel: mocks.createLabel,
+ addLabelsToIssue: mocks.addLabel,
+ removeLabelFromIssue: mocks.removeLabel,
+ }),
+}));
+vi.mock("../../apps/api/src/plugins/gitlab/utils/gitlab-api", () => ({
+ createGitlabClient: () => ({
+ listLabels: async () => [],
+ getIssue: async () => ({ labels: [] }),
+ createLabel: mocks.createLabel,
+ updateIssue: async (
+ _project: string,
+ _issue: number,
+ change: { add_labels?: string },
+ ) => (change.add_labels ? mocks.addLabel : mocks.removeLabel)(),
+ }),
+}));
+
+beforeEach(async () => {
+ await resetTestDatabase();
+ vi.clearAllMocks();
+ mocks.createLabel.mockResolvedValue({ id: 7, name: "bug" });
+ mocks.addLabel.mockResolvedValue(undefined);
+ mocks.removeLabel.mockResolvedValue(undefined);
+});
+
+it.each(
+ (["github", "gitea", "gitlab"] as const).flatMap((provider) =>
+ (["add", "remove"] as const).flatMap((action) =>
+ (["unchanged", "paused", "rule_changed"] as const).map((change) => ({
+ provider,
+ action,
+ change,
+ })),
+ ),
+ ),
+)(
+ "$provider custom-label $action rechecks scope at dispatch ($change)",
+ async ({ provider, action, change }) => {
+ const { user, workspace } = await createWorkspaceMember();
+ const { project } = await createProjectFixture({
+ workspaceId: workspace.id,
+ });
+ const config = {
+ repositoryOwner: "team",
+ repositoryName: "repo",
+ repositoryId: 1,
+ installationId: 2,
+ verifiedGithubAccountId: "3",
+ verifiedByUserId: user.id,
+ baseUrl: "https://git.example",
+ projectPath: "team/repo",
+ accessToken: "fake-test-token",
+ };
+ const [integration] = await db
+ .insert(schema.integrationTable)
+ .values({
+ projectId: project.id,
+ type: provider,
+ isActive: true,
+ config: JSON.stringify(config),
+ })
+ .returning();
+ const [task] = await db
+ .insert(schema.taskTable)
+ .values({
+ projectId: project.id,
+ title: "Label race",
+ number: 1,
+ status: "to-do",
+ })
+ .returning();
+ const [link] = await db
+ .insert(schema.externalLinkTable)
+ .values({
+ taskId: task!.id,
+ integrationId: integration!.id,
+ resourceType: "issue",
+ externalId: "12",
+ url: "https://git.example/team/repo/issues/12",
+ })
+ .returning();
+ let started!: () => void;
+ let release!: () => void;
+ const checked = new Promise<void>((resolve) => {
+ started = resolve;
+ });
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const original = eligibility.canSyncTask;
+ const guard = vi
+ .spyOn(eligibility, "canSyncTask")
+ .mockImplementationOnce(async (...args) => {
+ const result = await original(...args);
+ expect(result).toBe(true);
+ started();
+ await gate;
+ return result;
+ });
+ const methods = {
+ github: { add: syncLabelToGitHub, remove: removeLabelFromGitHub },
+ gitea: { add: syncLabelToGitea, remove: removeLabelFromGitea },
+ gitlab: { add: syncLabelToGitlab, remove: removeLabelFromGitlab },
+ };
+ const writing = methods[provider][action](task!.id, "bug", "#123456");
+ try {
+ await checked;
+ if (change === "paused")
+ await updateExternalLink(link!.id, {
+ metadata: { syncFilterPaused: true },
+ });
+ if (change === "rule_changed")
+ await db
+ .update(schema.integrationTable)
+ .set({
+ config: JSON.stringify({
+ ...config,
+ syncRules: {
+ outgoing: { mode: "labels", match: "any", labels: ["missing"] },
+ incoming: { mode: "all" },
+ },
+ }),
+ })
+ .where(eq(schema.integrationTable.id, integration!.id));
+ } finally {
+ release();
+ await writing;
+ guard.mockRestore();
+ }
+ expect(mocks.addLabel).toHaveBeenCalledTimes(
+ change === "unchanged" && action === "add" ? 1 : 0,
+ );
+ expect(mocks.removeLabel).toHaveBeenCalledTimes(
+ change === "unchanged" && action === "remove" ? 1 : 0,
+ );
+ if (change !== "unchanged")
+ expect(mocks.createLabel).not.toHaveBeenCalled();
+ },
+);
diff --git a/tests/api-integration/integration-sync-providers.test.ts b/tests/api-integration/integration-sync-providers.test.ts
index 15b618ad7..30b23fbf5 100644
--- a/tests/api-integration/integration-sync-providers.test.ts
+++ b/tests/api-integration/integration-sync-providers.test.ts
@@ -27,6 +27,7 @@ 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 * as eligibility 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";
@@ -250,6 +251,39 @@ describe.each(["github", "gitea", "gitlab"] as const)(
await reconcileProjectSync(f.project.id, f.integration.id);
expect(create).toHaveBeenCalledOnce();
});
+ it("skips completed links and excluded unlinked tasks, while still pausing excluded links", async () => {
+ const f = await setup(type);
+ await f.assign();
+ await reconcileTaskSync(f.project.id, f.task.id);
+ await db.insert(schema.taskTable).values(
+ Array.from({ length: 30 }, (_, index) => ({
+ projectId: f.project.id,
+ title: "Unmatched task",
+ number: index + 2,
+ status: "to-do",
+ })),
+ );
+ const guard = vi.spyOn(eligibility, "canSyncTask");
+ const publish = vi.spyOn(events, "publishEvent");
+ await reconcileProjectSync(f.project.id, f.integration.id);
+ expect(guard).not.toHaveBeenCalled();
+ expect(publish).not.toHaveBeenCalled();
+ await db
+ .delete(schema.labelTable)
+ .where(eq(schema.labelTable.taskId, f.task.id));
+ await reconcileProjectSync(f.project.id, f.integration.id);
+ expect(guard).toHaveBeenCalledOnce();
+ const link = await db.query.externalLinkTable.findFirst({
+ where: eq(schema.externalLinkTable.taskId, f.task.id),
+ });
+ expect(JSON.parse(link!.metadata!)).toMatchObject({
+ syncFilterPaused: true,
+ });
+ expect(
+ publish.mock.calls.filter(([name]) => name === "project.updated"),
+ ).toHaveLength(1);
+ 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);
@@ -987,6 +1021,36 @@ it("waits for another instance's creation lease instead of dropping the export",
expect(await db.query.externalLinkTable.findMany()).toHaveLength(1);
});
+it("refreshes scope once after a bulk run pauses multiple links", async () => {
+ const f = await setup("gitea");
+ const [other] = await db
+ .insert(schema.taskTable)
+ .values({
+ projectId: f.project.id,
+ title: "Other linked task",
+ number: 2,
+ status: "to-do",
+ })
+ .returning();
+ await db.insert(schema.externalLinkTable).values(
+ [f.task.id, other!.id].map((taskId, index) => ({
+ taskId,
+ integrationId: f.integration.id,
+ resourceType: "issue",
+ externalId: String(index + 1),
+ url: `https://git.example/team/repo/issues/${index + 1}`,
+ })),
+ );
+ const publish = vi.spyOn(events, "publishEvent");
+ await reconcileProjectSync(f.project.id);
+ expect(
+ publish.mock.calls.filter(([name]) => name === "task.updated"),
+ ).toHaveLength(2);
+ expect(
+ publish.mock.calls.filter(([name]) => name === "project.updated"),
+ ).toEqual([["project.updated", { projectId: f.project.id }]]);
+});
+
it("broadcasts only changed links and avoids task scans for unconfigured integrations", async () => {
const f = await setup("gitea");
const publish = vi.spyOn(events, "publishEvent");
@@ -994,7 +1058,10 @@ it("broadcasts only changed links and avoids task scans for unconfigured integra
expect(publish).not.toHaveBeenCalled();
await f.assign();
await reconcileTaskSync(f.project.id, f.task.id);
- expect(publish).toHaveBeenCalledOnce();
+ expect(publish.mock.calls).toEqual([
+ ["task.updated", { projectId: f.project.id, taskId: f.task.id }],
+ ["project.updated", { projectId: f.project.id }],
+ ]);
publish.mockClear();
await reconcileProjectSync(f.project.id);
expect(publish).not.toHaveBeenCalled();
diff --git a/tests/api/plugins/gitlab/utils/sync-label-to-gitlab.test.ts b/tests/api/plugins/gitlab/utils/sync-label-to-gitlab.test.ts
index 09c7f9c40..72f810318 100644
--- a/tests/api/plugins/gitlab/utils/sync-label-to-gitlab.test.ts
+++ b/tests/api/plugins/gitlab/utils/sync-label-to-gitlab.test.ts
@@ -106,3 +106,14 @@ it("still removes ordinary labels", async () => {
vi.mock("../../../../../apps/api/src/plugins/sync/eligibility", () => ({
canSyncTask: async () => true,
}));
+
+vi.mock(
+ "../../../../../apps/api/src/plugins/sync/dispatch-issue-write",
+ () => ({
+ dispatchIssueWrite: async (
+ _link: unknown,
+ _config: unknown,
+ send: () => Promise<unknown>,
+ ) => ({ value: await send() }),
+ }),
+);