⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
feat(integrations): add label-based sync in advanced settings
Tin82e0390def0c
diff --git a/apps/api/src/gitea-integration/controllers/create-gitea-integration.ts b/apps/api/src/gitea-integration/controllers/create-gitea-integration.tsindex 314da32d9..519f13968 100644--- a/apps/api/src/gitea-integration/controllers/create-gitea-integration.ts+++ b/apps/api/src/gitea-integration/controllers/create-gitea-integration.ts@@ -111,12 +111,11 @@ async function createGiteaIntegration({}}+ let previousConfig: Partial<GiteaConfig> = {};let webhookSecret = randomBytes(24).toString("hex");if (existingIntegration) {try {- const previousConfig = JSON.parse(- existingIntegration.config,- ) as GiteaConfig;+ previousConfig = JSON.parse(existingIntegration.config) as GiteaConfig;webhookSecret = previousConfig.webhookSecret ?? webhookSecret;} catch (error) {console.warn("Failed to parse existing Gitea config for webhook secret", {@@ -134,6 +133,8 @@ async function createGiteaIntegration({webhookSecret,);+ if (previousConfig.syncRules) config.syncRules = previousConfig.syncRules;+const validation = await validateGiteaConfig(config);if (!validation.valid) {throw new HTTPException(400, {diff --git a/apps/api/src/gitea-integration/controllers/import-gitea-issues.ts b/apps/api/src/gitea-integration/controllers/import-gitea-issues.tsindex 0d438466d..ae2fde150 100644--- a/apps/api/src/gitea-integration/controllers/import-gitea-issues.ts+++ b/apps/api/src/gitea-integration/controllers/import-gitea-issues.ts@@ -1,3 +1,4 @@+import { acceptsIssue } from "../../plugins/sync/rules";import { and, eq, inArray, notInArray } from "drizzle-orm";import { HTTPException } from "hono/http-exception";import db from "../../database";@@ -212,6 +213,8 @@ async function importSingleIssue(issue.number.toString(),);+ if (!existingLink && !acceptsIssue(config, issue.labels)) return "skipped";+const labels = issue.labels ?? [];const adaptedLabels = toPriorityLabels(labels);const priority = extractIssuePriority(adaptedLabels);@@ -280,6 +283,21 @@ async function importSingleIssue(null,{ id: integrationId, projectId, project: { workspaceId } },async (tx) => {+ const binding = await tx.query.integrationTable.findFirst({+ where: eq(integrationTable.id, integrationId),+ });+ if (+ !binding ||+ binding.config !== JSON.stringify(config) ||+ !acceptsIssue(binding.config, issue.labels) ||+ (await findExternalLink(+ integrationId,+ "issue",+ String(issue.number),+ tx,+ ))+ )+ return null;const nextNumber = await claimTaskNumber(projectId, tx);const taskValues: typeof taskTable.$inferInsert = {diff --git a/apps/api/src/gitea-integration/index.ts b/apps/api/src/gitea-integration/index.tsindex 287206172..a9bb42ac7 100644--- a/apps/api/src/gitea-integration/index.ts+++ b/apps/api/src/gitea-integration/index.ts@@ -2,6 +2,7 @@ import { and, eq } from "drizzle-orm";import type { Context } from "hono";import { HTTPException } from "hono/http-exception";import db from "../database";+import { publishEvent } from "../events";import { integrationTable } from "../database/schema";import { scopeToProjectFromBody } from "../integrations/middleware";import { projectIdBody, projectIdParam } from "../integrations/schema";@@ -262,6 +263,11 @@ const giteaIntegration = apiRouter<BaseVariables & { workspaceId: string }>()if (!integration) {throw new HTTPException(500, { message: "Failed to load integration" });}+ if (integration)+ await publishEvent("integration.sync_rules_changed", {+ projectId,+ integrationId: integration.id,+ });return c.json(integration, 200);}).openapi(updateIntegrationRoute, async (c) => {@@ -319,6 +325,12 @@ const giteaIntegration = apiRouter<BaseVariables & { workspaceId: string }>()if (!updated) {throw new HTTPException(500, { message: "Failed to load integration" });}+ if (body.isActive === true && !row.isActive)+ await publishEvent("integration.sync_rules_changed", {+ projectId,+ integrationId: row.id,+ });+ await publishEvent("project.updated", { projectId });return c.json(updated, 200);}).openapi(deleteIntegrationRoute, async (c) => {diff --git a/apps/api/src/github-integration/controllers/import-issues.ts b/apps/api/src/github-integration/controllers/import-issues.tsindex 8c98ca101..603f26cda 100644--- a/apps/api/src/github-integration/controllers/import-issues.ts+++ b/apps/api/src/github-integration/controllers/import-issues.ts@@ -1,3 +1,6 @@+import { acceptsIssue, readSyncRules } from "../../plugins/sync/rules";+import { canSyncTask } from "../../plugins/sync/eligibility";+import { importIssueLabels } from "../../plugins/sync/issue-labels";import { createId } from "@paralleldrive/cuid2";import { and, asc, eq, isNull } from "drizzle-orm";import { HTTPException } from "hono/http-exception";@@ -173,6 +176,35 @@ export async function importIssues(projectId: string, runId?: string) {message: "GitHub import paused; retry to resume saved progress",});}+ let admitted = true;+ let scopeLabels: unknown = [];+ const rules = readSyncRules(integration.config);+ if (+ run.state.phase === "issues" &&+ (rules?.incoming.mode === "labels" || rules?.outgoing.mode === "labels")+ ) {+ const parsed = issuesPageSchema.safeParse(payload);+ const issue = parsed.success+ ? parsed.data.repository.issues.nodes[0]+ : undefined;+ if (issue) {+ try {+ const remote = await octokit.rest.issues.get({+ owner: config.repositoryOwner,+ repo: config.repositoryName,+ issue_number: issue.number,+ request: { timeout: 10_000 },+ });+ scopeLabels = remote.data.labels;+ admitted = acceptsIssue(integration.config, scopeLabels);+ } catch {+ throw new HTTPException(502, {+ message:+ "Issue labels could not be read; resume the import later",+ });+ }+ }+ }const currentRun: typeof githubImportTable.$inferSelect = run;const notifications = new Map<string,@@ -215,6 +247,8 @@ export async function importIssues(projectId: string, runId?: string) {for (const type of types)notifications.set(`${type}:${taskId}`, { type, taskId });},+ admitted,+ scopeLabels,);const [saved] = await tx.update(githubImportTable)@@ -277,6 +311,8 @@ async function applyPage(project: typeof projectTable.$inferSelect,config: GitHubConfig,announce: (taskId: string, ...types: ImportEvent[]) => void,+ admitted = true,+ scopeLabels: unknown = [],) {if (state.phase === "issues") {const parsed = issuesPageSchema.safeParse(payload);@@ -291,6 +327,14 @@ async function applyPage(finishIssue(state);return;}+ if (+ !admitted &&+ !(await findLink(tx, integrationId, "issue", issue.number))+ ) {+ state.skipped++;+ finishIssue(state);+ return;+ }const task = await importIssue(tx, issue, integrationId, project.id);if (!task) {state.skipped++;@@ -315,6 +359,7 @@ async function applyPage(label.name.startsWith("priority:"),),};+ await importIssueLabels(task.id, project.workspaceId, scopeLabels, tx);await importLabels(tx, issue.labels.nodes, task.id, project.workspaceId);await importComments(tx, issue.comments.nodes, task.id, state.startedAt);announce(task.id, "task.updated", "task.labels_updated", "comment.updated");@@ -363,7 +408,11 @@ async function applyPage(),).for("update");- if (!task || !linked) {+ if (+ !task ||+ !linked ||+ !(await canSyncTask(current.taskId, integrationId, tx))+ ) {state.skipped++;finishIssue(state);return;@@ -462,6 +511,7 @@ async function importIssue(const priority = extractIssuePriority(issue.labels.nodes);const status = extractIssueStatus(issue.labels.nodes);if (link) {+ if (!(await canSyncTask(link.taskId, integrationId, tx))) return null;const [task] = await tx.select().from(taskTable)@@ -606,7 +656,7 @@ async function linkPull(.from(taskTable).where(and(eq(taskTable.id, task.id), eq(taskTable.projectId, project.id))).for("share");- if (!scopedTask) return;+ if (!scopedTask || !(await canSyncTask(task.id, integrationId, tx))) return;await tx.insert(externalLinkTable).values({taskId: task.id,integrationId,diff --git a/apps/api/src/github-integration/index.ts b/apps/api/src/github-integration/index.tsindex 458765342..5e8a111e7 100644--- a/apps/api/src/github-integration/index.ts+++ b/apps/api/src/github-integration/index.ts@@ -2,6 +2,7 @@ import { and, eq } from "drizzle-orm";import type { Context } from "hono";import { HTTPException } from "hono/http-exception";import db from "../database";+import { publishEvent } from "../events";import { accountTable, integrationTable } from "../database/schema";import { scopeToProjectFromBody } from "../integrations/middleware";import { projectIdParam } from "../integrations/schema";@@ -314,6 +315,11 @@ const githubIntegration = apiRouter<BaseVariables & { workspaceId: string }>()repositoryName,});+ if (integration)+ await publishEvent("integration.sync_rules_changed", {+ projectId,+ integrationId: integration.id,+ });return c.json(integration, 200);}).openapi(updateIntegrationRoute, async (c) => {@@ -373,6 +379,12 @@ const githubIntegration = apiRouter<BaseVariables & { workspaceId: string }>()});const updated = await getGithubIntegration(projectId);+ if (body.isActive === true && !row.isActive)+ await publishEvent("integration.sync_rules_changed", {+ projectId,+ integrationId: row.id,+ });+ await publishEvent("project.updated", { projectId });return c.json(updated, 200);}).openapi(deleteIntegrationRoute, async (c) => {diff --git a/apps/api/src/gitlab-integration/controllers/create-gitlab-integration.ts b/apps/api/src/gitlab-integration/controllers/create-gitlab-integration.tsindex 35d307a3c..56f1a32ec 100644--- a/apps/api/src/gitlab-integration/controllers/create-gitlab-integration.ts+++ b/apps/api/src/gitlab-integration/controllers/create-gitlab-integration.ts@@ -36,6 +36,7 @@ function pickSettings(config: Partial<GitlabConfig>): Partial<GitlabConfig> {if (config.statusTransitions !== undefined) {settings.statusTransitions = config.statusTransitions;}+ if (config.syncRules !== undefined) settings.syncRules = config.syncRules;return settings;}diff --git a/apps/api/src/gitlab-integration/controllers/import-gitlab-issues.ts b/apps/api/src/gitlab-integration/controllers/import-gitlab-issues.tsindex c8db74d5b..d346e4bfd 100644--- a/apps/api/src/gitlab-integration/controllers/import-gitlab-issues.ts+++ b/apps/api/src/gitlab-integration/controllers/import-gitlab-issues.ts@@ -1,3 +1,4 @@+import { acceptsIssue } from "../../plugins/sync/rules";import { and, eq, inArray } from "drizzle-orm";import { HTTPException } from "hono/http-exception";import db from "../../database";@@ -189,6 +190,8 @@ async function importSingleIssue(issue.iid.toString(),);+ if (!existingLink && !acceptsIssue(config, issue.labels)) return "skipped";+const labels = issue.labels ?? [];const priority = extractIssuePriority(labels);const status = extractIssueStatus(labels);@@ -255,6 +258,16 @@ async function importSingleIssue(null,{ id: integrationId, projectId, project: { workspaceId } },async (tx) => {+ const binding = await tx.query.integrationTable.findFirst({+ where: eq(integrationTable.id, integrationId),+ });+ if (+ !binding ||+ binding.config !== JSON.stringify(config) ||+ !acceptsIssue(binding.config, issue.labels) ||+ (await findExternalLink(integrationId, "issue", String(issue.iid), tx))+ )+ return null;const number = await claimTaskNumber(projectId, tx);const taskValues: typeof taskTable.$inferInsert = {diff --git a/apps/api/src/gitlab-integration/index.ts b/apps/api/src/gitlab-integration/index.tsindex 851a75d61..1152716ac 100644--- a/apps/api/src/gitlab-integration/index.ts+++ b/apps/api/src/gitlab-integration/index.ts@@ -2,6 +2,7 @@ import { and, eq } from "drizzle-orm";import type { Context } from "hono";import { HTTPException } from "hono/http-exception";import db from "../database";+import { publishEvent } from "../events";import { integrationTable } from "../database/schema";import { scopeToProjectFromBody } from "../integrations/middleware";import { projectIdBody, projectIdParam } from "../integrations/schema";@@ -269,6 +270,11 @@ const gitlabIntegration = apiRouter<BaseVariables & { workspaceId: string }>()if (!integration) {throw new HTTPException(500, { message: "Failed to load integration" });}+ if (integration)+ await publishEvent("integration.sync_rules_changed", {+ projectId,+ integrationId: integration.id,+ });return c.json(integration, 200);}).openapi(updateIntegrationRoute, async (c) => {@@ -326,6 +332,12 @@ const gitlabIntegration = apiRouter<BaseVariables & { workspaceId: string }>()if (!updated) {throw new HTTPException(500, { message: "Failed to load integration" });}+ if (body.isActive === true && !row.isActive)+ await publishEvent("integration.sync_rules_changed", {+ projectId,+ integrationId: row.id,+ });+ await publishEvent("project.updated", { projectId });return c.json(updated, 200);}).openapi(deleteIntegrationRoute, async (c) => {diff --git a/apps/api/src/index.ts b/apps/api/src/index.tsindex 5933e6ad7..da70740a4 100644--- a/apps/api/src/index.ts+++ b/apps/api/src/index.ts@@ -1,3 +1,4 @@+import integrationSync from "./integration-sync";import { syncWorkspaceAccess } from "./ws/workspace-access";import { drainPasswordResetDeliveries } from "./utils/password-reset-delivery";import "./instrument";@@ -748,6 +749,7 @@ export function createApp() {notificationPreferences,);const searchApi = api.route("/search", search);+ const integrationSyncApi = api.route("/integration-sync", integrationSync);const githubIntegrationApi = api.route("/github-integration",githubIntegration,@@ -884,6 +886,7 @@ export function createApp() {discordIntegrationApi,externalLinkApi,genericWebhookIntegrationApi,+ integrationSyncApi,githubIntegrationApi,giteaIntegrationApi,gitlabIntegrationApi,@@ -1014,6 +1017,7 @@ const {discordIntegrationApi,externalLinkApi,genericWebhookIntegrationApi,+ integrationSyncApi,githubIntegrationApi,giteaIntegrationApi,gitlabIntegrationApi,@@ -1064,6 +1068,7 @@ export type AppType =| typeof notificationApi| typeof notificationPreferencesApi| typeof searchApi+ | typeof integrationSyncApi| typeof githubIntegrationApi| typeof giteaIntegrationApi| typeof gitlabIntegrationApidiff --git a/apps/api/src/integration-sync/controllers/get-integration.ts b/apps/api/src/integration-sync/controllers/get-integration.tsnew file mode 100644index 000000000..f800fef71--- /dev/null+++ b/apps/api/src/integration-sync/controllers/get-integration.ts@@ -0,0 +1,22 @@+import { and, eq } from "drizzle-orm";+import { HTTPException } from "hono/http-exception";+import db from "../../database";+import { integrationTable } from "../../database/schema";+import { readSyncRules } from "../../plugins/sync/rules";++export async function getSyncIntegration(projectId: string, provider: string) {+ const integration = await db.query.integrationTable.findFirst({+ where: and(+ eq(integrationTable.projectId, projectId),+ eq(integrationTable.type, provider),+ ),+ with: { project: true },+ });+ if (!integration)+ throw new HTTPException(404, { message: "Integration not found" });+ if (!readSyncRules(integration.config))+ throw new HTTPException(409, {+ message: "Invalid sync rules; repair the integration configuration",+ });+ return integration;+}diff --git a/apps/api/src/integration-sync/controllers/preview-rules.ts b/apps/api/src/integration-sync/controllers/preview-rules.tsnew file mode 100644index 000000000..48aaa0ada--- /dev/null+++ b/apps/api/src/integration-sync/controllers/preview-rules.ts@@ -0,0 +1,125 @@+import { createHash } from "node:crypto";+import { and, asc, desc, eq, inArray, sql } from "drizzle-orm";+import db from "../../database";+import { externalLinkTable, taskTable } from "../../database/schema";+import type { IntegrationDatabase } from "../../plugins/github/services/integration-task-scope";+import { outgoingPredicate } from "../../plugins/sync/task-predicate";+import { readSyncRules, type SyncRules } from "../../plugins/sync/rules";+import type { getSyncIntegration } from "./get-integration";++export async function previewSyncRules(+ integration: Awaited<ReturnType<typeof getSyncIntegration>>,+ rules: SyncRules,+ database: IntegrationDatabase = db,+ after?: string,+) {+ const proposed = await outgoingPredicate(+ integration.project.workspaceId,+ rules.outgoing,+ database,+ );+ const current = await outgoingPredicate(+ integration.project.workspaceId,+ readSyncRules(integration.config)!.outgoing,+ database,+ );+ const rows = await database+ .selectDistinctOn([taskTable.id], {+ id: taskTable.id,+ eligible: proposed.predicate,+ current: current.predicate,+ linkId: externalLinkTable.id,+ url: externalLinkTable.url,+ paused: sql<boolean>`coalesce(${externalLinkTable.metadata} ~ '"syncFilterPaused"[[:space:]]*:[[:space:]]*true', false)`,+ })+ .from(taskTable)+ .leftJoin(+ externalLinkTable,+ and(+ eq(externalLinkTable.taskId, taskTable.id),+ eq(externalLinkTable.integrationId, integration.id),+ eq(externalLinkTable.resourceType, "issue"),+ ),+ )+ .where(eq(taskTable.projectId, integration.projectId))+ .orderBy(+ asc(taskTable.id),+ desc(+ sql`coalesce(${externalLinkTable.metadata} ~ '"syncFilterPaused"[[:space:]]*:[[:space:]]*true', false)`,+ ),+ asc(externalLinkTable.id),+ );+ const matching = rows.filter((row) => row.eligible);+ const paused = rows.filter(+ (row) => row.linkId && (!row.eligible || row.paused),+ );+ const pausedPage = paused+ .filter((row) => !after || row.id > after)+ .slice(0, 26);+ const sampled = [+ ...new Set(+ [...matching.slice(0, 10), ...pausedPage.slice(0, 25)].map(+ (row) => row.id,+ ),+ ),+ ];+ const tasks = sampled.length+ ? await database+ .select({+ id: taskTable.id,+ number: taskTable.number,+ title: taskTable.title,+ })+ .from(taskTable)+ .where(+ and(+ eq(taskTable.projectId, integration.projectId),+ inArray(taskTable.id, sampled),+ ),+ )+ : [];+ const samples = new Map(tasks.map((task) => [task.id, task]));+ const previewToken = createHash("sha256")+ .update(+ JSON.stringify({+ integration: [integration.id, integration.config, integration.isActive],+ rules,+ labels: proposed.labels,+ rows,+ }),+ )+ .digest("hex");+ return {+ isActive: integration.isActive === true,+ rules,+ labels: proposed.labels,+ missingLabels: proposed.missing,+ total: new Set(rows.map((row) => row.id)).size,+ matching: matching.length,+ willCreate: matching.filter((row) => !row.linkId).length,+ willPause: rows.filter((row) => row.linkId && !row.eligible && !row.paused)+ .length,+ needsReview: rows.filter(+ (row) => row.linkId && row.eligible && (row.paused || !row.current),+ ).length,+ paused: paused.length,+ matchingTasks: matching+ .slice(0, 10)+ .flatMap((row) => samples.get(row.id) ?? []),+ pausedNextCursor: pausedPage.length > 25 ? pausedPage[24]!.id : null,+ pausedTasks: pausedPage.slice(0, 25).flatMap((row) => {+ const task = samples.get(row.id);+ return task && row.linkId && row.url+ ? [+ {+ ...task,+ linkId: row.linkId,+ url: row.url,+ eligible: row.eligible,+ },+ ]+ : [];+ }),+ previewToken,+ };+}diff --git a/apps/api/src/integration-sync/controllers/resume-sync.ts b/apps/api/src/integration-sync/controllers/resume-sync.tsnew file mode 100644index 000000000..e546960ba--- /dev/null+++ b/apps/api/src/integration-sync/controllers/resume-sync.ts@@ -0,0 +1,218 @@+import { randomUUID } from "node:crypto";+import { and, asc, eq, sql } from "drizzle-orm";+import { HTTPException } from "hono/http-exception";+import db from "../../database";+import {+ columnTable,+ externalLinkTable,+ integrationTable,+ taskTable,+} from "../../database/schema";+import { publishEvent } from "../../events";+import { updateExternalLink } from "../../plugins/github/services/link-manager";+import { parseDeferredIssueEdit } from "../../plugins/github/utils/deferred-issue-edit";+import {+ inboundStamp,+ type SyncStamp,+} from "../../plugins/github/utils/sync-echo";+import { formatIssueBody } from "../../plugins/github/utils/format";+import { taskMatchesRule } from "../../plugins/sync/eligibility";+import { readSyncRules } from "../../plugins/sync/rules";+import { reviewSyncResume } from "./review-resume";++// A resume lease performs fresh reads and a nested commit using the pool.+// Queue concurrent requests locally to leave connections available for them.+let resumeQueue: Promise<void> = Promise.resolve();+export async function resumeSync(+ projectId: string,+ provider: string,+ linkId: string,+ token: string,+ source: "kaneo" | "provider",+) {+ const next = resumeQueue.then(() =>+ resumeWithLease(projectId, provider, linkId, token, source),+ );+ resumeQueue = next.then(+ () => {},+ () => {},+ );+ return next;+}++async function resumeWithLease(+ projectId: string,+ provider: string,+ linkId: string,+ token: string,+ source: "kaneo" | "provider",+) {+ await db.transaction(async (lease) => {+ const result = await lease.execute<{ locked: boolean }>(+ sql`select pg_try_advisory_xact_lock(hashtextextended(${`sync-resume:${linkId}`}, 0)) as locked`,+ );+ if (!result.rows[0]?.locked)+ throw new HTTPException(409, {+ message: "This task is already being resumed",+ });+ const review = await reviewSyncResume(projectId, provider, linkId);+ if (review.token !== token)+ throw new HTTPException(409, {+ message: "Task or issue changed; review the comparison again",+ });+ let updatedAt: string | null = null;+ if (source === "kaneo") {+ try {+ updatedAt = (await review.access.write(review.local)).updatedAt;+ } catch {+ throw new HTTPException(502, {+ message: "External issue could not be updated; sync remains paused",+ });+ }+ }+ await db.transaction(async (tx) => {+ const [binding] = await tx+ .select()+ .from(integrationTable)+ .where(+ and(+ eq(integrationTable.id, review.integration.id),+ eq(integrationTable.config, review.integration.config),+ eq(integrationTable.isActive, true),+ ),+ )+ .for("share");+ const [task] = await tx+ .select()+ .from(taskTable)+ .where(+ and(+ eq(taskTable.id, review.task.id),+ eq(taskTable.projectId, projectId),+ ),+ )+ .for("no key update");+ const [link] = await tx+ .select()+ .from(externalLinkTable)+ .where(+ and(+ eq(externalLinkTable.id, linkId),+ eq(externalLinkTable.integrationId, review.integration.id),+ eq(externalLinkTable.taskId, review.task.id),+ ),+ )+ .for("update");+ if (+ !binding ||+ !task ||+ !link ||+ task.updatedAt.getTime() !== review.task.updatedAt.getTime() ||+ link.metadata !== review.link.metadata ||+ !(await taskMatchesRule(+ task.id,+ projectId,+ readSyncRules(binding.config)!.outgoing,+ tx,+ ))+ )+ throw new HTTPException(409, {+ message: "Sync scope or task changed; review again before resuming",+ });+ 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",+ });+ await tx+ .update(taskTable)+ .set({+ title: review.remote.title,+ description: review.remote.description,+ status: target.slug,+ columnId: target.id,+ })+ .where(eq(taskTable.id, task.id));+ }+ const job = parseDeferredIssueEdit(+ JSON.parse(link.metadata ?? "{}").deferredIssueEdit,+ );+ for (const field of ["title", "description", "state"] as const) {+ await updateExternalLink(+ linkId,+ {+ ...(source === "kaneo" && provider !== "gitlab"+ ? {+ outbound: {+ field,+ value: review.local[field],+ intentId: randomUUID(),+ updatedAt: updatedAt ?? undefined,+ pending: false,+ },+ }+ : {}),+ ...(job ? { completeDeferredEdit: job.id } : {}),+ metadata: {+ syncFilterPaused: false,+ ...(provider === "gitlab"+ ? {+ lastOutboundStateSyncAt: Date.now(),+ lastSync: {+ title: {+ source: source === "kaneo" ? "kaneo" : "gitlab",+ value:+ review[source === "kaneo" ? "local" : "remote"].title,+ timestamp: new Date().toISOString(),+ },+ description: {+ source: source === "kaneo" ? "kaneo" : "gitlab",+ value:+ source === "kaneo"+ ? formatIssueBody(review.local.description, task.id)+ : review.remote.description,+ timestamp: new Date().toISOString(),+ },+ },+ }+ : {}),+ ...(source === "provider" && provider !== "gitlab"+ ? {+ lastSync: {+ [field]: inboundStamp(+ (+ JSON.parse(link.metadata ?? "{}").lastSync as+ | Record<string, SyncStamp>+ | undefined+ )?.[field],+ review.remote[field],+ provider,+ review.remoteIssueUpdatedAt ?? undefined,+ ),+ },+ }+ : {}),+ state: review[source === "kaneo" ? "local" : "remote"].state,+ },+ retireUncertainOutbound: field,+ },+ tx,+ );+ }+ });+ await publishEvent("task.updated", { projectId, taskId: review.task.id });+ await publishEvent("project.updated", { projectId });+ });+ return { success: true };+}diff --git a/apps/api/src/integration-sync/controllers/review-resume.ts b/apps/api/src/integration-sync/controllers/review-resume.tsnew file mode 100644index 000000000..9fed4128f--- /dev/null+++ b/apps/api/src/integration-sync/controllers/review-resume.ts@@ -0,0 +1,88 @@+import { createHash } from "node:crypto";+import { and, eq } from "drizzle-orm";+import { HTTPException } from "hono/http-exception";+import db from "../../database";+import { externalLinkTable, taskTable } from "../../database/schema";+import { isTaskInFinalState } from "../../plugins/github/services/task-service";+import { taskMatchesRule } from "../../plugins/sync/eligibility";+import { providerIssue } from "../../plugins/sync/provider-issue";+import { isSyncPaused, readSyncRules } from "../../plugins/sync/rules";+import { getSyncIntegration } from "./get-integration";++export async function reviewSyncResume(+ projectId: string,+ provider: string,+ linkId: string,+) {+ const integration = await getSyncIntegration(projectId, provider);+ const link = await db.query.externalLinkTable.findFirst({+ where: and(+ eq(externalLinkTable.id, linkId),+ eq(externalLinkTable.integrationId, integration.id),+ eq(externalLinkTable.resourceType, "issue"),+ ),+ });+ const task =+ link &&+ (await db.query.taskTable.findFirst({+ where: and(+ eq(taskTable.id, link.taskId),+ eq(taskTable.projectId, projectId),+ ),+ }));+ if (!link || !task)+ throw new HTTPException(404, { message: "Linked task not found" });+ if (+ !integration.isActive ||+ !isSyncPaused(link.metadata) ||+ !(await taskMatchesRule(+ task.id,+ projectId,+ readSyncRules(integration.config)!.outgoing,+ ))+ )+ throw new HTTPException(409, {+ message:+ "The task must match the current rule and be paused before resuming",+ });+ try {+ const access = await providerIssue(integration, link);+ const remoteIssue = await access.read();+ const local = {+ title: task.title,+ description: task.description ?? "",+ state: (await isTaskInFinalState(task))+ ? ("closed" as const)+ : ("open" as const),+ };+ const remote = {+ title: remoteIssue.title,+ description: remoteIssue.description,+ state: remoteIssue.state,+ };+ const token = createHash("sha256")+ .update(+ JSON.stringify({+ binding: [integration.id, integration.config],+ task,+ link,+ remoteIssue,+ }),+ )+ .digest("hex");+ return {+ integration,+ link,+ task,+ access,+ local,+ remote,+ remoteIssueUpdatedAt: remoteIssue.updatedAt,+ token,+ };+ } catch {+ throw new HTTPException(502, {+ message: "External issue could not be read; sync remains paused",+ });+ }+}diff --git a/apps/api/src/integration-sync/controllers/save-rules.ts b/apps/api/src/integration-sync/controllers/save-rules.tsnew file mode 100644index 000000000..ed4cd542e--- /dev/null+++ b/apps/api/src/integration-sync/controllers/save-rules.ts@@ -0,0 +1,94 @@+import { and, eq, not, or } from "drizzle-orm";+import { HTTPException } from "hono/http-exception";+import db from "../../database";+import {+ externalLinkTable,+ integrationTable,+ taskTable,+} from "../../database/schema";+import { publishEvent } from "../../events";+import { updateExternalLink } from "../../plugins/github/services/link-manager";+import { outgoingPredicate } from "../../plugins/sync/task-predicate";+import { readSyncRules, type SyncRules } from "../../plugins/sync/rules";+import { getSyncIntegration } from "./get-integration";+import { previewSyncRules } from "./preview-rules";++export async function saveSyncRules(+ projectId: string,+ provider: string,+ rules: SyncRules,+ previewToken: string,+) {+ const integration = await getSyncIntegration(projectId, provider);+ await db.transaction(async (tx) => {+ const [current] = await tx+ .select()+ .from(integrationTable)+ .where(+ and(+ eq(integrationTable.id, integration.id),+ eq(integrationTable.config, integration.config),+ ),+ )+ .for("update");+ if (!current)+ throw new HTTPException(409, {+ message: "Integration changed; preview again before saving",+ });+ const preview = await previewSyncRules(+ { ...integration, ...current },+ rules,+ tx,+ );+ if (preview.previewToken !== previewToken)+ throw new HTTPException(409, {+ message: "Sync impact changed; preview again before saving",+ });+ if (preview.missingLabels.length)+ throw new HTTPException(400, {+ message: "Select existing labels from this workspace",+ });+ const oldScope = await outgoingPredicate(+ integration.project.workspaceId,+ readSyncRules(current.config)!.outgoing,+ tx,+ );+ const nextScope = await outgoingPredicate(+ integration.project.workspaceId,+ rules.outgoing,+ tx,+ );+ const links = await tx+ .select({ id: externalLinkTable.id })+ .from(externalLinkTable)+ .innerJoin(taskTable, eq(taskTable.id, externalLinkTable.taskId))+ .where(+ and(+ eq(externalLinkTable.integrationId, integration.id),+ eq(externalLinkTable.resourceType, "issue"),+ eq(taskTable.projectId, projectId),+ or(not(oldScope.predicate), not(nextScope.predicate)),+ ),+ );+ for (const link of links)+ await updateExternalLink(+ link.id,+ { metadata: { syncFilterPaused: true } },+ tx,+ );+ const config = JSON.parse(current.config) as Record<string, unknown>;+ await tx+ .update(integrationTable)+ .set({+ config: JSON.stringify({ ...config, syncRules: rules }),+ updatedAt: new Date(),+ })+ .where(eq(integrationTable.id, integration.id));+ });+ await publishEvent("integration.sync_rules_changed", {+ projectId,+ integrationId: integration.id,+ });+ await publishEvent("project.updated", { projectId });+ return previewSyncRules(await getSyncIntegration(projectId, provider), rules);+}diff --git a/apps/api/src/integration-sync/index.ts b/apps/api/src/integration-sync/index.tsnew file mode 100644index 000000000..a321d36c1--- /dev/null+++ b/apps/api/src/integration-sync/index.ts@@ -0,0 +1,183 @@+import {+ apiRouter,+ createRoute,+ errorResponse,+ jsonResponse,+ z,+} from "../openapi";+import { readSyncRules } from "../plugins/sync/rules";+import { requireWorkspacePermission } from "../utils/require-workspace-permission";+import { workspaceAccess } from "../utils/workspace-access-middleware";+import { getSyncIntegration } from "./controllers/get-integration";+import { previewSyncRules } from "./controllers/preview-rules";+import { resumeSync } from "./controllers/resume-sync";+import { reviewSyncResume } from "./controllers/review-resume";+import { saveSyncRules } from "./controllers/save-rules";+import {+ resumeBody,+ resumeParams,+ resumePreviewSchema,+ rulesBody,+ saveRulesBody,+ syncParams,+ syncPreviewSchema,+} from "./schema";++const access = [workspaceAccess.fromProject("projectId")];+const manage = [+ ...access,+ requireWorkspacePermission({ workspace: ["manage_settings"] }),+];+const errors = {+ 400: errorResponse("Invalid rule or workspace label"),+ 403: errorResponse("No workspace access or required permission"),+ 404: errorResponse("Integration or linked task not found"),+ 409: errorResponse(+ "Configuration, impact or comparison changed; review again",+ ),+};+const path = "/project/{projectId}/{provider}";+const body = <T extends z.ZodType>(schema: T) => ({+ required: true as const,+ content: { "application/json": { schema } },+});++const getRoute = createRoute({+ method: "get",+ path,+ operationId: "getIntegrationSyncRules",+ tags: ["Integration sync"],+ summary: "Get sync rules and current task scope",+ description:+ "Workspace members can inspect saved rules. Rules remain active when advanced mode is hidden. Paused issue links are preserved; eligible paused tasks require review before resuming.",+ middleware: access,+ request: {+ params: syncParams,+ query: z.object({ after: z.string().optional() }),+ },+ responses: {+ 200: jsonResponse("Saved rules and scope", syncPreviewSchema),+ ...errors,+ },+});+const previewRoute = createRoute({+ method: "post",+ path: `${path}/preview`,+ operationId: "previewIntegrationSyncRules",+ tags: ["Integration sync"],+ summary: "Preview a sync rule change",+ description:+ "Returns matching tasks, new exports, paused links and a token bound to the current integration and impact. Outgoing labels are workspace label IDs; incoming labels are exact repository label names.",+ middleware: manage,+ request: { params: syncParams, body: body(rulesBody) },+ responses: {+ 200: jsonResponse("Proposed rule impact", syncPreviewSchema),+ ...errors,+ },+});+const saveRoute = createRoute({+ method: "patch",+ path,+ operationId: "saveIntegrationSyncRules",+ tags: ["Integration sync"],+ summary: "Apply a previewed sync rule",+ description:+ "Save shared integration rules only if the preview is still current. Excluded links are paused, never deleted. Newly matching unlinked tasks are exported through the integration event path. Paused links require explicit review to resume.",+ middleware: manage,+ request: { params: syncParams, body: body(saveRulesBody) },+ responses: {+ 200: jsonResponse("Saved rules and current scope", syncPreviewSchema),+ ...errors,+ },+});+const reviewRoute = createRoute({+ method: "get",+ path: `${path}/links/{linkId}/review`,+ operationId: "reviewIntegrationSyncResume",+ tags: ["Integration sync"],+ summary: "Compare a paused task with its external issue",+ middleware: manage,+ request: { params: resumeParams },+ responses: {+ 200: jsonResponse(+ "Current values and comparison token",+ resumePreviewSchema,+ ),+ ...errors,+ 502: errorResponse("External issue unavailable; sync remains paused"),+ },+});+const resumeRoute = createRoute({+ method: "post",+ path: `${path}/links/{linkId}/resume`,+ operationId: "resumeIntegrationSync",+ tags: ["Integration sync"],+ summary: "Resume a reviewed issue link",+ description:+ "Explicitly choose the current Kaneo or repository title, description and open/closed state. Existing links are reused; historical comments are not replayed. The task must still match its outgoing rule. A changed comparison requires another review.",+ middleware: [...manage, requireWorkspacePermission({ task: ["update"] })],+ request: { params: resumeParams, body: body(resumeBody) },+ responses: {+ 200: jsonResponse("Sync resumed", z.object({ success: z.boolean() })),+ ...errors,+ 502: errorResponse("External issue unavailable; sync remains paused"),+ },+});++export default apiRouter()+ .openapi(getRoute, async (c) => {+ const { projectId, provider } = c.req.valid("param");+ const integration = await getSyncIntegration(projectId, provider);+ return c.json(+ await previewSyncRules(+ integration,+ readSyncRules(integration.config)!,+ undefined,+ c.req.valid("query").after,+ ),+ 200,+ );+ })+ .openapi(previewRoute, async (c) => {+ const { projectId, provider } = c.req.valid("param");+ return c.json(+ await previewSyncRules(+ await getSyncIntegration(projectId, provider),+ c.req.valid("json").rules,+ ),+ 200,+ );+ })+ .openapi(saveRoute, async (c) => {+ const { projectId, provider } = c.req.valid("param");+ const { rules, previewToken } = c.req.valid("json");+ return c.json(+ await saveSyncRules(projectId, provider, rules, previewToken),+ 200,+ );+ })+ .openapi(reviewRoute, async (c) => {+ const { projectId, provider, linkId } = c.req.valid("param");+ const review = await reviewSyncResume(projectId, provider, linkId);+ return c.json(+ {+ task: {+ id: review.task.id,+ number: review.task.number,+ title: review.task.title,+ },+ local: review.local,+ remote: review.remote,+ token: review.token,+ },+ 200,+ );+ })+ .openapi(resumeRoute, async (c) => {+ const { projectId, provider, linkId } = c.req.valid("param");+ const { source, token } = c.req.valid("json");+ return c.json(+ await resumeSync(projectId, provider, linkId, token, source),+ 200,+ );+ });diff --git a/apps/api/src/integration-sync/schema.ts b/apps/api/src/integration-sync/schema.tsnew file mode 100644index 000000000..edc0d59a8--- /dev/null+++ b/apps/api/src/integration-sync/schema.ts@@ -0,0 +1,62 @@+import { z } from "../openapi";+import { syncProviders, syncRulesSchema } from "../plugins/sync/rules";++export const syncParams = z.object({+ projectId: z.string().min(1),+ provider: z.enum(syncProviders),+});+export const rulesBody = z.object({ rules: syncRulesSchema });+export const saveRulesBody = rulesBody.extend({+ previewToken: z.string().length(64),+});+export const resumeParams = syncParams.extend({ linkId: z.string().min(1) });+export const resumeBody = z.object({+ token: z.string().length(64),+ source: z.enum(["kaneo", "provider"]),+});++const taskSample = z.object({+ id: z.string(),+ number: z.number().nullable(),+ title: z.string(),+});+export const syncPreviewSchema = z+ .object({+ isActive: z.boolean(),+ rules: syncRulesSchema,+ labels: z.array(+ z.object({ id: z.string(), name: z.string(), color: z.string() }),+ ),+ missingLabels: z.array(z.string()),+ total: z.number(),+ matching: z.number(),+ willCreate: z.number(),+ willPause: z.number(),+ needsReview: z.number(),+ paused: z.number(),+ matchingTasks: z.array(taskSample),+ pausedNextCursor: z.string().nullable(),+ pausedTasks: z.array(+ taskSample.extend({+ linkId: z.string(),+ url: z.string(),+ eligible: z.boolean(),+ }),+ ),+ previewToken: z.string(),+ })+ .openapi("IntegrationSyncPreview");++const syncValues = z.object({+ title: z.string(),+ description: z.string(),+ state: z.enum(["open", "closed"]),+});+export const resumePreviewSchema = z+ .object({+ task: taskSample,+ local: syncValues,+ remote: syncValues,+ token: z.string(),+ })+ .openapi("IntegrationSyncResumePreview");diff --git a/apps/api/src/label/controllers/assign-label-to-task.ts b/apps/api/src/label/controllers/assign-label-to-task.tsindex 0db1b21f3..80eb7e947 100644--- a/apps/api/src/label/controllers/assign-label-to-task.ts+++ b/apps/api/src/label/controllers/assign-label-to-task.ts@@ -154,6 +154,15 @@ async function assignLabelToTask(id: string, taskId: string, userId: string) {});if (previousTaskId) {+ const previousTask = await db.query.taskTable.findFirst({+ where: eq(taskTable.id, previousTaskId),+ columns: { projectId: true },+ });+ if (previousTask)+ await publishEvent("task.labels_updated", {+ projectId: previousTask.projectId,+ taskId: previousTaskId,+ });removeLabelFromGitHub(previousTaskId, previousName).catch((error) => {console.error("Failed to remove label from GitHub:", error);});diff --git a/apps/api/src/label/controllers/delete-label.ts b/apps/api/src/label/controllers/delete-label.tsindex 32bbb19ab..d037b46bb 100644--- a/apps/api/src/label/controllers/delete-label.ts+++ b/apps/api/src/label/controllers/delete-label.ts@@ -97,6 +97,14 @@ async function deleteLabel(.returning();if (!root) throw new HTTPException(404, { message: "Label not found" });if (root.workspaceId) {+ const projects = await db+ .select({ id: projectTable.id })+ .from(projectTable)+ .where(eq(projectTable.workspaceId, root.workspaceId));+ for (const project of projects)+ await publishEvent("integration.sync_labels_changed", {+ projectId: project.id,+ });const predicate = and(eq(labelTable.workspaceId, root.workspaceId),eq(labelTable.name, root.name),diff --git a/apps/api/src/label/controllers/unassign-label-from-task.ts b/apps/api/src/label/controllers/unassign-label-from-task.tsindex 68b335e2d..9f6ea9e7e 100644--- a/apps/api/src/label/controllers/unassign-label-from-task.ts+++ b/apps/api/src/label/controllers/unassign-label-from-task.ts@@ -3,6 +3,8 @@ import { HTTPException } from "hono/http-exception";import db from "../../database";import { labelTable, projectTable, taskTable } from "../../database/schema";import { publishEvent } from "../../events";+import { removeLabelFromGitea } from "../../plugins/gitea/utils/sync-label-to-gitea";+import { removeLabelFromGitlab } from "../../plugins/gitlab/utils/sync-label-to-gitlab";import { removeLabelFromGitHub } from "../../plugins/github/utils/sync-label-to-github";async function unassignLabelFromTask(id: string, userId: string) {@@ -51,6 +53,12 @@ async function unassignLabelFromTask(id: string, userId: string) {}if (deletedLabel.taskId) {+ removeLabelFromGitea(deletedLabel.taskId, deletedLabel.name).catch(+ (error) => console.error("Failed to remove label from Gitea:", error),+ );+ removeLabelFromGitlab(deletedLabel.taskId, deletedLabel.name).catch(+ (error) => console.error("Failed to remove label from GitLab:", error),+ );removeLabelFromGitHub(deletedLabel.taskId, deletedLabel.name).catch((error) => {console.error("Failed to remove label from GitHub:", error);diff --git a/apps/api/src/label/controllers/update-label.ts b/apps/api/src/label/controllers/update-label.tsindex 0fdd74dec..fa6a4d4b6 100644--- a/apps/api/src/label/controllers/update-label.ts+++ b/apps/api/src/label/controllers/update-label.ts@@ -72,8 +72,10 @@ async function updateLabel(id: string, name: string, color: string) {);return { updatedLabel, projects };});- for (const { projectId } of result.projects)+ for (const { projectId } of result.projects) {await publishEvent("project.updated", { projectId });+ await publishEvent("integration.sync_labels_changed", { projectId });+ }return result.updatedLabel;}diff --git a/apps/api/src/plugins/gitea/config.ts b/apps/api/src/plugins/gitea/config.tsindex fef1155b1..2ee8ef790 100644--- a/apps/api/src/plugins/gitea/config.ts+++ b/apps/api/src/plugins/gitea/config.ts@@ -1,4 +1,5 @@import * as v from "valibot";+import { type SyncRules, syncRulesSchema } from "../sync/rules";import { branchPatterns } from "../github/config";export { branchPatterns };@@ -9,6 +10,9 @@ export const giteaConfigSchema = v.object({repositoryOwner: v.pipe(v.string(), v.trim(), v.nonEmpty()),repositoryName: v.pipe(v.string(), v.trim(), v.nonEmpty()),webhookSecret: v.optional(v.string()),+ syncRules: v.optional(+ v.custom<SyncRules>((value) => syncRulesSchema.safeParse(value).success),+ ),branchPattern: v.optional(v.string()),customBranchRegex: v.optional(v.string()),commentTaskLinkOnGiteaIssue: v.optional(v.boolean()),diff --git a/apps/api/src/plugins/gitea/events/task-comment-created.ts b/apps/api/src/plugins/gitea/events/task-comment-created.tsindex b5cf42f82..a162f3bdc 100644--- a/apps/api/src/plugins/gitea/events/task-comment-created.ts+++ b/apps/api/src/plugins/gitea/events/task-comment-created.ts@@ -1,3 +1,4 @@+import { canSyncTask } from "../../sync/eligibility";import { findExternalLinkByTaskAndType } from "../../github/services/link-manager";import type { PluginContext, TaskCommentCreatedEvent } from "../../types";import type { GiteaConfig } from "../config";@@ -8,6 +9,16 @@ export async function handleTaskCommentCreated(event: TaskCommentCreatedEvent,context: PluginContext,): Promise<void> {+ if (+ !(await canSyncTask(+ event.taskId,+ context.integrationId,+ undefined,+ JSON.stringify(context.config),+ ))+ )+ return;+const config = context.config as GiteaConfig;if (!config.baseUrl || !config.accessToken) {return;diff --git a/apps/api/src/plugins/gitea/events/task-created.ts b/apps/api/src/plugins/gitea/events/task-created.tsindex 007901f55..32c697185 100644--- a/apps/api/src/plugins/gitea/events/task-created.ts+++ b/apps/api/src/plugins/gitea/events/task-created.ts@@ -1,18 +1,18 @@+import { taskIssueLabels } from "../../sync/issue-labels";+import { withTaskSyncCreation } from "../../sync/create-task-issue";import {createExternalLink,+ updateExternalLink,findExternalLinkByTaskAndType,} from "../../github/services/link-manager";-import {- formatIssueBody,- formatIssueTitle,- getLabelsForIssue,-} from "../../github/utils/format";+import { formatIssueBody, formatIssueTitle } from "../../github/utils/format";+import { isTaskInFinalState } from "../../github/services/task-service";import type { PluginContext, TaskCreatedEvent } from "../../types";import type { GiteaConfig } from "../config";import { createGiteaClient } from "../utils/gitea-api";import { addLabelsToIssueGitea } from "../utils/labels";-export async function handleTaskCreated(+async function createTaskIssue(event: TaskCreatedEvent,context: PluginContext,): Promise<void> {@@ -44,7 +44,7 @@ export async function handleTaskCreated(},);- await createExternalLink({+ const createdLink = await createExternalLink({taskId: event.taskId,integrationId: context.integrationId,resourceType: "issue",@@ -58,9 +58,40 @@ export async function handleTaskCreated(},});- const labels = getLabelsForIssue(event.priority, event.status);+ if (+ await isTaskInFinalState({+ projectId: event.projectId,+ status: event.status,+ columnId: null,+ })+ ) {+ await client.updateIssue(+ repositoryOwner,+ repositoryName,+ createdIssue.number,+ { state: "closed" },+ );+ await updateExternalLink(createdLink.id, {+ metadata: { state: "closed", lastOutboundStateSyncAt: Date.now() },+ });+ }++ const labels = await taskIssueLabels(+ event.taskId,+ event.priority,+ event.status,+ );await addLabelsToIssueGitea(config, createdIssue.number, labels);} catch (error) {console.error("Failed to create Gitea issue:", error);}}++export async function handleTaskCreated(+ event: TaskCreatedEvent,+ context: PluginContext,+): Promise<void> {+ await withTaskSyncCreation(event, context, (current) =>+ createTaskIssue(current, context),+ );+}diff --git a/apps/api/src/plugins/gitea/events/task-description-changed.ts b/apps/api/src/plugins/gitea/events/task-description-changed.tsindex 2d57d2ce6..2f117acfc 100644--- a/apps/api/src/plugins/gitea/events/task-description-changed.ts+++ b/apps/api/src/plugins/gitea/events/task-description-changed.ts@@ -1,3 +1,4 @@+import { canSyncTask } from "../../sync/eligibility";import { syncLatestTaskValue } from "../../github/services/sync-latest-task-value";import db from "../../../database";import { linkedTaskScope } from "../../github/services/integration-task-scope";@@ -23,6 +24,16 @@ export async function handleTaskDescriptionChanged(event: TaskDescriptionChangedEvent,context: PluginContext,): Promise<void> {+ if (+ !(await canSyncTask(+ event.taskId,+ context.integrationId,+ undefined,+ JSON.stringify(context.config),+ ))+ )+ return;+const config = context.config as GiteaConfig;if (!config.baseUrl || !config.accessToken) {return;diff --git a/apps/api/src/plugins/gitea/events/task-priority-changed.ts b/apps/api/src/plugins/gitea/events/task-priority-changed.tsindex c18e0caaa..946a71be1 100644--- a/apps/api/src/plugins/gitea/events/task-priority-changed.ts+++ b/apps/api/src/plugins/gitea/events/task-priority-changed.ts@@ -1,3 +1,4 @@+import { canSyncTask } from "../../sync/eligibility";import { findExternalLinksByTask } from "../../github/services/link-manager";import type { PluginContext, TaskPriorityChangedEvent } from "../../types";import type { GiteaConfig } from "../config";@@ -7,6 +8,16 @@ export async function handleTaskPriorityChanged(event: TaskPriorityChangedEvent,context: PluginContext,): Promise<void> {+ if (+ !(await canSyncTask(+ event.taskId,+ context.integrationId,+ undefined,+ JSON.stringify(context.config),+ ))+ )+ return;+const config = context.config as GiteaConfig;if (!config.baseUrl || !config.accessToken) {return;diff --git a/apps/api/src/plugins/gitea/events/task-status-changed.ts b/apps/api/src/plugins/gitea/events/task-status-changed.tsindex 46d8061cd..9f6b017c4 100644--- a/apps/api/src/plugins/gitea/events/task-status-changed.ts+++ b/apps/api/src/plugins/gitea/events/task-status-changed.ts@@ -1,3 +1,4 @@+import { canSyncTask } from "../../sync/eligibility";import { syncLatestTaskValue } from "../../github/services/sync-latest-task-value";import { findExternalLinksByTask } from "../../github/services/link-manager";import type { PluginContext, TaskStatusChangedEvent } from "../../types";@@ -9,6 +10,16 @@ export async function handleTaskStatusChanged(event: TaskStatusChangedEvent,context: PluginContext,): Promise<void> {+ if (+ !(await canSyncTask(+ event.taskId,+ context.integrationId,+ undefined,+ JSON.stringify(context.config),+ ))+ )+ return;+const config = context.config as GiteaConfig;if (!config.baseUrl || !config.accessToken) {return;diff --git a/apps/api/src/plugins/gitea/events/task-title-changed.ts b/apps/api/src/plugins/gitea/events/task-title-changed.tsindex ed850d78c..48ef50084 100644--- a/apps/api/src/plugins/gitea/events/task-title-changed.ts+++ b/apps/api/src/plugins/gitea/events/task-title-changed.ts@@ -1,3 +1,4 @@+import { canSyncTask } from "../../sync/eligibility";import { syncLatestTaskValue } from "../../github/services/sync-latest-task-value";import db from "../../../database";import { linkedTaskScope } from "../../github/services/integration-task-scope";@@ -19,6 +20,16 @@ export async function handleTaskTitleChanged(event: TaskTitleChangedEvent,context: PluginContext,): Promise<void> {+ if (+ !(await canSyncTask(+ event.taskId,+ context.integrationId,+ undefined,+ JSON.stringify(context.config),+ ))+ )+ return;+const config = context.config as GiteaConfig;if (!config.baseUrl || !config.accessToken) {return;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.tsindex 42d99846b..fe1af5133 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 { canSyncTask } from "../../sync/eligibility";import { eq } from "drizzle-orm";import db from "../../../database";import { externalLinkTable } from "../../../database/schema";@@ -66,6 +67,8 @@ async function getGiteaIssueContext(taskId: string) {return null;}+ if (!(await canSyncTask(taskId, integration.id))) return null;+let config: GiteaConfig;try {config = JSON.parse(integration.config) as GiteaConfig;diff --git a/apps/api/src/plugins/gitea/webhooks/issue-labeled.ts b/apps/api/src/plugins/gitea/webhooks/issue-labeled.tsindex db17fdf43..344097dee 100644--- a/apps/api/src/plugins/gitea/webhooks/issue-labeled.ts+++ b/apps/api/src/plugins/gitea/webhooks/issue-labeled.ts@@ -1,3 +1,5 @@+import { acceptsIssue, readSyncRules } from "../../sync/rules";+import { handleGiteaIssueOpened } from "./issue-opened";import { withIntegrationLink } from "../../github/services/with-integration-link";import {type IntegrationDatabase,@@ -143,6 +145,20 @@ export async function handleGiteaIssueLabeled();if (!existingLink) {+ const fullIssue = issue as typeof issue &+ Partial<Parameters<typeof handleGiteaIssueOpened>[0]["issue"]>;+ if (+ ["label_updated", "labeled"].includes(payload.action) &&+ readSyncRules(integration.config)?.incoming.mode === "labels" &&+ acceptsIssue(integration.config, issue.labels) &&+ fullIssue.title &&+ fullIssue.html_url+ ) {+ await handleGiteaIssueOpened(+ payload as Parameters<typeof handleGiteaIssueOpened>[0],+ integration.id,+ );+ }continue;}diff --git a/apps/api/src/plugins/gitea/webhooks/issue-opened.ts b/apps/api/src/plugins/gitea/webhooks/issue-opened.tsindex f6774c26e..352bf5cca 100644--- a/apps/api/src/plugins/gitea/webhooks/issue-opened.ts+++ b/apps/api/src/plugins/gitea/webhooks/issue-opened.ts@@ -1,6 +1,13 @@+import { acceptsIssue } from "../../sync/rules";+import { importIssueLabels } from "../../sync/issue-labels";import { and, eq } from "drizzle-orm";import db from "../../../database";-import { columnTable, projectTable, taskTable } from "../../../database/schema";+import {+ columnTable,+ integrationTable,+ projectTable,+ taskTable,+} from "../../../database/schema";import { publishEvent } from "../../../events";import { claimTaskNumber } from "../../../task/controllers/claim-task-numbers";import {@@ -64,6 +71,7 @@ export async function handleGiteaIssueOpened(}for (const integration of integrations) {+ if (!acceptsIssue(integration.config, issue.labels)) continue;let config: GiteaConfig;try {config = JSON.parse(integration.config) as GiteaConfig;@@ -79,67 +87,81 @@ export async function handleGiteaIssueOpened(const priority = extractIssuePriority(issue.labels);const status = extractIssueStatus(issue.labels);- const existingLink = await findExternalLink(- integration.id,- "issue",- issue.number.toString(),- );-- if (existingLink) {- continue;- }-- const nextTaskNumber = await claimTaskNumber(projectId);-- const resolvedStatus = await resolveTargetStatus(- projectId,- "issue_opened",- status || "to-do",- );-- const targetColumn = await db.query.columnTable.findFirst({- where: and(- eq(columnTable.projectId, projectId),- eq(columnTable.slug, resolvedStatus),- ),- });-- const taskValues: typeof taskTable.$inferInsert = {- projectId,- userId: null,- title: issue.title,- description: formatTaskDescriptionFromIssue(issue.body),- status: resolvedStatus,- columnId: targetColumn?.id ?? null,- priority: priority ?? "low",- number: nextTaskNumber,- };-- const [createdTask] = await db- .insert(taskTable)- .values(taskValues)- .returning();-- if (!createdTask) {- console.error("Failed to create task from Gitea issue");- continue;- }-- // Must run before task.created: the plugin's onTaskCreated uses link- // existence to skip self-originated tasks, else it duplicates the issue.- await createExternalLink({- taskId: createdTask.id,- integrationId: integration.id,- resourceType: "issue",- externalId: issue.number.toString(),- url: issue.html_url,- title: issue.title,- metadata: {+ const result = await db.transaction(async (tx) => {+ const [current] = await tx+ .select()+ .from(integrationTable)+ .where(eq(integrationTable.id, integration.id))+ .for("update");+ if (+ !current?.isActive ||+ current.config !== integration.config ||+ !acceptsIssue(current.config, issue.labels)+ )+ return null;+ if (+ await findExternalLink(+ integration.id,+ "issue",+ String(issue.number),+ tx,+ )+ )+ return null;+ const resolvedStatus = await resolveTargetStatus(+ projectId,+ "issue_opened",+ status || "to-do",+ tx,+ );+ const targetColumn = await tx.query.columnTable.findFirst({+ where: and(+ eq(columnTable.projectId, projectId),+ eq(columnTable.slug, resolvedStatus),+ ),+ });+ const nextTaskNumber = await claimTaskNumber(projectId, tx);+ const [task] = await tx+ .insert(taskTable)+ .values({+ projectId,+ userId: null,+ title: issue.title,+ description: formatTaskDescriptionFromIssue(issue.body),+ status: resolvedStatus,+ columnId: targetColumn?.id ?? null,+ priority: priority ?? "low",+ number: nextTaskNumber,+ })+ .returning();+ if (!task) throw new Error("Failed to create task from gitea issue");+ const linkMetadata = {state: "open",createdFrom: "gitea",author: issue.user?.login ?? issue.user?.username,- },+ };+ const link = await createExternalLink(+ {+ taskId: task.id,+ integrationId: integration.id,+ resourceType: "issue",+ externalId: String(issue.number),+ url: issue.html_url,+ title: issue.title,+ metadata: linkMetadata,+ },+ tx,+ );+ await importIssueLabels(+ task.id,+ integration.project.workspaceId,+ issue.labels,+ tx,+ );+ return { task, link, linkMetadata };});+ if (!result) continue;+ const { task: createdTask } = result;await publishEvent("task.created", {...createdTask,diff --git a/apps/api/src/plugins/github/config.ts b/apps/api/src/plugins/github/config.tsindex 476f0b30b..a12d980e4 100644--- a/apps/api/src/plugins/github/config.ts+++ b/apps/api/src/plugins/github/config.ts@@ -1,4 +1,5 @@import * as v from "valibot";+import { type SyncRules, syncRulesSchema } from "../sync/rules";export const branchPatterns = ["{slug}-{number}",@@ -20,6 +21,9 @@ export const githubConfigSchema = v.object({repositoryId: v.optional(v.number()),verifiedGithubAccountId: v.optional(v.string()),verifiedByUserId: v.optional(v.string()),+ syncRules: v.optional(+ v.custom<SyncRules>((value) => syncRulesSchema.safeParse(value).success),+ ),branchPattern: v.optional(v.string()),customBranchRegex: v.optional(v.string()),commentTaskLinkOnGitHubIssue: v.optional(v.boolean()),diff --git a/apps/api/src/plugins/github/events/task-comment-created.ts b/apps/api/src/plugins/github/events/task-comment-created.tsindex e5f38bc0e..3f5da7497 100644--- a/apps/api/src/plugins/github/events/task-comment-created.ts+++ b/apps/api/src/plugins/github/events/task-comment-created.ts@@ -1,3 +1,4 @@+import { canSyncTask } from "../../sync/eligibility";import type { PluginContext, TaskCommentCreatedEvent } from "../../types";import { type GitHubConfig, hasVerifiedGitHubBinding } from "../config";import { findExternalLinkByTaskAndType } from "../services/link-manager";@@ -10,6 +11,16 @@ export async function handleTaskCommentCreated(event: TaskCommentCreatedEvent,context: PluginContext,): Promise<void> {+ if (+ !(await canSyncTask(+ event.taskId,+ context.integrationId,+ undefined,+ JSON.stringify(context.config),+ ))+ )+ return;+const githubApp = getGithubApp();if (!githubApp) {return;diff --git a/apps/api/src/plugins/github/events/task-created.ts b/apps/api/src/plugins/github/events/task-created.tsindex 86149a961..3486ee3a2 100644--- a/apps/api/src/plugins/github/events/task-created.ts+++ b/apps/api/src/plugins/github/events/task-created.ts@@ -1,24 +1,24 @@+import { taskIssueLabels } from "../../sync/issue-labels";+import { withTaskSyncCreation } from "../../sync/create-task-issue";import { eq } from "drizzle-orm";import db from "../../../database";import { projectTable } from "../../../database/schema";+import { isTaskInFinalState } from "../services/task-service";import type { PluginContext, TaskCreatedEvent } from "../../types";import { type GitHubConfig, hasVerifiedGitHubBinding } from "../config";import {createExternalLink,+ updateExternalLink,findExternalLinkByTaskAndType,} from "../services/link-manager";-import {- formatIssueBody,- formatIssueTitle,- getLabelsForIssue,-} from "../utils/format";+import { formatIssueBody, formatIssueTitle } from "../utils/format";import {getGithubApp,getVerifiedInstallationOctokit,} from "../utils/github-app";import { addLabelsToIssue } from "../utils/labels";-export async function handleTaskCreated(+async function createTaskIssue(event: TaskCreatedEvent,context: PluginContext,): Promise<void> {@@ -51,16 +51,7 @@ export async function handleTaskCreated(body: formatIssueBody(event.description, event.taskId),});- const labels = getLabelsForIssue(event.priority, event.status);- await addLabelsToIssue(- octokit,- repositoryOwner,- repositoryName,- createdIssue.data.number,- labels,- );-- await createExternalLink({+ const createdLink = await createExternalLink({taskId: event.taskId,integrationId: context.integrationId,resourceType: "issue",@@ -73,6 +64,37 @@ export async function handleTaskCreated(},});+ if (+ await isTaskInFinalState({+ projectId: event.projectId,+ status: event.status,+ columnId: null,+ })+ ) {+ await octokit.rest.issues.update({+ owner: repositoryOwner,+ repo: repositoryName,+ issue_number: createdIssue.data.number,+ state: "closed",+ });+ await updateExternalLink(createdLink.id, {+ metadata: { state: "closed", lastOutboundStateSyncAt: Date.now() },+ });+ }++ const labels = await taskIssueLabels(+ event.taskId,+ event.priority,+ event.status,+ );+ await addLabelsToIssue(+ octokit,+ repositoryOwner,+ repositoryName,+ createdIssue.data.number,+ labels,+ );+if (config.commentTaskLinkOnGitHubIssue !== false) {const project = await db.query.projectTable.findFirst({where: eq(projectTable.id, event.projectId),@@ -96,3 +118,12 @@ export async function handleTaskCreated(console.error("Failed to create GitHub issue:", error);}}++export async function handleTaskCreated(+ event: TaskCreatedEvent,+ context: PluginContext,+): Promise<void> {+ await withTaskSyncCreation(event, context, (current) =>+ createTaskIssue(current, context),+ );+}diff --git a/apps/api/src/plugins/github/events/task-description-changed.ts b/apps/api/src/plugins/github/events/task-description-changed.tsindex 5ded46218..1158443bb 100644--- a/apps/api/src/plugins/github/events/task-description-changed.ts+++ b/apps/api/src/plugins/github/events/task-description-changed.ts@@ -1,3 +1,4 @@+import { canSyncTask } from "../../sync/eligibility";import { syncLatestTaskValue } from "../services/sync-latest-task-value";import db from "../../../database";import { linkedTaskScope } from "../services/integration-task-scope";@@ -17,6 +18,16 @@ export async function handleTaskDescriptionChanged(event: TaskDescriptionChangedEvent,context: PluginContext,): Promise<void> {+ if (+ !(await canSyncTask(+ event.taskId,+ context.integrationId,+ undefined,+ JSON.stringify(context.config),+ ))+ )+ return;+const githubApp = getGithubApp();if (!githubApp) {return;diff --git a/apps/api/src/plugins/github/events/task-priority-changed.ts b/apps/api/src/plugins/github/events/task-priority-changed.tsindex 444080233..904d249be 100644--- a/apps/api/src/plugins/github/events/task-priority-changed.ts+++ b/apps/api/src/plugins/github/events/task-priority-changed.ts@@ -1,3 +1,4 @@+import { canSyncTask } from "../../sync/eligibility";import type { PluginContext, TaskPriorityChangedEvent } from "../../types";import { type GitHubConfig, hasVerifiedGitHubBinding } from "../config";import { findExternalLinksByTask } from "../services/link-manager";@@ -11,6 +12,16 @@ export async function handleTaskPriorityChanged(event: TaskPriorityChangedEvent,context: PluginContext,): Promise<void> {+ if (+ !(await canSyncTask(+ event.taskId,+ context.integrationId,+ undefined,+ JSON.stringify(context.config),+ ))+ )+ return;+const githubApp = getGithubApp();if (!githubApp) {return;diff --git a/apps/api/src/plugins/github/events/task-status-changed.ts b/apps/api/src/plugins/github/events/task-status-changed.tsindex 7962f057a..7e9a773c4 100644--- a/apps/api/src/plugins/github/events/task-status-changed.ts+++ b/apps/api/src/plugins/github/events/task-status-changed.ts@@ -1,3 +1,4 @@+import { canSyncTask } from "../../sync/eligibility";import { syncLatestTaskValue } from "../services/sync-latest-task-value";import type { PluginContext, TaskStatusChangedEvent } from "../../types";import { type GitHubConfig, hasVerifiedGitHubBinding } from "../config";@@ -12,6 +13,16 @@ export async function handleTaskStatusChanged(event: TaskStatusChangedEvent,context: PluginContext,): Promise<void> {+ if (+ !(await canSyncTask(+ event.taskId,+ context.integrationId,+ undefined,+ JSON.stringify(context.config),+ ))+ )+ return;+const githubApp = getGithubApp();if (!githubApp) {return;diff --git a/apps/api/src/plugins/github/events/task-title-changed.ts b/apps/api/src/plugins/github/events/task-title-changed.tsindex 6140bed03..e3af06901 100644--- a/apps/api/src/plugins/github/events/task-title-changed.ts+++ b/apps/api/src/plugins/github/events/task-title-changed.ts@@ -1,3 +1,4 @@+import { canSyncTask } from "../../sync/eligibility";import { syncLatestTaskValue } from "../services/sync-latest-task-value";import db from "../../../database";import { linkedTaskScope } from "../services/integration-task-scope";@@ -13,6 +14,16 @@ export async function handleTaskTitleChanged(event: TaskTitleChangedEvent,context: PluginContext,): Promise<void> {+ if (+ !(await canSyncTask(+ event.taskId,+ context.integrationId,+ undefined,+ JSON.stringify(context.config),+ ))+ )+ return;+const githubApp = getGithubApp();if (!githubApp) {return;diff --git a/apps/api/src/plugins/github/services/deferred-issue-edits.ts b/apps/api/src/plugins/github/services/deferred-issue-edits.tsindex 034017c16..cd1253808 100644--- a/apps/api/src/plugins/github/services/deferred-issue-edits.ts+++ b/apps/api/src/plugins/github/services/deferred-issue-edits.ts@@ -1,3 +1,4 @@+import { canSyncTask } from "../../sync/eligibility";import { and, asc, gt, sql } from "drizzle-orm";import db from "../../../database";import { externalLinkTable } from "../../../database/schema";@@ -144,6 +145,15 @@ async function replayClaimedIssueEdits() {await updateExternalLink(link.id, { completeDeferredEdit: job.id });continue;}+ if (+ !(await canSyncTask(+ link.taskId,+ integration.id,+ undefined,+ integration.config,+ ))+ )+ continue;const fields = [...new Set([...job.fields, ...(job.repairFields ?? [])]),];diff --git a/apps/api/src/plugins/github/services/integration-task-scope.ts b/apps/api/src/plugins/github/services/integration-task-scope.tsindex 005428e91..f70a386fa 100644--- a/apps/api/src/plugins/github/services/integration-task-scope.ts+++ b/apps/api/src/plugins/github/services/integration-task-scope.ts@@ -1,3 +1,4 @@+import { canSyncTask } from "../../sync/eligibility";import { and, eq, sql } from "drizzle-orm";import db from "../../../database";import {@@ -33,6 +34,19 @@ export async function withIntegrationTask<T>(): Promise<T | undefined> {const effects: Array<() => Promise<void>> = [];const result = await db.transaction(async (tx) => {+ if (taskId === null) {+ const [binding] = await tx+ .select({ id: integrationTable.id })+ .from(integrationTable)+ .where(+ and(+ eq(integrationTable.id, integration.id),+ eq(integrationTable.isActive, true),+ ),+ )+ .for("no key update");+ if (!binding) return undefined;+ }const [project] = await tx.select({ id: projectTable.id }).from(projectTable)@@ -89,6 +103,15 @@ 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/sync-latest-task-value.ts b/apps/api/src/plugins/github/services/sync-latest-task-value.tsindex 1ce89a6f7..0e65f6766 100644--- a/apps/api/src/plugins/github/services/sync-latest-task-value.ts+++ b/apps/api/src/plugins/github/services/sync-latest-task-value.ts@@ -1,3 +1,4 @@+import { canSyncTask } from "../../sync/eligibility";import { deferTaskSync } from "./defer-issue-edit";import { randomUUID } from "node:crypto";import db from "../../../database";@@ -57,6 +58,15 @@ export async function syncLatestTaskValue(});return;}+ if (+ !(await canSyncTask(+ taskId,+ link.integrationId ?? "",+ undefined,+ identity?.config,+ ))+ )+ return;return binding;};for (;;) {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.tsindex 90734f3f7..0e5ef9236 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 { canSyncTask } from "../../sync/eligibility";import { eq } from "drizzle-orm";import db from "../../../database";import { externalLinkTable } from "../../../database/schema";@@ -61,6 +62,8 @@ async function getGitHubContext(taskId: string) {return null;}+ if (!(await canSyncTask(taskId, integration.id))) return null;+let config: GitHubConfig;try {config = JSON.parse(integration.config);diff --git a/apps/api/src/plugins/github/webhooks/issue-labeled.ts b/apps/api/src/plugins/github/webhooks/issue-labeled.tsindex c8a664550..34085dfd5 100644--- a/apps/api/src/plugins/github/webhooks/issue-labeled.ts+++ b/apps/api/src/plugins/github/webhooks/issue-labeled.ts@@ -1,3 +1,5 @@+import { acceptsIssue, readSyncRules } from "../../sync/rules";+import { handleIssueOpened } from "./issue-opened";import { withIntegrationLink } from "../services/with-integration-link";import { linkedTaskScope } from "../services/integration-task-scope";import { eq } from "drizzle-orm";@@ -44,6 +46,20 @@ export async function handleIssueLabeled(payload: IssueLabeledPayload) {);if (!existingLink) {+ const fullIssue = issue as typeof issue &+ Partial<Parameters<typeof handleIssueOpened>[0]["issue"]>;+ if (+ payload.action === "labeled" &&+ readSyncRules(integration.config)?.incoming.mode === "labels" &&+ acceptsIssue(integration.config, issue.labels) &&+ fullIssue.title &&+ fullIssue.html_url+ ) {+ await handleIssueOpened(+ payload as Parameters<typeof handleIssueOpened>[0],+ integration.id,+ );+ }continue;}diff --git a/apps/api/src/plugins/github/webhooks/issue-opened.ts b/apps/api/src/plugins/github/webhooks/issue-opened.tsindex 9051982bf..40bdbbec2 100644--- a/apps/api/src/plugins/github/webhooks/issue-opened.ts+++ b/apps/api/src/plugins/github/webhooks/issue-opened.ts@@ -1,3 +1,5 @@+import { acceptsIssue } from "../../sync/rules";+import { importIssueLabels } from "../../sync/issue-labels";import { and, eq } from "drizzle-orm";import db from "../../../database";import { publishEvent } from "../../../events";@@ -39,7 +41,10 @@ type IssueOpenedPayload = {};};-export async function handleIssueOpened(payload: IssueOpenedPayload) {+export async function handleIssueOpened(+ payload: IssueOpenedPayload,+ integrationId?: string,+) {const githubApp = getGithubApp();if (!githubApp) {return;@@ -55,13 +60,16 @@ export async function handleIssueOpened(payload: IssueOpenedPayload) {return;}- const integrations = await findAllIntegrationsByRepo(payload);+ const integrations = (await findAllIntegrationsByRepo(payload)).filter(+ (integration) => !integrationId || integration.id === integrationId,+ );if (integrations.length === 0) {return;}for (const integration of integrations) {+ if (!acceptsIssue(integration.config, issue.labels)) continue;const config = JSON.parse(integration.config) as GitHubConfig;const projectId = integration.projectId;@@ -128,6 +136,12 @@ export async function handleIssueOpened(payload: IssueOpenedPayload) {},tx,);+ await importIssueLabels(+ task.id,+ integration.project.workspaceId,+ issue.labels,+ tx,+ );return task;});if (!createdTask) continue;diff --git a/apps/api/src/plugins/gitlab/config.ts b/apps/api/src/plugins/gitlab/config.tsindex e817b8a4a..30bd389da 100644--- a/apps/api/src/plugins/gitlab/config.ts+++ b/apps/api/src/plugins/gitlab/config.ts@@ -1,4 +1,5 @@import * as v from "valibot";+import { type SyncRules, syncRulesSchema } from "../sync/rules";import { privateDestinationsAllowed } from "../../utils/assert-public-destination";import { branchPatterns } from "../github/config";@@ -10,6 +11,9 @@ export const gitlabConfigSchema = v.object({tokenType: v.optional(v.picklist(["private", "bearer"])),projectPath: v.pipe(v.string(), v.trim(), v.nonEmpty()),webhookSecret: v.optional(v.string()),+ syncRules: v.optional(+ v.custom<SyncRules>((value) => syncRulesSchema.safeParse(value).success),+ ),branchPattern: v.optional(v.string()),customBranchRegex: v.optional(v.string()),commentTaskLinkOnGitlabIssue: v.optional(v.boolean()),diff --git a/apps/api/src/plugins/gitlab/events/task-comment-created.ts b/apps/api/src/plugins/gitlab/events/task-comment-created.tsindex 44132406f..3e30d2c25 100644--- a/apps/api/src/plugins/gitlab/events/task-comment-created.ts+++ b/apps/api/src/plugins/gitlab/events/task-comment-created.ts@@ -1,3 +1,4 @@+import { canSyncTask } from "../../sync/eligibility";import {findExternalLinkByTaskAndType,updateExternalLink,@@ -12,6 +13,16 @@ export async function handleTaskCommentCreated(event: TaskCommentCreatedEvent,context: PluginContext,): Promise<void> {+ if (+ !(await canSyncTask(+ event.taskId,+ context.integrationId,+ undefined,+ JSON.stringify(context.config),+ ))+ )+ return;+const config = context.config as GitlabConfig;if (!config.baseUrl || !config.accessToken) {return;diff --git a/apps/api/src/plugins/gitlab/events/task-created.ts b/apps/api/src/plugins/gitlab/events/task-created.tsindex 01550df25..2898afb0a 100644--- a/apps/api/src/plugins/gitlab/events/task-created.ts+++ b/apps/api/src/plugins/gitlab/events/task-created.ts@@ -1,18 +1,18 @@+import { taskIssueLabels } from "../../sync/issue-labels";+import { withTaskSyncCreation } from "../../sync/create-task-issue";import {createExternalLink,+ updateExternalLink,findExternalLinkByTaskAndType,} from "../../github/services/link-manager";-import {- formatIssueBody,- formatIssueTitle,- getLabelsForIssue,-} from "../../github/utils/format";+import { formatIssueBody, formatIssueTitle } from "../../github/utils/format";+import { isTaskInFinalState } from "../../github/services/task-service";import type { PluginContext, TaskCreatedEvent } from "../../types";import type { GitlabConfig } from "../config";import { createGitlabClient } from "../utils/gitlab-api";import { addLabelsToIssueGitlab } from "../utils/labels";-export async function handleTaskCreated(+async function createTaskIssue(event: TaskCreatedEvent,context: PluginContext,): Promise<void> {@@ -38,7 +38,7 @@ export async function handleTaskCreated(description: formatIssueBody(event.description, event.taskId),});- await createExternalLink({+ const createdLink = await createExternalLink({taskId: event.taskId,integrationId: context.integrationId,resourceType: "issue",@@ -52,12 +52,36 @@ export async function handleTaskCreated(},});+ if (+ await isTaskInFinalState({+ projectId: event.projectId,+ status: event.status,+ columnId: null,+ })+ ) {+ await client.updateIssue(config.projectPath, createdIssue.iid, {+ state_event: "close",+ });+ await updateExternalLink(createdLink.id, {+ metadata: { state: "closed", lastOutboundStateSyncAt: Date.now() },+ });+ }+await addLabelsToIssueGitlab(config,createdIssue.iid,- getLabelsForIssue(event.priority, event.status),+ await taskIssueLabels(event.taskId, event.priority, event.status),);} catch (error) {console.error("Failed to create GitLab issue:", error);}}++export async function handleTaskCreated(+ event: TaskCreatedEvent,+ context: PluginContext,+): Promise<void> {+ await withTaskSyncCreation(event, context, (current) =>+ createTaskIssue(current, context),+ );+}diff --git a/apps/api/src/plugins/gitlab/events/task-description-changed.ts b/apps/api/src/plugins/gitlab/events/task-description-changed.tsindex b267d8d8e..254381a8a 100644--- a/apps/api/src/plugins/gitlab/events/task-description-changed.ts+++ b/apps/api/src/plugins/gitlab/events/task-description-changed.ts@@ -1,3 +1,4 @@+import { canSyncTask } from "../../sync/eligibility";import {findExternalLinksByTask,updateExternalLink,@@ -16,6 +17,16 @@ export async function handleTaskDescriptionChanged(event: TaskDescriptionChangedEvent,context: PluginContext,): Promise<void> {+ if (+ !(await canSyncTask(+ event.taskId,+ context.integrationId,+ undefined,+ JSON.stringify(context.config),+ ))+ )+ return;+const config = context.config as GitlabConfig;if (!config.baseUrl || !config.accessToken) {return;diff --git a/apps/api/src/plugins/gitlab/events/task-priority-changed.ts b/apps/api/src/plugins/gitlab/events/task-priority-changed.tsindex 756a8b055..403a8c14c 100644--- a/apps/api/src/plugins/gitlab/events/task-priority-changed.ts+++ b/apps/api/src/plugins/gitlab/events/task-priority-changed.ts@@ -1,3 +1,4 @@+import { canSyncTask } from "../../sync/eligibility";import { findExternalLinksByTask } from "../../github/services/link-manager";import type { PluginContext, TaskPriorityChangedEvent } from "../../types";import type { GitlabConfig } from "../config";@@ -7,6 +8,16 @@ export async function handleTaskPriorityChanged(event: TaskPriorityChangedEvent,context: PluginContext,): Promise<void> {+ if (+ !(await canSyncTask(+ event.taskId,+ context.integrationId,+ undefined,+ JSON.stringify(context.config),+ ))+ )+ return;+const config = context.config as GitlabConfig;if (!config.baseUrl || !config.accessToken) {return;diff --git a/apps/api/src/plugins/gitlab/events/task-status-changed.ts b/apps/api/src/plugins/gitlab/events/task-status-changed.tsindex 8e57be85c..babb9c40c 100644--- a/apps/api/src/plugins/gitlab/events/task-status-changed.ts+++ b/apps/api/src/plugins/gitlab/events/task-status-changed.ts@@ -1,3 +1,4 @@+import { canSyncTask } from "../../sync/eligibility";import {findExternalLinksByTask,updateExternalLink,@@ -12,6 +13,16 @@ export async function handleTaskStatusChanged(event: TaskStatusChangedEvent,context: PluginContext,): Promise<void> {+ if (+ !(await canSyncTask(+ event.taskId,+ context.integrationId,+ undefined,+ JSON.stringify(context.config),+ ))+ )+ return;+// Keep activity and other integrations informed without echoing an issue// webhook back to the GitLab project that produced it.if (event.sourceIntegrationId === context.integrationId) return;diff --git a/apps/api/src/plugins/gitlab/events/task-title-changed.ts b/apps/api/src/plugins/gitlab/events/task-title-changed.tsindex b9888a8ad..e1f4feb2e 100644--- a/apps/api/src/plugins/gitlab/events/task-title-changed.ts+++ b/apps/api/src/plugins/gitlab/events/task-title-changed.ts@@ -1,3 +1,4 @@+import { canSyncTask } from "../../sync/eligibility";import {findExternalLinksByTask,updateExternalLink,@@ -15,6 +16,16 @@ export async function handleTaskTitleChanged(event: TaskTitleChangedEvent,context: PluginContext,): Promise<void> {+ if (+ !(await canSyncTask(+ event.taskId,+ context.integrationId,+ undefined,+ JSON.stringify(context.config),+ ))+ )+ return;+const config = context.config as GitlabConfig;if (!config.baseUrl || !config.accessToken) {return;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.tsindex 42bd1dbae..3900dd2f9 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 { canSyncTask } from "../../sync/eligibility";import { eq } from "drizzle-orm";import db from "../../../database";import { externalLinkTable } from "../../../database/schema";@@ -64,6 +65,8 @@ async function getGitlabIssueContext(taskId: string) {return null;}+ if (!(await canSyncTask(taskId, externalLink.integration.id))) return null;+let config: GitlabConfig;try {config = JSON.parse(externalLink.integration.config) as GitlabConfig;diff --git a/apps/api/src/plugins/gitlab/webhooks/issue-opened.ts b/apps/api/src/plugins/gitlab/webhooks/issue-opened.tsindex 421fd7dbb..6a67d1253 100644--- a/apps/api/src/plugins/gitlab/webhooks/issue-opened.ts+++ b/apps/api/src/plugins/gitlab/webhooks/issue-opened.ts@@ -1,6 +1,13 @@+import { acceptsIssue } from "../../sync/rules";+import { importIssueLabels } from "../../sync/issue-labels";import { and, eq } from "drizzle-orm";import db from "../../../database";-import { columnTable, projectTable, taskTable } from "../../../database/schema";+import {+ columnTable,+ integrationTable,+ projectTable,+ taskTable,+} from "../../../database/schema";import { publishEvent } from "../../../events";import { claimTaskNumber } from "../../../task/controllers/claim-task-numbers";import {@@ -75,6 +82,7 @@ export async function handleGitlabIssueOpened(const author = payload.user?.username ?? payload.user?.name;for (const integration of integrations) {+ if (!acceptsIssue(integration.config, payload.labels)) continue;let config: GitlabConfig;try {config = JSON.parse(integration.config) as GitlabConfig;@@ -90,69 +98,76 @@ export async function handleGitlabIssueOpened(const priority = extractIssuePriority(existingLabels);const status = extractIssueStatus(existingLabels);- const existingLink = await findExternalLink(- integration.id,- "issue",- issue.iid.toString(),- );-- if (existingLink) {- continue;- }-- const nextTaskNumber = await claimTaskNumber(projectId);-- const resolvedStatus = await resolveTargetStatus(- projectId,- "issue_opened",- status || "to-do",- );-- const targetColumn = await db.query.columnTable.findFirst({- where: and(- eq(columnTable.projectId, projectId),- eq(columnTable.slug, resolvedStatus),- ),- });-- const taskValues: typeof taskTable.$inferInsert = {- projectId,- userId: null,- title: issue.title,- description: taskDescriptionFromIssue(issue.description),- status: resolvedStatus,- columnId: targetColumn?.id ?? null,- priority: priority ?? "low",- number: nextTaskNumber,- };-- const [createdTask] = await db- .insert(taskTable)- .values(taskValues)- .returning();-- if (!createdTask) {- console.error("Failed to create task from GitLab issue");- continue;- }-- const linkMetadata: Record<string, unknown> = {- state: "opened",- createdFrom: "gitlab",- author,- };-- // Must run before task.created: the plugin's onTaskCreated uses link- // existence to skip self-originated tasks, else it duplicates the issue.- const issueLink = await createExternalLink({- taskId: createdTask.id,- integrationId: integration.id,- resourceType: "issue",- externalId: issue.iid.toString(),- url: issue.url,- title: issue.title,- metadata: linkMetadata,+ const result = await db.transaction(async (tx) => {+ const [current] = await tx+ .select()+ .from(integrationTable)+ .where(eq(integrationTable.id, integration.id))+ .for("update");+ if (+ !current?.isActive ||+ current.config !== integration.config ||+ !acceptsIssue(current.config, payload.labels)+ )+ return null;+ if (+ await findExternalLink(integration.id, "issue", String(issue.iid), tx)+ )+ return null;+ const resolvedStatus = await resolveTargetStatus(+ projectId,+ "issue_opened",+ status || "to-do",+ tx,+ );+ const targetColumn = await tx.query.columnTable.findFirst({+ where: and(+ eq(columnTable.projectId, projectId),+ eq(columnTable.slug, resolvedStatus),+ ),+ });+ const nextTaskNumber = await claimTaskNumber(projectId, tx);+ const [task] = await tx+ .insert(taskTable)+ .values({+ projectId,+ userId: null,+ title: issue.title,+ description: taskDescriptionFromIssue(issue.description),+ status: resolvedStatus,+ columnId: targetColumn?.id ?? null,+ priority: priority ?? "low",+ number: nextTaskNumber,+ })+ .returning();+ if (!task) throw new Error("Failed to create task from gitlab issue");+ const linkMetadata = {+ state: "opened",+ createdFrom: "gitlab",+ author: author,+ };+ const link = await createExternalLink(+ {+ taskId: task.id,+ integrationId: integration.id,+ resourceType: "issue",+ externalId: String(issue.iid),+ url: issue.url,+ title: issue.title,+ metadata: linkMetadata,+ },+ tx,+ );+ await importIssueLabels(+ task.id,+ integration.project.workspaceId,+ payload.labels,+ tx,+ );+ return { task, link, linkMetadata };});+ if (!result) continue;+ const { task: createdTask, link: issueLink, linkMetadata } = result;await publishEvent("task.created", {...createdTask,diff --git a/apps/api/src/plugins/gitlab/webhooks/issue-updated.ts b/apps/api/src/plugins/gitlab/webhooks/issue-updated.tsindex 3f1c22072..d2feb6252 100644--- a/apps/api/src/plugins/gitlab/webhooks/issue-updated.ts+++ b/apps/api/src/plugins/gitlab/webhooks/issue-updated.ts@@ -1,3 +1,5 @@+import { acceptsIssue, readSyncRules } from "../../sync/rules";+import { handleGitlabIssueOpened } from "./issue-opened";import { withIntegrationLink } from "../../github/services/with-integration-link";import {type IntegrationDatabase,@@ -161,6 +163,13 @@ export async function handleGitlabIssueUpdated();if (!externalLink) {+ if (+ touchedLabels &&+ readSyncRules(integration.config)?.incoming.mode === "labels" &&+ acceptsIssue(integration.config, payload.labels)+ ) {+ await handleGitlabIssueOpened(payload, integration.id);+ }continue;}diff --git a/apps/api/src/plugins/registry.ts b/apps/api/src/plugins/registry.tsindex e9bacccc6..b725fb5c1 100644--- a/apps/api/src/plugins/registry.ts+++ b/apps/api/src/plugins/registry.ts@@ -1,3 +1,4 @@+import { reconcileProjectSync, reconcileTaskSync } from "./sync/reconcile";import { and, eq } from "drizzle-orm";import db from "../database";import { integrationTable } from "../database/schema";@@ -229,6 +230,34 @@ export function initializeEventSubscriptions(): void {});});+ for (const event of [+ "task.label_created",+ "task.label_deleted",+ "task.label_assigned",+ "task.label_unassigned",+ "task.labels_updated",+ ]) {+ subscribeToEvent<{ projectId: string; taskId: string }>(+ event,+ async (data) => {+ await reconcileTaskSync(data.projectId, data.taskId);+ },+ );+ }+ subscribeToEvent<{ projectId: string; integrationId: string }>(+ "integration.sync_rules_changed",+ async (data) => {+ await reconcileProjectSync(data.projectId, data.integrationId);+ },+ );++ subscribeToEvent<{ projectId: string }>(+ "integration.sync_labels_changed",+ async (data) => {+ await reconcileProjectSync(data.projectId);+ },+ );+eventSubscriptionsInitialized = true;console.log("✓ Plugin event subscriptions initialized");}diff --git a/apps/api/src/plugins/sync/create-task-issue.ts b/apps/api/src/plugins/sync/create-task-issue.tsnew file mode 100644index 000000000..e4b561034--- /dev/null+++ b/apps/api/src/plugins/sync/create-task-issue.ts@@ -0,0 +1,71 @@+import { and, eq, sql } from "drizzle-orm";+import db from "../../database";+import { externalLinkTable, taskTable } from "../../database/schema";+import type { PluginContext, TaskCreatedEvent } from "../types";+import { canSyncTask } from "./eligibility";++// Keep one lease per API process so provider callbacks can use the pool without+// exhausting it. PostgreSQL also serializes the same task across API instances.+let creationQueue: Promise<void> = Promise.resolve();++export async function withTaskSyncCreation(+ event: TaskCreatedEvent,+ context: PluginContext,+ create: (current: TaskCreatedEvent) => Promise<void>,+) {+ const next = creationQueue.then(() =>+ createWithLease(event, context, create),+ );+ creationQueue = next.catch(() => {});+ await next;+}+async function createWithLease(+ event: TaskCreatedEvent,+ context: PluginContext,+ create: (current: TaskCreatedEvent) => Promise<void>,+) {+ await db.transaction(async (tx) => {+ const result = await tx.execute<{ locked: boolean }>(+ sql`select pg_try_advisory_xact_lock(hashtextextended(${`sync-create:${context.integrationId}:${event.taskId}`}, 0)) as locked`,+ );+ if (!result.rows[0]?.locked) return;+ if (+ !(await canSyncTask(+ event.taskId,+ context.integrationId,+ undefined,+ JSON.stringify(context.config),+ ))+ )+ return;+ if (+ await db.query.externalLinkTable.findFirst({+ where: and(+ eq(externalLinkTable.taskId, event.taskId),+ eq(externalLinkTable.integrationId, context.integrationId),+ eq(externalLinkTable.resourceType, "issue"),+ ),+ columns: { id: true },+ })+ )+ return;+ const task = await db.query.taskTable.findFirst({+ where: and(+ eq(taskTable.id, event.taskId),+ eq(taskTable.projectId, context.projectId),+ ),+ });+ if (!task || task.number === null) return;+ await create({+ taskId: task.id,+ projectId: task.projectId,+ userId: task.userId ?? "",+ title: task.title,+ description: task.description,+ priority: task.priority,+ status: task.status,+ number: task.number,+ });+ await canSyncTask(task.id, context.integrationId);+ });+}diff --git a/apps/api/src/plugins/sync/eligibility.ts b/apps/api/src/plugins/sync/eligibility.tsnew file mode 100644index 000000000..22bdcff56--- /dev/null+++ b/apps/api/src/plugins/sync/eligibility.ts@@ -0,0 +1,91 @@+import { outgoingPredicate } from "./task-predicate";+import { and, eq } from "drizzle-orm";+import db from "../../database";+import {+ externalLinkTable,+ integrationTable,+ projectTable,+ taskTable,+} from "../../database/schema";+import { updateExternalLink } from "../github/services/link-manager";+import type { IntegrationDatabase } from "../github/services/integration-task-scope";+import { isSyncPaused, readSyncRules, type LabelRule } from "./rules";++export async function taskMatchesRule(+ taskId: string,+ projectId: string,+ rule: LabelRule,+ database: IntegrationDatabase = db,+): Promise<boolean> {+ const task = await database.query.taskTable.findFirst({+ where: and(eq(taskTable.id, taskId), eq(taskTable.projectId, projectId)),+ columns: { id: true },+ });+ if (!task) return false;+ if (rule.mode === "all") return true;+ const project = await database.query.projectTable.findFirst({+ where: eq(projectTable.id, projectId),+ columns: { workspaceId: true },+ });+ if (!project) return false;+ const { predicate } = await outgoingPredicate(+ project.workspaceId,+ rule,+ database,+ );+ const [matching] = await database+ .select({ id: taskTable.id })+ .from(taskTable)+ .where(+ and(+ eq(taskTable.id, taskId),+ eq(taskTable.projectId, projectId),+ predicate,+ ),+ );+ return !!matching;+}++export async function canSyncTask(+ taskId: string,+ integrationId: string,+ database: IntegrationDatabase = db,+ expectedConfig?: string,+): Promise<boolean> {+ const integration = await database.query.integrationTable.findFirst({+ where: eq(integrationTable.id, integrationId),+ });+ if (+ !integration?.isActive ||+ (expectedConfig !== undefined && integration.config !== expectedConfig)+ )+ return false;+ const rules = readSyncRules(integration.config);+ const matches =+ !!rules &&+ (await taskMatchesRule(+ taskId,+ integration.projectId,+ rules.outgoing,+ database,+ ));+ const links = await database.query.externalLinkTable.findMany({+ where: and(+ eq(externalLinkTable.integrationId, integrationId),+ eq(externalLinkTable.taskId, taskId),+ eq(externalLinkTable.resourceType, "issue"),+ ),+ });+ if (!matches) {+ for (const link of links) {+ if (!isSyncPaused(link.metadata))+ await updateExternalLink(+ link.id,+ { metadata: { syncFilterPaused: true } },+ database,+ );+ }+ return false;+ }+ return !links.some((link) => isSyncPaused(link.metadata));+}diff --git a/apps/api/src/plugins/sync/issue-labels.ts b/apps/api/src/plugins/sync/issue-labels.tsnew file mode 100644index 000000000..c3676de2f--- /dev/null+++ b/apps/api/src/plugins/sync/issue-labels.ts@@ -0,0 +1,53 @@+import { and, eq, isNull } from "drizzle-orm";+import db from "../../database";+import { labelTable } from "../../database/schema";+import type { IntegrationDatabase } from "../github/services/integration-task-scope";+import { getLabelsForIssue } from "../github/utils/format";+import { issueLabelNames } from "./rules";++export async function taskIssueLabels(+ taskId: string,+ priority: string | null,+ status: string,+) {+ const assigned = await db+ .select({ name: labelTable.name })+ .from(labelTable)+ .where(eq(labelTable.taskId, taskId));+ return [+ ...new Set([+ ...getLabelsForIssue(priority, status),+ ...assigned.map((label) => label.name),+ ]),+ ];+}++export async function importIssueLabels(+ taskId: string,+ workspaceId: string,+ labels: unknown,+ database: IntegrationDatabase = db,+) {+ const names = issueLabelNames(labels).filter(+ (name) => !name.startsWith("status:") && !name.startsWith("priority:"),+ );+ if (!names.length) return;+ const existing = await database+ .select({ name: labelTable.name, color: labelTable.color })+ .from(labelTable)+ .where(+ and(eq(labelTable.workspaceId, workspaceId), isNull(labelTable.taskId)),+ );+ await database+ .insert(labelTable)+ .values(+ [...new Set(names)].map((name) => ({+ name,+ color:+ existing.find((label) => label.name === name)?.color ?? "#6B7280",+ taskId,+ workspaceId,+ })),+ )+ .onConflictDoNothing({ target: [labelTable.taskId, labelTable.name] });+}diff --git a/apps/api/src/plugins/sync/provider-issue.ts b/apps/api/src/plugins/sync/provider-issue.tsnew file mode 100644index 000000000..6f73c9eca--- /dev/null+++ b/apps/api/src/plugins/sync/provider-issue.ts@@ -0,0 +1,107 @@+import type { GiteaConfig } from "../gitea/config";+import { createGiteaClient } from "../gitea/utils/gitea-api";+import type { GitHubConfig } from "../github/config";+import {+ formatIssueBody,+ formatTaskDescriptionFromIssue,+} from "../github/utils/format";+import { getVerifiedInstallationOctokit } from "../github/utils/github-app";+import type { GitlabConfig } from "../gitlab/config";+import { createGitlabClient } from "../gitlab/utils/gitlab-api";++export type IssueValues = {+ title: string;+ description: string;+ state: "open" | "closed";+};++export async function providerIssue(+ integration: { type: string; config: string },+ link: { externalId: string; taskId: string },+) {+ const number = Number(link.externalId);+ if (!Number.isSafeInteger(number) || number <= 0)+ throw new Error("Invalid issue number");+ const config = JSON.parse(integration.config);+ const owner = config.repositoryOwner;+ const repo = config.repositoryName;+ const normalize = (issue: {+ title: string;+ body?: string | null;+ description?: string | null;+ state: string;+ updated_at?: string;+ }) => ({+ title: issue.title,+ description: formatTaskDescriptionFromIssue(+ issue.body ?? issue.description ?? "",+ link.taskId,+ ),+ state: issue.state === "closed" ? ("closed" as const) : ("open" as const),+ updatedAt: issue.updated_at ?? null,+ });+ if (integration.type === "gitea") {+ const client = createGiteaClient(config as GiteaConfig);+ return {+ read: async () => normalize(await client.getIssue(owner, repo, number)),+ write: async (values: IssueValues) =>+ normalize(+ await client.updateIssue(owner, repo, number, {+ title: values.title,+ body: formatIssueBody(values.description, link.taskId),+ state: values.state,+ }),+ ),+ };+ }+ if (integration.type === "gitlab") {+ const client = createGitlabClient(config as GitlabConfig);+ return {+ read: async () => {+ const issue = await client.getIssue(config.projectPath, number);+ if (issue.confidential)+ throw new Error("Confidential issue cannot be synchronized");+ return normalize(issue);+ },+ write: async (values: IssueValues) =>+ normalize(+ await client.updateIssue(config.projectPath, number, {+ title: values.title,+ description: formatIssueBody(values.description, link.taskId),+ state_event: values.state === "closed" ? "close" : "reopen",+ }),+ ),+ };+ }+ const octokit = await getVerifiedInstallationOctokit(+ config as GitHubConfig,+ true,+ );+ return {+ read: async () =>+ normalize(+ (+ await octokit.rest.issues.get({+ owner,+ repo,+ issue_number: number,+ request: { timeout: 10_000 },+ })+ ).data,+ ),+ write: async (values: IssueValues) =>+ normalize(+ (+ await octokit.rest.issues.update({+ owner,+ repo,+ issue_number: number,+ title: values.title,+ body: formatIssueBody(values.description, link.taskId),+ state: values.state,+ request: { timeout: 10_000 },+ })+ ).data,+ ),+ };+}diff --git a/apps/api/src/plugins/sync/reconcile.ts b/apps/api/src/plugins/sync/reconcile.tsnew file mode 100644index 000000000..9a2977387--- /dev/null+++ b/apps/api/src/plugins/sync/reconcile.ts@@ -0,0 +1,82 @@+import { and, asc, eq, gt, inArray } from "drizzle-orm";+import db from "../../database";+import { integrationTable, taskTable } from "../../database/schema";+import { publishEvent } from "../../events";+import { getPlugin } from "../registry";+import { canSyncTask } from "./eligibility";+import { readSyncRules, syncProviders } from "./rules";++export async function reconcileTaskSync(+ projectId: string,+ taskId: string,+ onlyIntegrationId?: string,+) {+ const integrations = await db.query.integrationTable.findMany({+ where: and(+ eq(integrationTable.projectId, projectId),+ eq(integrationTable.isActive, true),+ inArray(integrationTable.type, [...syncProviders]),+ onlyIntegrationId+ ? eq(integrationTable.id, onlyIntegrationId)+ : undefined,+ ),+ });+ for (const integration of integrations) {+ // Legacy integrations retain their existing task-created behavior.+ const config = JSON.parse(integration.config) as Record<string, unknown>;+ if (!config.syncRules || !readSyncRules(config)) continue;+ 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 },+ );+ }+ await publishEvent("task.updated", { projectId, taskId });+}++export async function reconcileProjectSync(+ projectId: string,+ integrationId?: string,+) {+ 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)+ await reconcileTaskSync(projectId, task.id, integrationId);+ cursor = tasks.at(-1)?.id;+ }+}diff --git a/apps/api/src/plugins/sync/rules.ts b/apps/api/src/plugins/sync/rules.tsnew file mode 100644index 000000000..2d944303d--- /dev/null+++ b/apps/api/src/plugins/sync/rules.ts@@ -0,0 +1,90 @@+import { z } from "zod";++const labelSelection = z.object({+ mode: z.literal("labels"),+ match: z.enum(["any", "all"]),+ labels: z+ .array(z.string().trim().min(1).max(128))+ .min(1)+ .max(50)+ .refine(+ (labels) => new Set(labels).size === labels.length,+ "Labels must be unique",+ ),+});++export const labelRuleSchema = z.discriminatedUnion("mode", [+ z.object({ mode: z.literal("all") }),+ labelSelection,+]);++export const syncRulesSchema = z.object({+ outgoing: labelRuleSchema.describe(+ "Kaneo workspace label IDs controlling task sync. Missing labels pause sync.",+ ),+ incoming: labelRuleSchema.describe(+ "Exact repository label names controlling which issues can be imported.",+ ),+});++export type LabelRule = z.infer<typeof labelRuleSchema>;+export type SyncRules = z.infer<typeof syncRulesSchema>;+export const defaultSyncRules: SyncRules = {+ outgoing: { mode: "all" },+ incoming: { mode: "all" },+};+export const syncProviders = ["github", "gitea", "gitlab"] as const;++export function readSyncRules(+ config: string | Record<string, unknown>,+): SyncRules | null {+ try {+ const parsed = typeof config === "string" ? JSON.parse(config) : config;+ if (!parsed || typeof parsed !== "object") return null;+ if (parsed.syncRules === undefined) return defaultSyncRules;+ const result = syncRulesSchema.safeParse(parsed.syncRules);+ return result.success ? result.data : null;+ } catch {+ return null;+ }+}++export function matchesLabels(+ rule: LabelRule,+ labels: readonly string[],+): boolean {+ if (rule.mode === "all") return true;+ if (!rule.labels.length) return false;+ const present = new Set(labels);+ return rule.match === "all"+ ? rule.labels.every((label) => present.has(label))+ : rule.labels.some((label) => present.has(label));+}++export function issueLabelNames(labels: unknown): string[] {+ if (!Array.isArray(labels)) return [];+ return labels.flatMap((label) => {+ if (typeof label === "string") return [label];+ if (label && typeof label === "object") {+ const name = label.name ?? label.title;+ return typeof name === "string" ? [name] : [];+ }+ return [];+ });+}++export function acceptsIssue(+ config: string | Record<string, unknown>,+ labels: unknown,+): boolean {+ const rules = readSyncRules(config);+ return !!rules && matchesLabels(rules.incoming, issueLabelNames(labels));+}++export function isSyncPaused(metadata: string | null): boolean {+ try {+ return JSON.parse(metadata ?? "{}").syncFilterPaused === true;+ } catch {+ return false;+ }+}diff --git a/apps/api/src/plugins/sync/task-predicate.ts b/apps/api/src/plugins/sync/task-predicate.tsnew file mode 100644index 000000000..4db79de8e--- /dev/null+++ b/apps/api/src/plugins/sync/task-predicate.ts@@ -0,0 +1,43 @@+import { and, eq, isNull, sql } from "drizzle-orm";+import db from "../../database";+import { labelTable, taskTable } from "../../database/schema";+import type { IntegrationDatabase } from "../github/services/integration-task-scope";+import type { LabelRule } from "./rules";++export async function outgoingPredicate(+ workspaceId: string,+ rule: LabelRule,+ database: IntegrationDatabase = db,+) {+ const labels = await database+ .select({+ id: labelTable.id,+ name: labelTable.name,+ color: labelTable.color,+ })+ .from(labelTable)+ .where(+ and(+ eq(labelTable.workspaceId, workspaceId),+ isNull(labelTable.taskId),+ isNull(labelTable.deletionStartedAt),+ ),+ );+ if (rule.mode === "all")+ return { predicate: sql<boolean>`true`, labels, missing: [] as string[] };+ const selected = labels.filter((label) => rule.labels.includes(label.id));+ const missing = rule.labels.filter(+ (id) => !selected.some((label) => label.id === id),+ );+ if (missing.length || !selected.length)+ return { predicate: sql<boolean>`false`, labels, missing };+ const names = sql.join(+ selected.map((label) => sql`${label.name}`),+ sql`, `,+ );+ const predicate =+ rule.match === "any"+ ? sql<boolean>`exists (select 1 from ${labelTable} assigned where assigned.task_id = ${taskTable.id} and assigned.workspace_id = ${workspaceId} and assigned.name in (${names}))`+ : sql<boolean>`(select count(distinct assigned.name) from ${labelTable} assigned where assigned.task_id = ${taskTable.id} and assigned.workspace_id = ${workspaceId} and assigned.name in (${names})) = ${selected.length}`;+ return { predicate, labels, missing };+}diff --git a/apps/docs/core/integrations/index.mdx b/apps/docs/core/integrations/index.mdxindex ae1503083..e9b8546e1 100644--- a/apps/docs/core/integrations/index.mdx+++ b/apps/docs/core/integrations/index.mdx@@ -21,6 +21,17 @@ Connect the tools your team already uses. Repository connections and shared notiGitHub, Gitea, and GitLab have connection forms under **Settings → Projects → your project → Integrations**. Follow the provider guide to connect a repository and configure its webhook.+## Limit repository sync by label++Enable **Advanced settings** in **Account → Preferences** or **Workspace → General**, then open a connected GitHub, Gitea, or GitLab integration. Workspace settings managers can edit its **Sync scope**. The saved rules apply to everyone in the project; turning advanced mode off only hides the editor.++- **Kaneo → repository** selects workspace labels by stable ID. Match any selected label or require all of them. The preview shows matching tasks, new exports, and affected links before you apply the rule.+- **Repository → Kaneo** selects exact repository label names for new tasks and imports. Existing linked tasks follow the Kaneo rule. Adding a qualifying repository label can admit an issue that was previously excluded.++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.++Newly matching tasks without an issue link are exported in the background when rules or task labels change. Use **Export matching tasks** to retry tasks that still have no issue link after a failed export. An inactive integration does not export or resume tasks. Existing installations retain unrestricted sync until a rule is saved.+## Team notificationsSend selected project events to a shared channel. Open **Settings → Projects → your project → Integrations** to connect these services.diff --git a/apps/docs/openapi.json b/apps/docs/openapi.jsonindex 3ef2e70d8..2a2bb6522 100644--- a/apps/docs/openapi.json+++ b/apps/docs/openapi.json@@ -2254,6 +2254,342 @@"relevanceScore"]},+ "IntegrationSyncPreview": {+ "type": "object",+ "properties": {+ "isActive": {+ "type": "boolean"+ },+ "rules": {+ "type": "object",+ "properties": {+ "outgoing": {+ "oneOf": [+ {+ "type": "object",+ "properties": {+ "mode": {+ "type": "string",+ "enum": [+ "all"+ ]+ }+ },+ "required": [+ "mode"+ ]+ },+ {+ "type": "object",+ "properties": {+ "mode": {+ "type": "string",+ "enum": [+ "labels"+ ]+ },+ "match": {+ "type": "string",+ "enum": [+ "any",+ "all"+ ]+ },+ "labels": {+ "type": "array",+ "items": {+ "type": "string",+ "minLength": 1,+ "maxLength": 128+ },+ "minItems": 1,+ "maxItems": 50+ }+ },+ "required": [+ "mode",+ "match",+ "labels"+ ]+ }+ ],+ "description": "Kaneo workspace label IDs controlling task sync. Missing labels pause sync."+ },+ "incoming": {+ "oneOf": [+ {+ "type": "object",+ "properties": {+ "mode": {+ "type": "string",+ "enum": [+ "all"+ ]+ }+ },+ "required": [+ "mode"+ ]+ },+ {+ "type": "object",+ "properties": {+ "mode": {+ "type": "string",+ "enum": [+ "labels"+ ]+ },+ "match": {+ "type": "string",+ "enum": [+ "any",+ "all"+ ]+ },+ "labels": {+ "type": "array",+ "items": {+ "type": "string",+ "minLength": 1,+ "maxLength": 128+ },+ "minItems": 1,+ "maxItems": 50+ }+ },+ "required": [+ "mode",+ "match",+ "labels"+ ]+ }+ ],+ "description": "Exact repository label names controlling which issues can be imported."+ }+ },+ "required": [+ "outgoing",+ "incoming"+ ]+ },+ "labels": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "color": {+ "type": "string"+ }+ },+ "required": [+ "id",+ "name",+ "color"+ ]+ }+ },+ "missingLabels": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "total": {+ "type": "number"+ },+ "matching": {+ "type": "number"+ },+ "willCreate": {+ "type": "number"+ },+ "willPause": {+ "type": "number"+ },+ "needsReview": {+ "type": "number"+ },+ "paused": {+ "type": "number"+ },+ "matchingTasks": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "number": {+ "type": [+ "number",+ "null"+ ]+ },+ "title": {+ "type": "string"+ }+ },+ "required": [+ "id",+ "number",+ "title"+ ]+ }+ },+ "pausedNextCursor": {+ "type": [+ "string",+ "null"+ ]+ },+ "pausedTasks": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "number": {+ "type": [+ "number",+ "null"+ ]+ },+ "title": {+ "type": "string"+ },+ "linkId": {+ "type": "string"+ },+ "url": {+ "type": "string"+ },+ "eligible": {+ "type": "boolean"+ }+ },+ "required": [+ "id",+ "number",+ "title",+ "linkId",+ "url",+ "eligible"+ ]+ }+ },+ "previewToken": {+ "type": "string"+ }+ },+ "required": [+ "isActive",+ "rules",+ "labels",+ "missingLabels",+ "total",+ "matching",+ "willCreate",+ "willPause",+ "needsReview",+ "paused",+ "matchingTasks",+ "pausedNextCursor",+ "pausedTasks",+ "previewToken"+ ]+ },+ "IntegrationSyncResumePreview": {+ "type": "object",+ "properties": {+ "task": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "number": {+ "type": [+ "number",+ "null"+ ]+ },+ "title": {+ "type": "string"+ }+ },+ "required": [+ "id",+ "number",+ "title"+ ]+ },+ "local": {+ "type": "object",+ "properties": {+ "title": {+ "type": "string"+ },+ "description": {+ "type": "string"+ },+ "state": {+ "type": "string",+ "enum": [+ "open",+ "closed"+ ]+ }+ },+ "required": [+ "title",+ "description",+ "state"+ ]+ },+ "remote": {+ "type": "object",+ "properties": {+ "title": {+ "type": "string"+ },+ "description": {+ "type": "string"+ },+ "state": {+ "type": "string",+ "enum": [+ "open",+ "closed"+ ]+ }+ },+ "required": [+ "title",+ "description",+ "state"+ ]+ },+ "token": {+ "type": "string"+ }+ },+ "required": [+ "task",+ "local",+ "remote",+ "token"+ ]+ },"GitHubAppInfo": {"type": "object","properties": {@@ -13464,6 +13800,792 @@}}},+ "/integration-sync/project/{projectId}/{provider}": {+ "get": {+ "operationId": "getIntegrationSyncRules",+ "tags": [+ "Integration sync"+ ],+ "summary": "Get sync rules and current task scope",+ "description": "Workspace members can inspect saved rules. Rules remain active when advanced mode is hidden. Paused issue links are preserved; eligible paused tasks require review before resuming.",+ "parameters": [+ {+ "schema": {+ "type": "string",+ "minLength": 1+ },+ "required": true,+ "name": "projectId",+ "in": "path"+ },+ {+ "schema": {+ "type": "string",+ "enum": [+ "github",+ "gitea",+ "gitlab"+ ]+ },+ "required": true,+ "name": "provider",+ "in": "path"+ },+ {+ "schema": {+ "type": "string"+ },+ "required": false,+ "name": "after",+ "in": "query"+ }+ ],+ "responses": {+ "200": {+ "description": "Saved rules and scope",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/IntegrationSyncPreview"+ }+ }+ }+ },+ "400": {+ "description": "Invalid rule or workspace label",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "401": {+ "description": "Missing or invalid credentials"+ },+ "403": {+ "description": "No workspace access or required permission",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "404": {+ "description": "Integration or linked task not found",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "409": {+ "description": "Configuration, impact or comparison changed; review again",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ }+ }+ },+ "patch": {+ "operationId": "saveIntegrationSyncRules",+ "tags": [+ "Integration sync"+ ],+ "summary": "Apply a previewed sync rule",+ "description": "Save shared integration rules only if the preview is still current. Excluded links are paused, never deleted. Newly matching unlinked tasks are exported through the integration event path. Paused links require explicit review to resume.",+ "parameters": [+ {+ "schema": {+ "type": "string",+ "minLength": 1+ },+ "required": true,+ "name": "projectId",+ "in": "path"+ },+ {+ "schema": {+ "type": "string",+ "enum": [+ "github",+ "gitea",+ "gitlab"+ ]+ },+ "required": true,+ "name": "provider",+ "in": "path"+ }+ ],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "properties": {+ "rules": {+ "type": "object",+ "properties": {+ "outgoing": {+ "oneOf": [+ {+ "type": "object",+ "properties": {+ "mode": {+ "type": "string",+ "enum": [+ "all"+ ]+ }+ },+ "required": [+ "mode"+ ]+ },+ {+ "type": "object",+ "properties": {+ "mode": {+ "type": "string",+ "enum": [+ "labels"+ ]+ },+ "match": {+ "type": "string",+ "enum": [+ "any",+ "all"+ ]+ },+ "labels": {+ "type": "array",+ "items": {+ "type": "string",+ "minLength": 1,+ "maxLength": 128+ },+ "minItems": 1,+ "maxItems": 50+ }+ },+ "required": [+ "mode",+ "match",+ "labels"+ ]+ }+ ],+ "description": "Kaneo workspace label IDs controlling task sync. Missing labels pause sync."+ },+ "incoming": {+ "oneOf": [+ {+ "type": "object",+ "properties": {+ "mode": {+ "type": "string",+ "enum": [+ "all"+ ]+ }+ },+ "required": [+ "mode"+ ]+ },+ {+ "type": "object",+ "properties": {+ "mode": {+ "type": "string",+ "enum": [+ "labels"+ ]+ },+ "match": {+ "type": "string",+ "enum": [+ "any",+ "all"+ ]+ },+ "labels": {+ "type": "array",+ "items": {+ "type": "string",+ "minLength": 1,+ "maxLength": 128+ },+ "minItems": 1,+ "maxItems": 50+ }+ },+ "required": [+ "mode",+ "match",+ "labels"+ ]+ }+ ],+ "description": "Exact repository label names controlling which issues can be imported."+ }+ },+ "required": [+ "outgoing",+ "incoming"+ ]+ },+ "previewToken": {+ "type": "string",+ "minLength": 64,+ "maxLength": 64+ }+ },+ "required": [+ "rules",+ "previewToken"+ ]+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "Saved rules and current scope",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/IntegrationSyncPreview"+ }+ }+ }+ },+ "400": {+ "description": "Invalid rule or workspace label",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "401": {+ "description": "Missing or invalid credentials"+ },+ "403": {+ "description": "No workspace access or required permission",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "404": {+ "description": "Integration or linked task not found",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "409": {+ "description": "Configuration, impact or comparison changed; review again",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ }+ }+ }+ },+ "/integration-sync/project/{projectId}/{provider}/preview": {+ "post": {+ "operationId": "previewIntegrationSyncRules",+ "tags": [+ "Integration sync"+ ],+ "summary": "Preview a sync rule change",+ "description": "Returns matching tasks, new exports, paused links and a token bound to the current integration and impact. Outgoing labels are workspace label IDs; incoming labels are exact repository label names.",+ "parameters": [+ {+ "schema": {+ "type": "string",+ "minLength": 1+ },+ "required": true,+ "name": "projectId",+ "in": "path"+ },+ {+ "schema": {+ "type": "string",+ "enum": [+ "github",+ "gitea",+ "gitlab"+ ]+ },+ "required": true,+ "name": "provider",+ "in": "path"+ }+ ],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "properties": {+ "rules": {+ "type": "object",+ "properties": {+ "outgoing": {+ "oneOf": [+ {+ "type": "object",+ "properties": {+ "mode": {+ "type": "string",+ "enum": [+ "all"+ ]+ }+ },+ "required": [+ "mode"+ ]+ },+ {+ "type": "object",+ "properties": {+ "mode": {+ "type": "string",+ "enum": [+ "labels"+ ]+ },+ "match": {+ "type": "string",+ "enum": [+ "any",+ "all"+ ]+ },+ "labels": {+ "type": "array",+ "items": {+ "type": "string",+ "minLength": 1,+ "maxLength": 128+ },+ "minItems": 1,+ "maxItems": 50+ }+ },+ "required": [+ "mode",+ "match",+ "labels"+ ]+ }+ ],+ "description": "Kaneo workspace label IDs controlling task sync. Missing labels pause sync."+ },+ "incoming": {+ "oneOf": [+ {+ "type": "object",+ "properties": {+ "mode": {+ "type": "string",+ "enum": [+ "all"+ ]+ }+ },+ "required": [+ "mode"+ ]+ },+ {+ "type": "object",+ "properties": {+ "mode": {+ "type": "string",+ "enum": [+ "labels"+ ]+ },+ "match": {+ "type": "string",+ "enum": [+ "any",+ "all"+ ]+ },+ "labels": {+ "type": "array",+ "items": {+ "type": "string",+ "minLength": 1,+ "maxLength": 128+ },+ "minItems": 1,+ "maxItems": 50+ }+ },+ "required": [+ "mode",+ "match",+ "labels"+ ]+ }+ ],+ "description": "Exact repository label names controlling which issues can be imported."+ }+ },+ "required": [+ "outgoing",+ "incoming"+ ]+ }+ },+ "required": [+ "rules"+ ]+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "Proposed rule impact",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/IntegrationSyncPreview"+ }+ }+ }+ },+ "400": {+ "description": "Invalid rule or workspace label",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "401": {+ "description": "Missing or invalid credentials"+ },+ "403": {+ "description": "No workspace access or required permission",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "404": {+ "description": "Integration or linked task not found",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "409": {+ "description": "Configuration, impact or comparison changed; review again",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ }+ }+ }+ },+ "/integration-sync/project/{projectId}/{provider}/links/{linkId}/review": {+ "get": {+ "operationId": "reviewIntegrationSyncResume",+ "tags": [+ "Integration sync"+ ],+ "summary": "Compare a paused task with its external issue",+ "parameters": [+ {+ "schema": {+ "type": "string",+ "minLength": 1+ },+ "required": true,+ "name": "projectId",+ "in": "path"+ },+ {+ "schema": {+ "type": "string",+ "enum": [+ "github",+ "gitea",+ "gitlab"+ ]+ },+ "required": true,+ "name": "provider",+ "in": "path"+ },+ {+ "schema": {+ "type": "string",+ "minLength": 1+ },+ "required": true,+ "name": "linkId",+ "in": "path"+ }+ ],+ "responses": {+ "200": {+ "description": "Current values and comparison token",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/IntegrationSyncResumePreview"+ }+ }+ }+ },+ "400": {+ "description": "Invalid rule or workspace label",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "401": {+ "description": "Missing or invalid credentials"+ },+ "403": {+ "description": "No workspace access or required permission",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "404": {+ "description": "Integration or linked task not found",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "409": {+ "description": "Configuration, impact or comparison changed; review again",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "502": {+ "description": "External issue unavailable; sync remains paused",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ }+ }+ }+ },+ "/integration-sync/project/{projectId}/{provider}/links/{linkId}/resume": {+ "post": {+ "operationId": "resumeIntegrationSync",+ "tags": [+ "Integration sync"+ ],+ "summary": "Resume a reviewed issue link",+ "description": "Explicitly choose the current Kaneo or repository title, description and open/closed state. Existing links are reused; historical comments are not replayed. The task must still match its outgoing rule. A changed comparison requires another review.",+ "parameters": [+ {+ "schema": {+ "type": "string",+ "minLength": 1+ },+ "required": true,+ "name": "projectId",+ "in": "path"+ },+ {+ "schema": {+ "type": "string",+ "enum": [+ "github",+ "gitea",+ "gitlab"+ ]+ },+ "required": true,+ "name": "provider",+ "in": "path"+ },+ {+ "schema": {+ "type": "string",+ "minLength": 1+ },+ "required": true,+ "name": "linkId",+ "in": "path"+ }+ ],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "properties": {+ "token": {+ "type": "string",+ "minLength": 64,+ "maxLength": 64+ },+ "source": {+ "type": "string",+ "enum": [+ "kaneo",+ "provider"+ ]+ }+ },+ "required": [+ "token",+ "source"+ ]+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "Sync resumed",+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "properties": {+ "success": {+ "type": "boolean"+ }+ },+ "required": [+ "success"+ ]+ }+ }+ }+ },+ "400": {+ "description": "Invalid rule or workspace label",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "401": {+ "description": "Missing or invalid credentials"+ },+ "403": {+ "description": "No workspace access or required permission",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "404": {+ "description": "Integration or linked task not found",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "409": {+ "description": "Configuration, impact or comparison changed; review again",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "502": {+ "description": "External issue unavailable; sync remains paused",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ }+ }+ }+ },"/github-integration/app-info": {"get": {"operationId": "getGitHubAppInfo",diff --git a/apps/web/src/components/external-links/external-links-accordion.tsx b/apps/web/src/components/external-links/external-links-accordion.tsxindex ef2a8ac09..928acd2d5 100644--- a/apps/web/src/components/external-links/external-links-accordion.tsx+++ b/apps/web/src/components/external-links/external-links-accordion.tsx@@ -122,6 +122,14 @@ export function ExternalLinksAccordion({const isIssue = link.resourceType === "issue";const isBranch = link.resourceType === "branch";+ if (isIssue && link.metadata?.syncFilterPaused === true) {+ return (+ <span className="text-xs font-medium text-warning-foreground">+ {t("settings:syncRules.paused")}+ </span>+ );+ }+if (isIssue) {return (<span className="text-xs font-medium text-muted-foreground">diff --git a/apps/web/src/components/project/integrations/integration-row.test.tsx b/apps/web/src/components/project/integrations/integration-row.test.tsxindex 2b76cbedd..8802cccad 100644--- a/apps/web/src/components/project/integrations/integration-row.test.tsx+++ b/apps/web/src/components/project/integrations/integration-row.test.tsx@@ -3,6 +3,10 @@ import { afterEach, describe, expect, it, vi } from "vite-plus/test";import type { IntegrationDefinition } from "@/components/project/integrations/integration-definitions";import { IntegrationRow } from "@/components/project/integrations/integration-row";+vi.mock("@/components/project/sync-rules/sync-rules-section", () => ({+ SyncRulesSection: () => <p>Sync rules</p>,+}));+vi.mock("react-i18next", () => ({useTranslation: () => ({ t: (key: string) => key }),}));diff --git a/apps/web/src/components/project/integrations/integration-row.tsx b/apps/web/src/components/project/integrations/integration-row.tsxindex 7182ce82a..f36a49fbf 100644--- a/apps/web/src/components/project/integrations/integration-row.tsx+++ b/apps/web/src/components/project/integrations/integration-row.tsx@@ -1,3 +1,4 @@+import { SyncRulesSection } from "@/components/project/sync-rules/sync-rules-section";import { useState } from "react";import { useTranslation } from "react-i18next";import type { IntegrationStatus } from "@/components/project/integrations/get-integration-status";@@ -89,6 +90,17 @@ export function IntegrationRow({<CollapsiblePanel><div className="border-t border-border bg-muted/40 p-4"><integration.Settings projectId={projectId} />+ {isSetUp &&+ (integration.id === "github" ||+ integration.id === "gitea" ||+ integration.id === "gitlab") && (+ <div className="mt-4">+ <SyncRulesSection+ projectId={projectId}+ provider={integration.id}+ />+ </div>+ )}</div></CollapsiblePanel></Collapsible>diff --git a/apps/web/src/components/project/sync-rules/label-rule-editor.tsx b/apps/web/src/components/project/sync-rules/label-rule-editor.tsxnew file mode 100644index 000000000..789178554--- /dev/null+++ b/apps/web/src/components/project/sync-rules/label-rule-editor.tsx@@ -0,0 +1,200 @@+import { Plus, X } from "lucide-react";+import { useId, useState } from "react";+import { useTranslation } from "react-i18next";+import { Button } from "@/components/ui/button";+import { Checkbox } from "@/components/ui/checkbox";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import type { LabelRule, SyncPreview } from "@/fetchers/integration-sync/types";++export function LabelRuleEditor({+ direction,+ rule,+ labels,+ onChange,+}: {+ direction: "outgoing" | "incoming";+ rule: LabelRule;+ labels: SyncPreview["labels"];+ onChange: (rule: LabelRule) => void;+}) {+ const { t } = useTranslation();+ const id = useId();+ const [labelName, setLabelName] = useState("");+ const outgoing = direction === "outgoing";+ const addLabel = () => {+ const name = labelName.trim();+ if (+ rule.mode !== "labels" ||+ !name ||+ name.length > 128 ||+ rule.labels.includes(name) ||+ rule.labels.length >= 50+ )+ return;+ onChange({ ...rule, labels: [...rule.labels, name] });+ setLabelName("");+ };+ return (+ <fieldset className="space-y-3">+ <legend className="text-sm font-medium">+ {outgoing+ ? t("settings:syncRules.outgoing")+ : t("settings:syncRules.incoming")}+ </legend>+ <p className="text-xs text-muted-foreground">+ {outgoing+ ? t("settings:syncRules.outgoingHint")+ : t("settings:syncRules.incomingHint")}+ </p>+ <Select+ value={rule.mode}+ onValueChange={(mode) => {+ if (mode === "all") onChange({ mode: "all" });+ else if (mode === "labels")+ onChange({ mode: "labels", match: "any", labels: [] });+ }}+ >+ <SelectTrigger+ className="w-full"+ aria-label={+ outgoing+ ? t("settings:syncRules.outgoing")+ : t("settings:syncRules.incoming")+ }+ size="sm"+ >+ <SelectValue>+ {rule.mode === "all"+ ? t("settings:syncRules.all")+ : t("settings:syncRules.filtered")}+ </SelectValue>+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="all">{t("settings:syncRules.all")}</SelectItem>+ <SelectItem value="labels">+ {t("settings:syncRules.filtered")}+ </SelectItem>+ </SelectContent>+ </Select>+ {rule.mode === "labels" && (+ <>+ <Select+ value={rule.match}+ onValueChange={(match) => {+ if (match === "any" || match === "all")+ onChange({ ...rule, match });+ }}+ >+ <SelectTrigger+ size="sm"+ className="w-full"+ aria-label={t("settings:syncRules.matchLabels")}+ >+ <SelectValue>+ {rule.match === "any"+ ? t("settings:syncRules.any")+ : t("settings:syncRules.every")}+ </SelectValue>+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="any">{t("settings:syncRules.any")}</SelectItem>+ <SelectItem value="all">+ {t("settings:syncRules.every")}+ </SelectItem>+ </SelectContent>+ </Select>+ {outgoing ? (+ <div className="max-h-48 space-y-2 overflow-y-auto rounded-lg border border-border p-3">+ {labels.length === 0 && (+ <p className="text-xs text-muted-foreground">+ {t("settings:syncRules.noLabels")}+ </p>+ )}+ {labels.map((label) => (+ <Label+ key={label.id}+ className="flex items-center gap-2 text-sm"+ >+ <Checkbox+ checked={rule.labels.includes(label.id)}+ onCheckedChange={(checked) =>+ onChange({+ ...rule,+ labels: checked+ ? [...rule.labels, label.id]+ : rule.labels.filter((item) => item !== label.id),+ })+ }+ />+ <span className="min-w-0 truncate">{label.name}</span>+ </Label>+ ))}+ </div>+ ) : (+ <div className="space-y-2">+ <Label htmlFor={id} className="sr-only">+ {t("settings:syncRules.repositoryLabel")}+ </Label>+ <div className="flex gap-2">+ <Input+ id={id}+ value={labelName}+ maxLength={128}+ placeholder={t("settings:syncRules.repositoryLabel")}+ onChange={(event) => setLabelName(event.target.value)}+ onKeyDown={(event) => {+ if (event.key === "Enter") {+ event.preventDefault();+ addLabel();+ }+ }}+ />+ <Button+ size="icon"+ variant="outline"+ onClick={addLabel}+ disabled={!labelName.trim() || rule.labels.length >= 50}+ aria-label={t("settings:syncRules.addLabel")}+ >+ <Plus aria-hidden="true" />+ </Button>+ </div>+ <div className="flex flex-wrap gap-2">+ {rule.labels.map((name) => (+ <Button+ key={name}+ size="xs"+ variant="secondary"+ onClick={() =>+ onChange({+ ...rule,+ labels: rule.labels.filter((item) => item !== name),+ })+ }+ aria-label={t("settings:syncRules.removeLabel", { name })}+ >+ {name}+ <X aria-hidden="true" />+ </Button>+ ))}+ </div>+ </div>+ )}+ {rule.labels.length === 0 && (+ <p role="status" className="text-xs text-muted-foreground">+ {t("settings:syncRules.selectLabel")}+ </p>+ )}+ </>+ )}+ </fieldset>+ );+}diff --git a/apps/web/src/components/project/sync-rules/resume-sync-dialog.tsx b/apps/web/src/components/project/sync-rules/resume-sync-dialog.tsxnew file mode 100644index 000000000..1505f06eb--- /dev/null+++ b/apps/web/src/components/project/sync-rules/resume-sync-dialog.tsx@@ -0,0 +1,142 @@+import { useTranslation } from "react-i18next";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogClose,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogPanel,+ DialogPopup,+ DialogTitle,+} from "@/components/ui/dialog";+import type { SyncParams } from "@/fetchers/integration-sync/types";+import { useResumeSync } from "@/hooks/mutations/integration-sync/use-resume-sync";+import { useResumePreview } from "@/hooks/queries/integration-sync/use-resume-preview";++export function ResumeSyncDialog({+ param,+ linkId,+ onClose,+}: {+ param: SyncParams;+ linkId: string;+ onClose: () => void;+}) {+ const { t } = useTranslation();+ const preview = useResumePreview(param, linkId);+ const resume = useResumeSync(param, linkId);+ const data = preview.data;+ const choose = (source: "kaneo" | "provider") => {+ if (data)+ resume.mutate({ source, token: data.token }, { onSuccess: onClose });+ };+ return (+ <Dialog+ open+ onOpenChange={(open) => {+ if (!open && !resume.isPending) onClose();+ }}+ >+ <DialogPopup className="sm:max-w-2xl">+ <DialogHeader>+ <DialogTitle>{t("settings:syncRules.reviewTitle")}</DialogTitle>+ <DialogDescription>+ {t("settings:syncRules.reviewHint")}+ </DialogDescription>+ </DialogHeader>+ <DialogPanel>+ {preview.isPending && (+ <p role="status">{t("common:empty.loading")}</p>+ )}+ {(preview.isError || resume.isError) && (+ <div role="alert" className="space-y-3">+ <p className="text-sm text-destructive">+ {t("settings:syncRules.resumeError")}+ </p>+ <Button+ size="sm"+ variant="outline"+ onClick={() => {+ resume.reset();+ void preview.refetch();+ }}+ >+ {t("settings:syncRules.refreshComparison")}+ </Button>+ </div>+ )}+ {data && (+ <div className="space-y-4">+ <p className="text-sm font-medium">{data.task.title}</p>+ <div className="grid gap-4 sm:grid-cols-2">+ {(["local", "remote"] as const).map((side) => (+ <div+ key={side}+ className="min-w-0 space-y-3 rounded-lg border border-border bg-background p-3"+ >+ <p className="text-xs font-medium text-muted-foreground">+ {side === "local"+ ? "Kaneo"+ : t("settings:syncRules.repository")}+ </p>+ <p+ className={+ data.local.title !== data.remote.title+ ? "break-words text-sm text-warning-foreground"+ : "break-words text-sm"+ }+ >+ {data[side].title}+ </p>+ <p className="text-xs">+ {data[side].state === "closed"+ ? t("settings:syncRules.closed")+ : t("settings:syncRules.open")}+ </p>+ <div className="max-h-64 overflow-y-auto whitespace-pre-wrap break-words text-xs text-muted-foreground">+ {data[side].description ||+ t("settings:syncRules.noDescription")}+ </div>+ </div>+ ))}+ </div>+ </div>+ )}+ </DialogPanel>+ <DialogFooter className="flex-wrap">+ <DialogClose+ disabled={resume.isPending}+ render={<Button variant="ghost" size="sm" />}+ >+ {t("common:actions.cancel")}+ </DialogClose>+ <Button+ variant="outline"+ size="sm"+ disabled={+ !data ||+ preview.isFetching ||+ resume.isPending ||+ resume.isError ||+ preview.isError+ }+ onClick={() => choose("provider")}+ >+ {t("settings:syncRules.useRepository")}+ </Button>+ <Button+ size="sm"+ loading={resume.isPending}+ disabled={+ !data || preview.isFetching || resume.isError || preview.isError+ }+ onClick={() => choose("kaneo")}+ >+ {t("settings:syncRules.useKaneo")}+ </Button>+ </DialogFooter>+ </DialogPopup>+ </Dialog>+ );+}diff --git a/apps/web/src/components/project/sync-rules/rule-summary.tsx b/apps/web/src/components/project/sync-rules/rule-summary.tsxnew file mode 100644index 000000000..7024dee5c--- /dev/null+++ b/apps/web/src/components/project/sync-rules/rule-summary.tsx@@ -0,0 +1,28 @@+import { useTranslation } from "react-i18next";+import type { LabelRule, SyncPreview } from "@/fetchers/integration-sync/types";++export function RuleSummary({+ rule,+ labels,+ outgoing,+}: {+ rule: LabelRule;+ labels: SyncPreview["labels"];+ outgoing: boolean;+}) {+ const { t } = useTranslation();+ if (rule.mode === "all") return <>{t("settings:syncRules.all")}</>;+ const names = rule.labels.map((id) =>+ outgoing+ ? (labels.find((label) => label.id === id)?.name ??+ t("settings:syncRules.unavailableLabel"))+ : id,+ );+ return (+ <>+ {rule.match === "all"+ ? t("settings:syncRules.allSummary", { labels: names.join(", ") })+ : t("settings:syncRules.anySummary", { labels: names.join(", ") })}+ </>+ );+}diff --git a/apps/web/src/components/project/sync-rules/sync-rules-editor.tsx b/apps/web/src/components/project/sync-rules/sync-rules-editor.tsxnew file mode 100644index 000000000..d3a515351--- /dev/null+++ b/apps/web/src/components/project/sync-rules/sync-rules-editor.tsx@@ -0,0 +1,157 @@+import { useState } from "react";+import { useTranslation } from "react-i18next";+import { Button } from "@/components/ui/button";+import type {+ SyncParams,+ SyncPreview,+} from "@/fetchers/integration-sync/types";+import { useSaveSyncRules } from "@/hooks/mutations/integration-sync/use-save-sync-rules";+import { useSyncPreview } from "@/hooks/queries/integration-sync/use-sync-preview";+import { toast } from "@/lib/toast";+import { LabelRuleEditor } from "./label-rule-editor";++export function SyncRulesEditor({+ param,+ saved,+}: {+ param: SyncParams;+ saved: SyncPreview;+}) {+ const { t } = useTranslation();+ const [rules, setRules] = useState(saved.rules);+ const save = useSaveSyncRules(param);+ const dirty = JSON.stringify(rules) !== JSON.stringify(saved.rules);+ const valid = [rules.outgoing, rules.incoming].every(+ (rule) => rule.mode === "all" || rule.labels.length > 0,+ );+ const pendingExports = saved.isActive && saved.willCreate > 0;+ const preview = useSyncPreview(+ param,+ rules,+ (dirty || pendingExports) && valid,+ );+ const impact = dirty ? preview.data : saved;+ return (+ <div className="space-y-5 border-t border-border pt-5">+ <div className="grid gap-6 sm:grid-cols-2">+ <LabelRuleEditor+ direction="outgoing"+ rule={rules.outgoing}+ labels={saved.labels}+ onChange={(outgoing) => {+ save.reset();+ setRules((current) => ({ ...current, outgoing }));+ }}+ />+ <LabelRuleEditor+ direction="incoming"+ rule={rules.incoming}+ labels={saved.labels}+ onChange={(incoming) => {+ save.reset();+ setRules((current) => ({ ...current, incoming }));+ }}+ />+ </div>+ {valid && impact && (+ <div+ className="space-y-3 rounded-lg border border-border bg-background p-3"+ aria-live="polite"+ >+ <p className="text-sm font-medium">+ {t("settings:syncRules.impactTitle")}+ </p>+ <p className="text-xs text-muted-foreground">+ {t("settings:syncRules.impact", {+ matching: impact.matching,+ total: impact.total,+ create: impact.willCreate,+ pause: impact.willPause,+ review: impact.needsReview,+ })}+ </p>+ <p className="text-xs text-muted-foreground">+ {t("settings:syncRules.preserveHint")}+ </p>+ {impact.matchingTasks.length > 0 && (+ <ul className="space-y-1 text-xs text-muted-foreground">+ {impact.matchingTasks.map((task) => (+ <li key={task.id} className="truncate">+ {task.number !== null ? `#${task.number} · ` : ""}+ {task.title}+ </li>+ ))}+ </ul>+ )}+ </div>+ )}+ {preview.isFetching && (+ <p role="status" className="text-xs text-muted-foreground">+ {t("settings:syncRules.previewing")}+ </p>+ )}+ {(preview.isError || save.isError) && (+ <div role="alert" className="space-y-2">+ <p className="text-xs text-destructive">+ {t("settings:syncRules.saveError")}+ </p>+ <Button+ variant="outline"+ size="xs"+ onClick={() => {+ save.reset();+ void preview.refetch();+ }}+ >+ {t("settings:syncRules.refreshPreview")}+ </Button>+ </div>+ )}+ {impact?.missingLabels.length ? (+ <p role="alert" className="text-xs text-destructive">+ {t("settings:syncRules.missingLabels")}+ </p>+ ) : null}+ <div className="flex items-center gap-2">+ <Button+ size="sm"+ loading={save.isPending}+ disabled={+ (!dirty && !pendingExports) ||+ !valid ||+ !preview.data ||+ preview.isFetching ||+ preview.isError ||+ !!preview.data.missingLabels.length+ }+ onClick={() => {+ if (preview.data)+ save.mutate(+ { rules, previewToken: preview.data.previewToken },+ {+ onSuccess: () => toast.success(t("settings:syncRules.saved")),+ },+ );+ }}+ >+ {!dirty && pendingExports+ ? t("settings:syncRules.exportPending")+ : t("settings:syncRules.apply")}+ </Button>+ {dirty && (+ <Button+ variant="ghost"+ size="sm"+ disabled={save.isPending}+ onClick={() => {+ setRules(saved.rules);+ save.reset();+ }}+ >+ {t("common:actions.cancel")}+ </Button>+ )}+ </div>+ </div>+ );+}diff --git a/apps/web/src/components/project/sync-rules/sync-rules-section.tsx b/apps/web/src/components/project/sync-rules/sync-rules-section.tsxnew file mode 100644index 000000000..4873d1f96--- /dev/null+++ b/apps/web/src/components/project/sync-rules/sync-rules-section.tsx@@ -0,0 +1,189 @@+import { Filter, Pause } from "lucide-react";+import { useState } from "react";+import { useTranslation } from "react-i18next";+import { Button } from "@/components/ui/button";+import type { SyncParams } from "@/fetchers/integration-sync/types";+import { useSyncRules } from "@/hooks/queries/integration-sync/use-sync-rules";+import { useWorkspacePermission } from "@/hooks/use-workspace-permission";+import { useUserPreferencesStore } from "@/store/user-preferences";+import { ResumeSyncDialog } from "./resume-sync-dialog";+import { RuleSummary } from "./rule-summary";+import { SyncRulesEditor } from "./sync-rules-editor";++export function SyncRulesSection({ projectId, provider }: SyncParams) {+ const { t } = useTranslation();+ const advanced = useUserPreferencesStore((state) => state.advancedSettings);+ const { canManageSettings, canUpdateTasks } = useWorkspacePermission();+ const canManage = canManageSettings();+ const canResume = canManage && canUpdateTasks();+ const [pages, setPages] = useState<string[]>([]);+ const [reviewLinkId, setReviewLinkId] = useState<string | null>(null);+ const param = { projectId, provider };+ const query = useSyncRules(param, pages.at(-1));+ const data = query.data;+ if (query.isPending)+ return (+ <p role="status" className="text-xs text-muted-foreground">+ {t("settings:syncRules.loading")}+ </p>+ );+ if (!data)+ return (+ <div+ role="alert"+ className="flex items-center justify-between gap-3 rounded-xl border border-border p-4"+ >+ <p className="text-xs text-destructive">+ {t("settings:syncRules.loadError")}+ </p>+ <Button+ size="xs"+ variant="outline"+ onClick={() => void query.refetch()}+ >+ {t("common:error.tryAgain")}+ </Button>+ </div>+ );+ const filtered =+ data.rules.outgoing.mode === "labels" ||+ data.rules.incoming.mode === "labels";+ return (+ <section+ className="space-y-4 rounded-xl border border-border bg-card p-4"+ aria-label={t("settings:syncRules.title")}+ >+ <div className="space-y-1">+ <p className="flex items-center gap-2 text-sm font-medium">+ <Filter aria-hidden="true" className="size-4" />+ {t("settings:syncRules.title")}+ {filtered && (+ <span className="rounded bg-muted px-1.5 py-0.5 text-xs text-muted-foreground">+ {t("settings:syncRules.filteredBadge")}+ </span>+ )}+ </p>+ <p className="text-xs text-muted-foreground">+ {t("settings:syncRules.sharedHint")}+ </p>+ </div>+ <dl className="grid gap-2 text-xs sm:grid-cols-2">+ <div className="space-y-1">+ <dt className="font-medium">{t("settings:syncRules.outgoing")}</dt>+ <dd className="break-words text-muted-foreground">+ <RuleSummary+ outgoing+ rule={data.rules.outgoing}+ labels={data.labels}+ />+ </dd>+ </div>+ <div className="space-y-1">+ <dt className="font-medium">{t("settings:syncRules.incoming")}</dt>+ <dd className="break-words text-muted-foreground">+ <RuleSummary+ outgoing={false}+ rule={data.rules.incoming}+ labels={data.labels}+ />+ </dd>+ </div>+ </dl>+ {!data.isActive && (+ <p role="status" className="text-xs text-muted-foreground">+ {t("settings:syncRules.inactiveHint")}+ </p>+ )}+ {data.missingLabels.length > 0 && (+ <p role="alert" className="text-xs text-destructive">+ {t("settings:syncRules.missingLabels")}+ </p>+ )}+ {advanced && canManage ? (+ <SyncRulesEditor+ key={JSON.stringify(data.rules)}+ param={param}+ saved={data}+ />+ ) : !advanced && canManage ? (+ <p className="text-xs text-muted-foreground">+ {t("settings:syncRules.advancedHint")}+ </p>+ ) : null}+ {data.paused > 0 && (+ <div className="space-y-3 border-t border-border pt-4">+ <p className="flex items-center gap-2 text-sm font-medium">+ <Pause aria-hidden="true" className="size-4" />+ {t("settings:syncRules.pausedCount", { count: data.paused })}+ </p>+ <p className="text-xs text-muted-foreground">+ {t("settings:syncRules.pausedHint")}+ </p>+ <ul className="divide-y divide-border">+ {data.pausedTasks.map((task) => (+ <li+ key={task.linkId}+ className="flex items-center justify-between gap-3 py-2"+ >+ <div className="min-w-0">+ <a+ className="block truncate text-sm hover:underline"+ href={task.url}+ target="_blank"+ rel="noopener noreferrer"+ >+ {task.title}+ </a>+ <p className="text-xs text-muted-foreground">+ {task.eligible+ ? t("settings:syncRules.reviewRequired")+ : t("settings:syncRules.excluded")}+ </p>+ </div>+ {task.eligible && data.isActive && canResume && (+ <Button+ size="xs"+ variant="outline"+ onClick={() => setReviewLinkId(task.linkId)}+ >+ {t("settings:syncRules.review")}+ </Button>+ )}+ </li>+ ))}+ </ul>+ {(pages.length > 0 || data.pausedNextCursor) && (+ <div className="flex gap-2">+ <Button+ size="xs"+ variant="outline"+ disabled={!pages.length}+ onClick={() => setPages((current) => current.slice(0, -1))}+ >+ {t("settings:syncRules.previous")}+ </Button>+ <Button+ size="xs"+ variant="outline"+ disabled={!data.pausedNextCursor}+ onClick={() => {+ if (data.pausedNextCursor)+ setPages((current) => [...current, data.pausedNextCursor!]);+ }}+ >+ {t("settings:syncRules.next")}+ </Button>+ </div>+ )}+ </div>+ )}+ {reviewLinkId && (+ <ResumeSyncDialog+ param={param}+ linkId={reviewLinkId}+ onClose={() => setReviewLinkId(null)}+ />+ )}+ </section>+ );+}diff --git a/apps/web/src/components/project/sync-rules/sync-rules.test.tsx b/apps/web/src/components/project/sync-rules/sync-rules.test.tsxnew file mode 100644index 000000000..a74ba0321--- /dev/null+++ b/apps/web/src/components/project/sync-rules/sync-rules.test.tsx@@ -0,0 +1,229 @@+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import {+ act,+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@testing-library/react";+import {+ afterEach,+ beforeEach,+ describe,+ expect,+ it,+ vi,+} from "vite-plus/test";+import type { SyncPreview } from "@/fetchers/integration-sync/types";+import { useUserPreferencesStore } from "@/store/user-preferences";+import { ResumeSyncDialog } from "./resume-sync-dialog";+import { SyncRulesSection } from "./sync-rules-section";++const mocks = vi.hoisted(() => ({+ get: vi.fn(),+ preview: vi.fn(),+ save: vi.fn(),+ review: vi.fn(),+ resume: vi.fn(),+ canManage: true,+}));+vi.mock("react-i18next", async (importOriginal) => ({+ ...(await importOriginal<typeof import("react-i18next")>()),+ useTranslation: () => ({ t: (key: string) => key }),+}));+vi.mock("@/hooks/use-workspace-permission", () => ({+ useWorkspacePermission: () => ({+ canManageSettings: () => mocks.canManage,+ canUpdateTasks: () => mocks.canManage,+ }),+}));+vi.mock("@/fetchers/integration-sync/get-sync-rules", () => ({+ default: mocks.get,+}));+vi.mock("@/fetchers/integration-sync/preview-sync-rules", () => ({+ default: mocks.preview,+}));+vi.mock("@/fetchers/integration-sync/save-sync-rules", () => ({+ default: mocks.save,+}));+vi.mock("@/fetchers/integration-sync/review-sync-resume", () => ({+ default: mocks.review,+}));+vi.mock("@/fetchers/integration-sync/resume-sync", () => ({+ default: mocks.resume,+}));+vi.mock("@/lib/toast", () => ({ toast: { success: vi.fn() } }));++const param = { projectId: "project-1", provider: "gitea" as const };+const saved: SyncPreview = {+ isActive: true,+ rules: {+ outgoing: { mode: "labels", match: "any", labels: ["label-1"] },+ incoming: { mode: "all" },+ },+ labels: [{ id: "label-1", name: "sync", color: "#123456" }],+ missingLabels: [],+ total: 2,+ matching: 1,+ willCreate: 0,+ willPause: 0,+ needsReview: 0,+ paused: 0,+ matchingTasks: [{ id: "task-1", title: "Matching task", number: 1 }],+ pausedTasks: [],+ pausedNextCursor: null,+ previewToken: "a".repeat(64),+};++beforeEach(() => {+ vi.clearAllMocks();+ mocks.canManage = true;+ useUserPreferencesStore.setState({ advancedSettings: false });+ mocks.get.mockResolvedValue(saved);+ mocks.preview.mockResolvedValue({ ...saved, previewToken: "b".repeat(64) });+ mocks.review.mockResolvedValue({+ task: { id: "task-1", number: 1, title: "Kaneo task" },+ local: { title: "Kaneo title", description: "Local body", state: "open" },+ remote: {+ title: "Repository title",+ description: "Remote body",+ state: "closed",+ },+ token: "c".repeat(64),+ });+});+afterEach(cleanup);+function mount(node = <SyncRulesSection {...param} />) {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ });+ return render(+ <QueryClientProvider client={client}>{node}</QueryClientProvider>,+ );+}++describe("advanced sync settings", () => {+ it("offers an explicit retry for eligible tasks without an issue link", async () => {+ useUserPreferencesStore.setState({ advancedSettings: true });+ mocks.get.mockResolvedValue({ ...saved, willCreate: 1 });+ mount();+ const retry = await screen.findByRole("button", {+ name: "settings:syncRules.exportPending",+ });+ await waitFor(() => expect(retry).toBeEnabled());+ fireEvent.click(retry);+ await waitFor(() =>+ expect(mocks.save).toHaveBeenCalledWith(+ param,+ saved.rules,+ "b".repeat(64),+ ),+ );+ });+ it("shows the active rule while advanced mode is off and preserves it when toggled", async () => {+ mount();+ await screen.findByText("settings:syncRules.advancedHint");+ expect(screen.getByText("settings:syncRules.anySummary")).toBeVisible();+ expect(+ screen.queryByRole("button", { name: "settings:syncRules.apply" }),+ ).toBeNull();+ act(() => useUserPreferencesStore.getState().setAdvancedSettings(true));+ expect(await screen.findByRole("checkbox", { name: "sync" })).toBeChecked();+ act(() => useUserPreferencesStore.getState().setAdvancedSettings(false));+ expect(screen.queryByRole("checkbox", { name: "sync" })).toBeNull();+ expect(mocks.save).not.toHaveBeenCalled();+ });++ it("requires a selected label and a current impact preview before saving", async () => {+ useUserPreferencesStore.setState({ advancedSettings: true });+ mount();+ const checkbox = await screen.findByRole("checkbox", { name: "sync" });+ const apply = screen.getByRole("button", {+ name: "settings:syncRules.apply",+ });+ fireEvent.click(checkbox);+ expect(apply).toBeDisabled();+ expect(mocks.preview).not.toHaveBeenCalled();+ // Restore the saved rule, then add a repository-side filter to create a valid draft.+ fireEvent.click(checkbox);+ fireEvent.click(+ screen.getByRole("combobox", { name: "settings:syncRules.incoming" }),+ { detail: 1 },+ );+ const option = await screen.findByRole("option", {+ name: "settings:syncRules.filtered",+ });+ fireEvent.pointerDown(option);+ fireEvent.mouseDown(option);+ fireEvent.pointerUp(option);+ fireEvent.mouseUp(option);+ fireEvent.click(option, { detail: 1 });+ fireEvent.change(+ await screen.findByRole("textbox", {+ name: "settings:syncRules.repositoryLabel",+ }),+ { target: { value: "ready" } },+ );+ fireEvent.click(+ screen.getByRole("button", { name: "settings:syncRules.addLabel" }),+ );+ await waitFor(() => expect(apply).toBeEnabled());+ fireEvent.click(apply);+ await waitFor(() =>+ expect(mocks.save).toHaveBeenCalledWith(+ param,+ expect.objectContaining({+ incoming: { mode: "labels", match: "any", labels: ["ready"] },+ }),+ "b".repeat(64),+ ),+ );+ });++ it("shows shared rules to members without an editor or resume controls", async () => {+ mocks.canManage = false;+ useUserPreferencesStore.setState({ advancedSettings: true });+ mocks.get.mockResolvedValue({+ ...saved,+ paused: 1,+ pausedTasks: [+ {+ id: "task-1",+ number: 1,+ title: "Paused task",+ linkId: "link-1",+ url: "https://git.example/1",+ eligible: true,+ },+ ],+ });+ mount();+ await screen.findByText("Paused task");+ expect(+ screen.queryByRole("button", { name: "settings:syncRules.review" }),+ ).toBeNull();+ expect(screen.queryByRole("checkbox")).toBeNull();+ });++ it("keeps the comparison open and requires refresh after a failed resume", async () => {+ const onClose = vi.fn();+ mocks.resume.mockRejectedValue(new Error("Comparison changed"));+ mount(<ResumeSyncDialog param={param} linkId="link-1" onClose={onClose} />);+ await screen.findByText("Repository title");+ const keepLocal = screen.getByRole("button", {+ name: "settings:syncRules.useKaneo",+ });+ fireEvent.click(keepLocal);+ await screen.findByText("settings:syncRules.resumeError");+ expect(onClose).not.toHaveBeenCalled();+ expect(keepLocal).toBeDisabled();+ fireEvent.click(+ screen.getByRole("button", {+ name: "settings:syncRules.refreshComparison",+ }),+ );+ await waitFor(() => expect(keepLocal).toBeEnabled());+ expect(mocks.review).toHaveBeenCalledTimes(2);+ });+});diff --git a/apps/web/src/components/settings/advanced-settings-switch.tsx b/apps/web/src/components/settings/advanced-settings-switch.tsxnew file mode 100644index 000000000..4e2cbe985--- /dev/null+++ b/apps/web/src/components/settings/advanced-settings-switch.tsx@@ -0,0 +1,30 @@+import { useId } from "react";+import { useTranslation } from "react-i18next";+import { Label } from "@/components/ui/label";+import { Switch } from "@/components/ui/switch";+import { useUserPreferencesStore } from "@/store/user-preferences";++export function AdvancedSettingsSwitch() {+ const { t } = useTranslation();+ const id = useId();+ const advancedSettings = useUserPreferencesStore(+ (state) => state.advancedSettings,+ );+ const setAdvancedSettings = useUserPreferencesStore(+ (state) => state.setAdvancedSettings,+ );++ return (+ <div className="flex items-center justify-between gap-4 rounded-xl border border-border bg-card p-4">+ <Label htmlFor={id} className="text-sm font-medium">+ {t("settings:advancedSettings")}+ </Label>+ <Switch+ id={id}+ aria-label={t("settings:advancedSettings")}+ checked={advancedSettings}+ onCheckedChange={setAdvancedSettings}+ />+ </div>+ );+}diff --git a/apps/web/src/fetchers/integration-sync/get-sync-rules.ts b/apps/web/src/fetchers/integration-sync/get-sync-rules.tsnew file mode 100644index 000000000..730775f51--- /dev/null+++ b/apps/web/src/fetchers/integration-sync/get-sync-rules.ts@@ -0,0 +1,11 @@+import { client } from "@kaneo/libs";+import { HttpError } from "@/lib/http-error";+import type { SyncParams } from "./types";++export default async function getSyncRules(param: SyncParams, after?: string) {+ const response = await client["integration-sync"].project[":projectId"][+ ":provider"+ ].$get({ param, query: after ? { after } : {} });+ if (!response.ok) throw new HttpError(response.status, await response.text());+ return response.json();+}diff --git a/apps/web/src/fetchers/integration-sync/preview-sync-rules.ts b/apps/web/src/fetchers/integration-sync/preview-sync-rules.tsnew file mode 100644index 000000000..b850b8fd0--- /dev/null+++ b/apps/web/src/fetchers/integration-sync/preview-sync-rules.ts@@ -0,0 +1,14 @@+import { client } from "@kaneo/libs";+import { HttpError } from "@/lib/http-error";+import type { SyncParams, SyncRules } from "./types";++export default async function previewSyncRules(+ param: SyncParams,+ rules: SyncRules,+) {+ const response = await client["integration-sync"].project[":projectId"][+ ":provider"+ ].preview.$post({ param, json: { rules } });+ if (!response.ok) throw new HttpError(response.status, await response.text());+ return response.json();+}diff --git a/apps/web/src/fetchers/integration-sync/resume-sync.ts b/apps/web/src/fetchers/integration-sync/resume-sync.tsnew file mode 100644index 000000000..845790f1d--- /dev/null+++ b/apps/web/src/fetchers/integration-sync/resume-sync.ts@@ -0,0 +1,19 @@+import { client } from "@kaneo/libs";+import { HttpError } from "@/lib/http-error";+import type { SyncParams } from "./types";++export default async function resumeSync(+ param: SyncParams,+ linkId: string,+ token: string,+ source: "kaneo" | "provider",+) {+ const response = await client["integration-sync"].project[":projectId"][+ ":provider"+ ].links[":linkId"].resume.$post({+ param: { ...param, linkId },+ json: { token, source },+ });+ if (!response.ok) throw new HttpError(response.status, await response.text());+ return response.json();+}diff --git a/apps/web/src/fetchers/integration-sync/review-sync-resume.ts b/apps/web/src/fetchers/integration-sync/review-sync-resume.tsnew file mode 100644index 000000000..b94bb2f1f--- /dev/null+++ b/apps/web/src/fetchers/integration-sync/review-sync-resume.ts@@ -0,0 +1,14 @@+import { client } from "@kaneo/libs";+import { HttpError } from "@/lib/http-error";+import type { SyncParams } from "./types";++export default async function reviewSyncResume(+ param: SyncParams,+ linkId: string,+) {+ const response = await client["integration-sync"].project[":projectId"][+ ":provider"+ ].links[":linkId"].review.$get({ param: { ...param, linkId } });+ if (!response.ok) throw new HttpError(response.status, await response.text());+ return response.json();+}diff --git a/apps/web/src/fetchers/integration-sync/save-sync-rules.ts b/apps/web/src/fetchers/integration-sync/save-sync-rules.tsnew file mode 100644index 000000000..7dbb232b9--- /dev/null+++ b/apps/web/src/fetchers/integration-sync/save-sync-rules.ts@@ -0,0 +1,15 @@+import { client } from "@kaneo/libs";+import { HttpError } from "@/lib/http-error";+import type { SyncParams, SyncRules } from "./types";++export default async function saveSyncRules(+ param: SyncParams,+ rules: SyncRules,+ previewToken: string,+) {+ const response = await client["integration-sync"].project[":projectId"][+ ":provider"+ ].$patch({ param, json: { rules, previewToken } });+ if (!response.ok) throw new HttpError(response.status, await response.text());+ return response.json();+}diff --git a/apps/web/src/fetchers/integration-sync/types.ts b/apps/web/src/fetchers/integration-sync/types.tsnew file mode 100644index 000000000..2b5eb7719--- /dev/null+++ b/apps/web/src/fetchers/integration-sync/types.ts@@ -0,0 +1,13 @@+import { client } from "@kaneo/libs";+import type { InferRequestType, InferResponseType } from "hono";++type SyncRoute =+ (typeof client)["integration-sync"]["project"][":projectId"][":provider"];+export type SyncParams = InferRequestType<SyncRoute["$get"]>["param"];+export type SyncRules = InferRequestType<SyncRoute["$patch"]>["json"]["rules"];+export type LabelRule = SyncRules["outgoing"];+export type SyncPreview = InferResponseType<SyncRoute["$get"], 200>;+export type ResumePreview = InferResponseType<+ SyncRoute["links"][":linkId"]["review"]["$get"],+ 200+>;diff --git a/apps/web/src/hooks/mutations/integration-sync/use-resume-sync.ts b/apps/web/src/hooks/mutations/integration-sync/use-resume-sync.tsnew file mode 100644index 000000000..6191a07e6--- /dev/null+++ b/apps/web/src/hooks/mutations/integration-sync/use-resume-sync.ts@@ -0,0 +1,31 @@+import { useMutation, useQueryClient } from "@tanstack/react-query";+import resumeSync from "@/fetchers/integration-sync/resume-sync";+import type { SyncParams } from "@/fetchers/integration-sync/types";++export function useResumeSync(param: SyncParams, linkId: string) {+ const client = useQueryClient();+ return useMutation({+ mutationFn: ({+ token,+ source,+ }: {+ token: string;+ source: "kaneo" | "provider";+ }) => resumeSync(param, linkId, token, source),+ onSuccess: async () => {+ await client.invalidateQueries({+ queryKey: ["integration-sync", param.projectId],+ });+ await client.invalidateQueries({+ queryKey: [+ "integration-sync-review",+ param.projectId,+ param.provider,+ linkId,+ ],+ });+ await client.invalidateQueries({ queryKey: ["external-links"] });+ await client.invalidateQueries({ queryKey: ["tasks"] });+ },+ });+}diff --git a/apps/web/src/hooks/mutations/integration-sync/use-save-sync-rules.ts b/apps/web/src/hooks/mutations/integration-sync/use-save-sync-rules.tsnew file mode 100644index 000000000..56da8567a--- /dev/null+++ b/apps/web/src/hooks/mutations/integration-sync/use-save-sync-rules.ts@@ -0,0 +1,24 @@+import { useMutation, useQueryClient } from "@tanstack/react-query";+import saveSyncRules from "@/fetchers/integration-sync/save-sync-rules";+import type { SyncParams, SyncRules } from "@/fetchers/integration-sync/types";++export function useSaveSyncRules(param: SyncParams) {+ const client = useQueryClient();+ return useMutation({+ mutationFn: ({+ rules,+ previewToken,+ }: {+ rules: SyncRules;+ previewToken: string;+ }) => saveSyncRules(param, rules, previewToken),+ onSuccess: async () => {+ await client.invalidateQueries({+ queryKey: ["integration-sync", param.projectId],+ });+ await client.invalidateQueries({+ queryKey: ["integration-sync-preview", param.projectId],+ });+ },+ });+}diff --git a/apps/web/src/hooks/queries/integration-sync/use-resume-preview.ts b/apps/web/src/hooks/queries/integration-sync/use-resume-preview.tsnew file mode 100644index 000000000..2729c26f3--- /dev/null+++ b/apps/web/src/hooks/queries/integration-sync/use-resume-preview.ts@@ -0,0 +1,17 @@+import { useQuery } from "@tanstack/react-query";+import reviewSyncResume from "@/fetchers/integration-sync/review-sync-resume";+import type { SyncParams } from "@/fetchers/integration-sync/types";++export function useResumePreview(param: SyncParams, linkId: string) {+ return useQuery({+ queryKey: [+ "integration-sync-review",+ param.projectId,+ param.provider,+ linkId,+ ],+ queryFn: () => reviewSyncResume(param, linkId),+ retry: false,+ staleTime: 0,+ });+}diff --git a/apps/web/src/hooks/queries/integration-sync/use-sync-preview.ts b/apps/web/src/hooks/queries/integration-sync/use-sync-preview.tsnew file mode 100644index 000000000..ca952692b--- /dev/null+++ b/apps/web/src/hooks/queries/integration-sync/use-sync-preview.ts@@ -0,0 +1,22 @@+import { useQuery } from "@tanstack/react-query";+import previewSyncRules from "@/fetchers/integration-sync/preview-sync-rules";+import type { SyncParams, SyncRules } from "@/fetchers/integration-sync/types";++export function useSyncPreview(+ param: SyncParams,+ rules: SyncRules,+ enabled: boolean,+) {+ return useQuery({+ queryKey: [+ "integration-sync-preview",+ param.projectId,+ param.provider,+ rules,+ ],+ queryFn: () => previewSyncRules(param, rules),+ enabled,+ retry: false,+ staleTime: 0,+ });+}diff --git a/apps/web/src/hooks/queries/integration-sync/use-sync-rules.ts b/apps/web/src/hooks/queries/integration-sync/use-sync-rules.tsnew file mode 100644index 000000000..b9a38f23b--- /dev/null+++ b/apps/web/src/hooks/queries/integration-sync/use-sync-rules.ts@@ -0,0 +1,15 @@+import { useQuery } from "@tanstack/react-query";+import getSyncRules from "@/fetchers/integration-sync/get-sync-rules";+import type { SyncParams } from "@/fetchers/integration-sync/types";++export function useSyncRules(param: SyncParams, after?: string) {+ return useQuery({+ queryKey: [+ "integration-sync",+ param.projectId,+ param.provider,+ after ?? "",+ ],+ queryFn: () => getSyncRules(param, after),+ });+}diff --git a/apps/web/src/hooks/use-project-websocket-cache.test.tsx b/apps/web/src/hooks/use-project-websocket-cache.test.tsxindex a3b8cba87..56618dd97 100644--- a/apps/web/src/hooks/use-project-websocket-cache.test.tsx+++ b/apps/web/src/hooks/use-project-websocket-cache.test.tsx@@ -483,3 +483,22 @@ it("refreshes workspace label filters when a remote project event changes labels}),);});++it.each([+ "PROJECT_UPDATED",+ "TASK_LABEL_UPDATED",+ "TASK_CREATED",+ "TASK_DELETED",+ "TASK_MOVED",+])("refreshes saved scopes and draft impact after %s", async (type) => {+ renderHook(() => useProjectWebSocket("p"));+ Socket.current.message(type, { taskId: "a" });+ await vi.waitFor(() => {+ expect(mocks.client.invalidateQueries).toHaveBeenCalledWith({+ queryKey: ["integration-sync", "p"],+ });+ expect(mocks.client.invalidateQueries).toHaveBeenCalledWith({+ queryKey: ["integration-sync-preview", "p"],+ });+ });+});diff --git a/apps/web/src/hooks/use-project-websocket.ts b/apps/web/src/hooks/use-project-websocket.tsindex f367cf192..bbeec1291 100644--- a/apps/web/src/hooks/use-project-websocket.ts+++ b/apps/web/src/hooks/use-project-websocket.ts@@ -70,6 +70,23 @@ export function useProjectWebSocket(projectId: string) {sourceTaskId?: string;targetTaskId?: string;}) {+ if (+ [+ "PROJECT_UPDATED",+ "TASK_UPDATED",+ "TASK_LABEL_UPDATED",+ "TASK_CREATED",+ "TASK_DELETED",+ "TASK_MOVED",+ ].includes(message.type)+ ) {+ queryClient.invalidateQueries({+ queryKey: ["integration-sync", projectId],+ });+ queryClient.invalidateQueries({+ queryKey: ["integration-sync-preview", projectId],+ });+ }if (message.type === "PROJECT_UPDATED") {queryClient.invalidateQueries({ queryKey: ["projects"] });queryClient.invalidateQueries({ queryKey: ["labels"] });diff --git a/apps/web/src/routes/_layout/_authenticated/dashboard/settings/account/preferences.tsx b/apps/web/src/routes/_layout/_authenticated/dashboard/settings/account/preferences.tsxindex 061ab9c5f..09d33add5 100644--- a/apps/web/src/routes/_layout/_authenticated/dashboard/settings/account/preferences.tsx+++ b/apps/web/src/routes/_layout/_authenticated/dashboard/settings/account/preferences.tsx@@ -26,6 +26,7 @@ import {WEEK_START_DAYS,type WeekStartDay,} from "@/store/user-preferences";+import { AdvancedSettingsSwitch } from "@/components/settings/advanced-settings-switch";import { SettingsPage } from "@/components/settings/settings-page";import { SettingsSectionHeader } from "@/components/settings/settings-section-header";@@ -368,6 +369,8 @@ function RouteComponent() {</div></div></div>++ <AdvancedSettingsSwitch /></SettingsPage>);}diff --git a/apps/web/src/routes/_layout/_authenticated/dashboard/settings/projects/$projectId/integrations.tsx b/apps/web/src/routes/_layout/_authenticated/dashboard/settings/projects/$projectId/integrations.tsxindex 54440e16a..fa0a84610 100644--- a/apps/web/src/routes/_layout/_authenticated/dashboard/settings/projects/$projectId/integrations.tsx+++ b/apps/web/src/routes/_layout/_authenticated/dashboard/settings/projects/$projectId/integrations.tsx@@ -1,3 +1,4 @@+import { useProjectWebSocket } from "@/hooks/use-project-websocket";import { createFileRoute } from "@tanstack/react-router";import { useTranslation } from "react-i18next";import PageTitle from "@/components/page-title";@@ -15,6 +16,7 @@ export const Route = createFileRoute(function RouteComponent() {const { t } = useTranslation();const { projectId } = Route.useParams();+ useProjectWebSocket(projectId);const { statuses, retry } = useIntegrationStatuses(projectId);return (diff --git a/apps/web/src/routes/_layout/_authenticated/dashboard/settings/workspace/general.tsx b/apps/web/src/routes/_layout/_authenticated/dashboard/settings/workspace/general.tsxindex 917e36b52..66f6400f3 100644--- a/apps/web/src/routes/_layout/_authenticated/dashboard/settings/workspace/general.tsx+++ b/apps/web/src/routes/_layout/_authenticated/dashboard/settings/workspace/general.tsx@@ -41,6 +41,7 @@ import useActiveWorkspace from "@/hooks/queries/workspace/use-active-workspace";import useGetFullWorkspace from "@/hooks/queries/workspace/use-get-full-workspace";import { useWorkspacePermission } from "@/hooks/use-workspace-permission";import { toast } from "@/lib/toast";+import { AdvancedSettingsSwitch } from "@/components/settings/advanced-settings-switch";import { SettingsPage } from "@/components/settings/settings-page";import { SettingsSectionHeader } from "@/components/settings/settings-section-header";@@ -510,6 +511,8 @@ function RouteComponent() {</div>)}+ <AdvancedSettingsSwitch />+<AlertDialogopen={isTransferModalOpen}onOpenChange={setIsTransferModalOpen}diff --git a/apps/web/src/store/user-preferences.ts b/apps/web/src/store/user-preferences.tsindex c81949fc2..6900b7895 100644--- a/apps/web/src/store/user-preferences.ts+++ b/apps/web/src/store/user-preferences.ts@@ -21,6 +21,9 @@ type UserPreferencesStore = {compactMode: boolean;setCompactMode: (compact: boolean) => void;+ advancedSettings: boolean;+ setAdvancedSettings: (enabled: boolean) => void;+showTaskNumbers: boolean;setShowTaskNumbers: (show: boolean) => void;toggleTaskNumbers: () => void;@@ -87,6 +90,9 @@ export const useUserPreferencesStore = create<UserPreferencesStore>()(compactMode: false,setCompactMode: (compact) => set({ compactMode: compact }),+ advancedSettings: false,+ setAdvancedSettings: (enabled) => set({ advancedSettings: enabled }),+showTaskNumbers: true,setShowTaskNumbers: (show) => set({ showTaskNumbers: show }),toggleTaskNumbers: () =>diff --git a/apps/web/src/types/external-link/index.ts b/apps/web/src/types/external-link/index.tsindex 8bfd16ff7..869b2cb54 100644--- a/apps/web/src/types/external-link/index.ts+++ b/apps/web/src/types/external-link/index.ts@@ -1,4 +1,5 @@export type ExternalLinkMetadata = {+ syncFilterPaused?: boolean;state?: string;merged?: boolean;mergedAt?: string;diff --git a/i18n/az-AZ.json b/i18n/az-AZ.jsonindex 316761891..a0f2529e0 100644--- a/i18n/az-AZ.json+++ b/i18n/az-AZ.json@@ -423,6 +423,7 @@}},"settings": {+ "advancedSettings": "Ətraflı parametrlər","account": "Hesab","developer": "Proqramçı","information": "Məlumat",@@ -1872,6 +1873,61 @@"viewPlans": "View plans"},"openFailed": "Couldn't open billing for this workspace"+ },+ "syncRules": {+ "addLabel": "Add label",+ "advancedHint": "Enable Advanced settings in Preferences to edit these rules.",+ "all": "All tasks and issues",+ "allSummary": "All of: {{labels}}",+ "any": "Any selected label",+ "anySummary": "Any of: {{labels}}",+ "apply": "Apply sync rules",+ "closed": "Closed",+ "every": "All selected labels",+ "excluded": "Outside the current rule",+ "filtered": "Only matching labels",+ "filteredBadge": "Filtered by labels",+ "impact": "{{matching}} of {{total}} tasks match. {{create}} tasks will be exported, {{pause}} links will pause, and {{review}} links need review to resume.",+ "impactTitle": "What will change",+ "incoming": "Repository → Kaneo",+ "incomingHint": "Choose which issues can be imported or create tasks. Use exact repository label names. Existing links follow the Kaneo task rule.",+ "loadError": "Sync rules could not be loaded.",+ "loading": "Loading sync rules…",+ "matchLabels": "Label matching",+ "missingLabels": "A selected workspace label is unavailable. Sync stays paused until the rule is repaired.",+ "next": "Next",+ "noDescription": "No description",+ "noLabels": "Create workspace labels before configuring a task filter.",+ "open": "Open",+ "outgoing": "Kaneo → repository",+ "outgoingHint": "Choose which Kaneo tasks can sync. Losing a matching label pauses both directions for an existing task.",+ "paused": "Sync paused",+ "pausedCount_one": "{{count}} paused link",+ "pausedCount_other": "{{count}} paused links",+ "pausedHint": "Records and links are preserved. Tasks that match again need review before syncing resumes.",+ "preserveHint": "Pausing keeps both records and their link. Resuming requires a comparison; historical comments are never replayed.",+ "previewing": "Checking sync impact…",+ "previous": "Previous",+ "refreshComparison": "Refresh comparison",+ "refreshPreview": "Refresh preview",+ "removeLabel": "Remove {{name}}",+ "repository": "Repository",+ "repositoryLabel": "Repository label name",+ "resumeError": "Could not resume. The task, issue or rule may have changed, or the provider is unavailable. Sync remains paused; refresh the comparison.",+ "review": "Review and resume",+ "reviewHint": "Compare the current title, description and open/closed state. Choose which side to keep for these fields. Labels and historical comments remain unchanged.",+ "reviewRequired": "Matches the rule · review required",+ "reviewTitle": "Review before resuming sync",+ "saved": "Sync rules saved",+ "saveError": "Could not apply these rules. The integration or task scope may have changed. Refresh the preview and try again.",+ "selectLabel": "Select at least one label to preview this rule.",+ "sharedHint": "These rules apply to everyone using this project. Hiding advanced settings does not disable them.",+ "title": "Sync scope",+ "unavailableLabel": "Unavailable label",+ "useKaneo": "Keep Kaneo values",+ "useRepository": "Keep repository values",+ "exportPending": "Export matching tasks",+ "inactiveHint": "This integration is paused. No tasks will be exported until it is reactivated."}},"navigation": {diff --git a/i18n/de-DE.json b/i18n/de-DE.jsonindex 954ef0f14..9fe2fcec2 100644--- a/i18n/de-DE.json+++ b/i18n/de-DE.json@@ -423,6 +423,7 @@}},"settings": {+ "advancedSettings": "Erweiterte Einstellungen","account": "Konto","administration": "Administration","developer": "Entwicklung",@@ -1872,6 +1873,61 @@"viewPlans": "View plans"},"openFailed": "Couldn't open billing for this workspace"+ },+ "syncRules": {+ "addLabel": "Label hinzufügen",+ "advancedHint": "Aktiviere die erweiterten Einstellungen unter Präferenzen, um diese Regeln zu bearbeiten.",+ "all": "Alle Aufgaben und Issues",+ "allSummary": "Alle von: {{labels}}",+ "any": "Mindestens ein ausgewähltes Label",+ "anySummary": "Mindestens eines von: {{labels}}",+ "apply": "Synchronisierungsregeln anwenden",+ "closed": "Geschlossen",+ "every": "Alle ausgewählten Labels",+ "excluded": "Außerhalb der aktuellen Regel",+ "filtered": "Nur passende Labels",+ "filteredBadge": "Nach Labels gefiltert",+ "impact": "Passende Aufgaben: {{matching}} / {{total}} · Neue Exporte: {{create}} · Zu pausieren: {{pause}} · Zu prüfen: {{review}}",+ "impactTitle": "Was sich ändern wird",+ "incoming": "Repository → Kaneo",+ "incomingHint": "Wähle, welche Issues importiert werden oder Aufgaben erstellen dürfen. Verwende die exakten Labelnamen im Repository. Bestehende Verknüpfungen folgen der Kaneo-Regel.",+ "loadError": "Synchronisierungsregeln konnten nicht geladen werden.",+ "loading": "Synchronisierungsregeln werden geladen…",+ "matchLabels": "Labelübereinstimmung",+ "missingLabels": "Ein ausgewähltes Workspace-Label ist nicht verfügbar. Die Synchronisierung bleibt pausiert, bis die Regel korrigiert wird.",+ "next": "Weiter",+ "noDescription": "Keine Beschreibung",+ "noLabels": "Erstelle zuerst Workspace-Labels, um einen Aufgabenfilter einzurichten.",+ "open": "Offen",+ "outgoing": "Kaneo → Repository",+ "outgoingHint": "Wähle, welche Kaneo-Aufgaben synchronisiert werden dürfen. Verliert eine verknüpfte Aufgabe ein erforderliches Label, pausieren beide Richtungen.",+ "paused": "Synchronisierung pausiert",+ "pausedCount_one": "{{count}} pausierte Verknüpfung",+ "pausedCount_other": "{{count}} pausierte Verknüpfungen",+ "pausedHint": "Einträge und Verknüpfungen bleiben erhalten. Aufgaben, die wieder passen, müssen vor dem Fortsetzen geprüft werden.",+ "preserveHint": "Beim Pausieren bleiben beide Einträge und ihre Verknüpfung erhalten. Das Fortsetzen erfordert einen Vergleich; alte Kommentare werden nicht erneut übertragen.",+ "previewing": "Synchronisierungsumfang wird geprüft…",+ "previous": "Zurück",+ "refreshComparison": "Vergleich aktualisieren",+ "refreshPreview": "Vorschau aktualisieren",+ "removeLabel": "{{name}} entfernen",+ "repository": "Repository",+ "repositoryLabel": "Labelname im Repository",+ "resumeError": "Fortsetzen fehlgeschlagen. Aufgabe, Issue oder Regel könnten sich geändert haben, oder der Anbieter ist nicht erreichbar. Die Synchronisierung bleibt pausiert; aktualisiere den Vergleich.",+ "review": "Prüfen und fortsetzen",+ "reviewHint": "Vergleiche den aktuellen Titel, die Beschreibung und den Status offen/geschlossen. Wähle, welche Seite diese Felder bestimmen soll. Labels und bisherige Kommentare bleiben unverändert.",+ "reviewRequired": "Passt zur Regel · Prüfung erforderlich",+ "reviewTitle": "Vor dem Fortsetzen vergleichen",+ "saved": "Synchronisierungsregeln gespeichert",+ "saveError": "Diese Regeln konnten nicht angewendet werden. Die Integration oder der Aufgabenumfang könnte sich geändert haben. Aktualisiere die Vorschau und versuche es erneut.",+ "selectLabel": "Wähle mindestens ein Label für die Vorschau.",+ "sharedHint": "Diese Regeln gelten für alle im Projekt. Das Ausblenden erweiterter Einstellungen deaktiviert sie nicht.",+ "title": "Synchronisierungsumfang",+ "unavailableLabel": "Nicht verfügbares Label",+ "useKaneo": "Kaneo-Werte übernehmen",+ "useRepository": "Repository-Werte übernehmen",+ "exportPending": "Passende Aufgaben exportieren",+ "inactiveHint": "Diese Integration ist pausiert. Aufgaben werden erst nach ihrer Reaktivierung exportiert."}},"navigation": {diff --git a/i18n/el-GR.json b/i18n/el-GR.jsonindex 9a8e37117..17710cd3b 100644--- a/i18n/el-GR.json+++ b/i18n/el-GR.json@@ -423,6 +423,7 @@}},"settings": {+ "advancedSettings": "Σύνθετες ρυθμίσεις","account": "Λογαριασμός","developer": "Προγραμματιστής","information": "Πληροφορίες",@@ -1872,6 +1873,61 @@"viewPlans": "View plans"},"openFailed": "Couldn't open billing for this workspace"+ },+ "syncRules": {+ "addLabel": "Add label",+ "advancedHint": "Enable Advanced settings in Preferences to edit these rules.",+ "all": "All tasks and issues",+ "allSummary": "All of: {{labels}}",+ "any": "Any selected label",+ "anySummary": "Any of: {{labels}}",+ "apply": "Apply sync rules",+ "closed": "Closed",+ "every": "All selected labels",+ "excluded": "Outside the current rule",+ "filtered": "Only matching labels",+ "filteredBadge": "Filtered by labels",+ "impact": "{{matching}} of {{total}} tasks match. {{create}} tasks will be exported, {{pause}} links will pause, and {{review}} links need review to resume.",+ "impactTitle": "What will change",+ "incoming": "Repository → Kaneo",+ "incomingHint": "Choose which issues can be imported or create tasks. Use exact repository label names. Existing links follow the Kaneo task rule.",+ "loadError": "Sync rules could not be loaded.",+ "loading": "Loading sync rules…",+ "matchLabels": "Label matching",+ "missingLabels": "A selected workspace label is unavailable. Sync stays paused until the rule is repaired.",+ "next": "Next",+ "noDescription": "No description",+ "noLabels": "Create workspace labels before configuring a task filter.",+ "open": "Open",+ "outgoing": "Kaneo → repository",+ "outgoingHint": "Choose which Kaneo tasks can sync. Losing a matching label pauses both directions for an existing task.",+ "paused": "Sync paused",+ "pausedCount_one": "{{count}} paused link",+ "pausedCount_other": "{{count}} paused links",+ "pausedHint": "Records and links are preserved. Tasks that match again need review before syncing resumes.",+ "preserveHint": "Pausing keeps both records and their link. Resuming requires a comparison; historical comments are never replayed.",+ "previewing": "Checking sync impact…",+ "previous": "Previous",+ "refreshComparison": "Refresh comparison",+ "refreshPreview": "Refresh preview",+ "removeLabel": "Remove {{name}}",+ "repository": "Repository",+ "repositoryLabel": "Repository label name",+ "resumeError": "Could not resume. The task, issue or rule may have changed, or the provider is unavailable. Sync remains paused; refresh the comparison.",+ "review": "Review and resume",+ "reviewHint": "Compare the current title, description and open/closed state. Choose which side to keep for these fields. Labels and historical comments remain unchanged.",+ "reviewRequired": "Matches the rule · review required",+ "reviewTitle": "Review before resuming sync",+ "saved": "Sync rules saved",+ "saveError": "Could not apply these rules. The integration or task scope may have changed. Refresh the preview and try again.",+ "selectLabel": "Select at least one label to preview this rule.",+ "sharedHint": "These rules apply to everyone using this project. Hiding advanced settings does not disable them.",+ "title": "Sync scope",+ "unavailableLabel": "Unavailable label",+ "useKaneo": "Keep Kaneo values",+ "useRepository": "Keep repository values",+ "exportPending": "Export matching tasks",+ "inactiveHint": "This integration is paused. No tasks will be exported until it is reactivated."}},"navigation": {diff --git a/i18n/en-US.json b/i18n/en-US.jsonindex 1dff327db..c1059f8d4 100644--- a/i18n/en-US.json+++ b/i18n/en-US.json@@ -423,6 +423,62 @@}},"settings": {+ "advancedSettings": "Advanced settings",+ "syncRules": {+ "title": "Sync scope",+ "filteredBadge": "Filtered by labels",+ "sharedHint": "These rules apply to everyone using this project. Hiding advanced settings does not disable them.",+ "outgoing": "Kaneo → repository",+ "incoming": "Repository → Kaneo",+ "outgoingHint": "Choose which Kaneo tasks can sync. Losing a matching label pauses both directions for an existing task.",+ "incomingHint": "Choose which issues can be imported or create tasks. Use exact repository label names. Existing links follow the Kaneo task rule.",+ "all": "All tasks and issues",+ "filtered": "Only matching labels",+ "any": "Any selected label",+ "every": "All selected labels",+ "matchLabels": "Label matching",+ "repositoryLabel": "Repository label name",+ "addLabel": "Add label",+ "removeLabel": "Remove {{name}}",+ "noLabels": "Create workspace labels before configuring a task filter.",+ "selectLabel": "Select at least one label to preview this rule.",+ "anySummary": "Any of: {{labels}}",+ "allSummary": "All of: {{labels}}",+ "unavailableLabel": "Unavailable label",+ "impactTitle": "What will change",+ "impact": "Matching tasks: {{matching}} / {{total}} · New exports: {{create}} · Links to pause: {{pause}} · Links to review: {{review}}",+ "preserveHint": "Pausing keeps both records and their link. Resuming requires a comparison; historical comments are never replayed.",+ "previewing": "Checking sync impact…",+ "saveError": "Could not apply these rules. The integration or task scope may have changed. Refresh the preview and try again.",+ "refreshPreview": "Refresh preview",+ "missingLabels": "A selected workspace label is unavailable. Sync stays paused until the rule is repaired.",+ "apply": "Apply sync rules",+ "saved": "Sync rules saved",+ "loading": "Loading sync rules…",+ "loadError": "Sync rules could not be loaded.",+ "advancedHint": "Enable Advanced settings in Preferences to edit these rules.",+ "paused": "Sync paused",+ "pausedCount_one": "{{count}} paused link",+ "pausedCount_other": "{{count}} paused links",+ "pausedHint": "Records and links are preserved. Tasks that match again need review before syncing resumes.",+ "reviewRequired": "Matches the rule · review required",+ "excluded": "Outside the current rule",+ "review": "Review and resume",+ "previous": "Previous",+ "next": "Next",+ "reviewTitle": "Review before resuming sync",+ "reviewHint": "Compare the current title, description and open/closed state. Choose which side to keep for these fields. Labels and historical comments remain unchanged.",+ "resumeError": "Could not resume. The task, issue or rule may have changed, or the provider is unavailable. Sync remains paused; refresh the comparison.",+ "refreshComparison": "Refresh comparison",+ "repository": "Repository",+ "open": "Open",+ "closed": "Closed",+ "noDescription": "No description",+ "useRepository": "Keep repository values",+ "useKaneo": "Keep Kaneo values",+ "exportPending": "Export matching tasks",+ "inactiveHint": "This integration is paused. No tasks will be exported until it is reactivated."+ },"account": "Account","administration": "Administration","developer": "Developer",diff --git a/i18n/es-ES.json b/i18n/es-ES.jsonindex 494cad928..2b3275d2e 100644--- a/i18n/es-ES.json+++ b/i18n/es-ES.json@@ -424,6 +424,7 @@}},"settings": {+ "advancedSettings": "Configuración avanzada","account": "Cuenta","developer": "Desarrollador","information": "Información",@@ -1879,6 +1880,62 @@"viewPlans": "View plans"},"openFailed": "Couldn't open billing for this workspace"+ },+ "syncRules": {+ "addLabel": "Add label",+ "advancedHint": "Enable Advanced settings in Preferences to edit these rules.",+ "all": "All tasks and issues",+ "allSummary": "All of: {{labels}}",+ "any": "Any selected label",+ "anySummary": "Any of: {{labels}}",+ "apply": "Apply sync rules",+ "closed": "Closed",+ "every": "All selected labels",+ "excluded": "Outside the current rule",+ "filtered": "Only matching labels",+ "filteredBadge": "Filtered by labels",+ "impact": "{{matching}} of {{total}} tasks match. {{create}} tasks will be exported, {{pause}} links will pause, and {{review}} links need review to resume.",+ "impactTitle": "What will change",+ "incoming": "Repository → Kaneo",+ "incomingHint": "Choose which issues can be imported or create tasks. Use exact repository label names. Existing links follow the Kaneo task rule.",+ "loadError": "Sync rules could not be loaded.",+ "loading": "Loading sync rules…",+ "matchLabels": "Label matching",+ "missingLabels": "A selected workspace label is unavailable. Sync stays paused until the rule is repaired.",+ "next": "Next",+ "noDescription": "No description",+ "noLabels": "Create workspace labels before configuring a task filter.",+ "open": "Open",+ "outgoing": "Kaneo → repository",+ "outgoingHint": "Choose which Kaneo tasks can sync. Losing a matching label pauses both directions for an existing task.",+ "paused": "Sync paused",+ "pausedCount_many": "{{count}} paused links",+ "pausedCount_one": "{{count}} paused link",+ "pausedCount_other": "{{count}} paused links",+ "pausedHint": "Records and links are preserved. Tasks that match again need review before syncing resumes.",+ "preserveHint": "Pausing keeps both records and their link. Resuming requires a comparison; historical comments are never replayed.",+ "previewing": "Checking sync impact…",+ "previous": "Previous",+ "refreshComparison": "Refresh comparison",+ "refreshPreview": "Refresh preview",+ "removeLabel": "Remove {{name}}",+ "repository": "Repository",+ "repositoryLabel": "Repository label name",+ "resumeError": "Could not resume. The task, issue or rule may have changed, or the provider is unavailable. Sync remains paused; refresh the comparison.",+ "review": "Review and resume",+ "reviewHint": "Compare the current title, description and open/closed state. Choose which side to keep for these fields. Labels and historical comments remain unchanged.",+ "reviewRequired": "Matches the rule · review required",+ "reviewTitle": "Review before resuming sync",+ "saved": "Sync rules saved",+ "saveError": "Could not apply these rules. The integration or task scope may have changed. Refresh the preview and try again.",+ "selectLabel": "Select at least one label to preview this rule.",+ "sharedHint": "These rules apply to everyone using this project. Hiding advanced settings does not disable them.",+ "title": "Sync scope",+ "unavailableLabel": "Unavailable label",+ "useKaneo": "Keep Kaneo values",+ "useRepository": "Keep repository values",+ "exportPending": "Export matching tasks",+ "inactiveHint": "This integration is paused. No tasks will be exported until it is reactivated."}},"navigation": {diff --git a/i18n/fr-FR.json b/i18n/fr-FR.jsonindex cfa6dc9af..ec10040fa 100644--- a/i18n/fr-FR.json+++ b/i18n/fr-FR.json@@ -424,6 +424,7 @@}},"settings": {+ "advancedSettings": "Paramètres avancés","account": "Compte","developer": "Développeur","information": "Information",@@ -1879,6 +1880,62 @@"viewPlans": "View plans"},"openFailed": "Couldn't open billing for this workspace"+ },+ "syncRules": {+ "addLabel": "Add label",+ "advancedHint": "Enable Advanced settings in Preferences to edit these rules.",+ "all": "All tasks and issues",+ "allSummary": "All of: {{labels}}",+ "any": "Any selected label",+ "anySummary": "Any of: {{labels}}",+ "apply": "Apply sync rules",+ "closed": "Closed",+ "every": "All selected labels",+ "excluded": "Outside the current rule",+ "filtered": "Only matching labels",+ "filteredBadge": "Filtered by labels",+ "impact": "{{matching}} of {{total}} tasks match. {{create}} tasks will be exported, {{pause}} links will pause, and {{review}} links need review to resume.",+ "impactTitle": "What will change",+ "incoming": "Repository → Kaneo",+ "incomingHint": "Choose which issues can be imported or create tasks. Use exact repository label names. Existing links follow the Kaneo task rule.",+ "loadError": "Sync rules could not be loaded.",+ "loading": "Loading sync rules…",+ "matchLabels": "Label matching",+ "missingLabels": "A selected workspace label is unavailable. Sync stays paused until the rule is repaired.",+ "next": "Next",+ "noDescription": "No description",+ "noLabels": "Create workspace labels before configuring a task filter.",+ "open": "Open",+ "outgoing": "Kaneo → repository",+ "outgoingHint": "Choose which Kaneo tasks can sync. Losing a matching label pauses both directions for an existing task.",+ "paused": "Sync paused",+ "pausedCount_many": "{{count}} paused links",+ "pausedCount_one": "{{count}} paused link",+ "pausedCount_other": "{{count}} paused links",+ "pausedHint": "Records and links are preserved. Tasks that match again need review before syncing resumes.",+ "preserveHint": "Pausing keeps both records and their link. Resuming requires a comparison; historical comments are never replayed.",+ "previewing": "Checking sync impact…",+ "previous": "Previous",+ "refreshComparison": "Refresh comparison",+ "refreshPreview": "Refresh preview",+ "removeLabel": "Remove {{name}}",+ "repository": "Repository",+ "repositoryLabel": "Repository label name",+ "resumeError": "Could not resume. The task, issue or rule may have changed, or the provider is unavailable. Sync remains paused; refresh the comparison.",+ "review": "Review and resume",+ "reviewHint": "Compare the current title, description and open/closed state. Choose which side to keep for these fields. Labels and historical comments remain unchanged.",+ "reviewRequired": "Matches the rule · review required",+ "reviewTitle": "Review before resuming sync",+ "saved": "Sync rules saved",+ "saveError": "Could not apply these rules. The integration or task scope may have changed. Refresh the preview and try again.",+ "selectLabel": "Select at least one label to preview this rule.",+ "sharedHint": "These rules apply to everyone using this project. Hiding advanced settings does not disable them.",+ "title": "Sync scope",+ "unavailableLabel": "Unavailable label",+ "useKaneo": "Keep Kaneo values",+ "useRepository": "Keep repository values",+ "exportPending": "Export matching tasks",+ "inactiveHint": "This integration is paused. No tasks will be exported until it is reactivated."}},"navigation": {diff --git a/i18n/hi-IN.json b/i18n/hi-IN.jsonindex 1bb9eca02..c1293d270 100644--- a/i18n/hi-IN.json+++ b/i18n/hi-IN.json@@ -423,6 +423,7 @@}},"settings": {+ "advancedSettings": "उन्नत सेटिंग्स","account": "खाता","developer": "डेवलपर","information": "जानकारी",@@ -1872,6 +1873,61 @@"viewPlans": "View plans"},"openFailed": "Couldn't open billing for this workspace"+ },+ "syncRules": {+ "addLabel": "Add label",+ "advancedHint": "Enable Advanced settings in Preferences to edit these rules.",+ "all": "All tasks and issues",+ "allSummary": "All of: {{labels}}",+ "any": "Any selected label",+ "anySummary": "Any of: {{labels}}",+ "apply": "Apply sync rules",+ "closed": "Closed",+ "every": "All selected labels",+ "excluded": "Outside the current rule",+ "filtered": "Only matching labels",+ "filteredBadge": "Filtered by labels",+ "impact": "{{matching}} of {{total}} tasks match. {{create}} tasks will be exported, {{pause}} links will pause, and {{review}} links need review to resume.",+ "impactTitle": "What will change",+ "incoming": "Repository → Kaneo",+ "incomingHint": "Choose which issues can be imported or create tasks. Use exact repository label names. Existing links follow the Kaneo task rule.",+ "loadError": "Sync rules could not be loaded.",+ "loading": "Loading sync rules…",+ "matchLabels": "Label matching",+ "missingLabels": "A selected workspace label is unavailable. Sync stays paused until the rule is repaired.",+ "next": "Next",+ "noDescription": "No description",+ "noLabels": "Create workspace labels before configuring a task filter.",+ "open": "Open",+ "outgoing": "Kaneo → repository",+ "outgoingHint": "Choose which Kaneo tasks can sync. Losing a matching label pauses both directions for an existing task.",+ "paused": "Sync paused",+ "pausedCount_one": "{{count}} paused link",+ "pausedCount_other": "{{count}} paused links",+ "pausedHint": "Records and links are preserved. Tasks that match again need review before syncing resumes.",+ "preserveHint": "Pausing keeps both records and their link. Resuming requires a comparison; historical comments are never replayed.",+ "previewing": "Checking sync impact…",+ "previous": "Previous",+ "refreshComparison": "Refresh comparison",+ "refreshPreview": "Refresh preview",+ "removeLabel": "Remove {{name}}",+ "repository": "Repository",+ "repositoryLabel": "Repository label name",+ "resumeError": "Could not resume. The task, issue or rule may have changed, or the provider is unavailable. Sync remains paused; refresh the comparison.",+ "review": "Review and resume",+ "reviewHint": "Compare the current title, description and open/closed state. Choose which side to keep for these fields. Labels and historical comments remain unchanged.",+ "reviewRequired": "Matches the rule · review required",+ "reviewTitle": "Review before resuming sync",+ "saved": "Sync rules saved",+ "saveError": "Could not apply these rules. The integration or task scope may have changed. Refresh the preview and try again.",+ "selectLabel": "Select at least one label to preview this rule.",+ "sharedHint": "These rules apply to everyone using this project. Hiding advanced settings does not disable them.",+ "title": "Sync scope",+ "unavailableLabel": "Unavailable label",+ "useKaneo": "Keep Kaneo values",+ "useRepository": "Keep repository values",+ "exportPending": "Export matching tasks",+ "inactiveHint": "This integration is paused. No tasks will be exported until it is reactivated."}},"navigation": {diff --git a/i18n/id-ID.json b/i18n/id-ID.jsonindex 5d0cd4f99..250beaf0d 100644--- a/i18n/id-ID.json+++ b/i18n/id-ID.json@@ -422,6 +422,7 @@}},"settings": {+ "advancedSettings": "Pengaturan lanjutan","account": "Akun","developer": "Pengembang","information": "Informasi",@@ -1865,6 +1866,60 @@"viewPlans": "View plans"},"openFailed": "Couldn't open billing for this workspace"+ },+ "syncRules": {+ "addLabel": "Add label",+ "advancedHint": "Enable Advanced settings in Preferences to edit these rules.",+ "all": "All tasks and issues",+ "allSummary": "All of: {{labels}}",+ "any": "Any selected label",+ "anySummary": "Any of: {{labels}}",+ "apply": "Apply sync rules",+ "closed": "Closed",+ "every": "All selected labels",+ "excluded": "Outside the current rule",+ "filtered": "Only matching labels",+ "filteredBadge": "Filtered by labels",+ "impact": "{{matching}} of {{total}} tasks match. {{create}} tasks will be exported, {{pause}} links will pause, and {{review}} links need review to resume.",+ "impactTitle": "What will change",+ "incoming": "Repository → Kaneo",+ "incomingHint": "Choose which issues can be imported or create tasks. Use exact repository label names. Existing links follow the Kaneo task rule.",+ "loadError": "Sync rules could not be loaded.",+ "loading": "Loading sync rules…",+ "matchLabels": "Label matching",+ "missingLabels": "A selected workspace label is unavailable. Sync stays paused until the rule is repaired.",+ "next": "Next",+ "noDescription": "No description",+ "noLabels": "Create workspace labels before configuring a task filter.",+ "open": "Open",+ "outgoing": "Kaneo → repository",+ "outgoingHint": "Choose which Kaneo tasks can sync. Losing a matching label pauses both directions for an existing task.",+ "paused": "Sync paused",+ "pausedCount_other": "{{count}} paused links",+ "pausedHint": "Records and links are preserved. Tasks that match again need review before syncing resumes.",+ "preserveHint": "Pausing keeps both records and their link. Resuming requires a comparison; historical comments are never replayed.",+ "previewing": "Checking sync impact…",+ "previous": "Previous",+ "refreshComparison": "Refresh comparison",+ "refreshPreview": "Refresh preview",+ "removeLabel": "Remove {{name}}",+ "repository": "Repository",+ "repositoryLabel": "Repository label name",+ "resumeError": "Could not resume. The task, issue or rule may have changed, or the provider is unavailable. Sync remains paused; refresh the comparison.",+ "review": "Review and resume",+ "reviewHint": "Compare the current title, description and open/closed state. Choose which side to keep for these fields. Labels and historical comments remain unchanged.",+ "reviewRequired": "Matches the rule · review required",+ "reviewTitle": "Review before resuming sync",+ "saved": "Sync rules saved",+ "saveError": "Could not apply these rules. The integration or task scope may have changed. Refresh the preview and try again.",+ "selectLabel": "Select at least one label to preview this rule.",+ "sharedHint": "These rules apply to everyone using this project. Hiding advanced settings does not disable them.",+ "title": "Sync scope",+ "unavailableLabel": "Unavailable label",+ "useKaneo": "Keep Kaneo values",+ "useRepository": "Keep repository values",+ "exportPending": "Export matching tasks",+ "inactiveHint": "This integration is paused. No tasks will be exported until it is reactivated."}},"navigation": {diff --git a/i18n/it-IT.json b/i18n/it-IT.jsonindex 75840cefe..d8caa3ccd 100644--- a/i18n/it-IT.json+++ b/i18n/it-IT.json@@ -424,6 +424,7 @@}},"settings": {+ "advancedSettings": "Impostazioni avanzate","account": "Account","developer": "Sviluppatore","information": "Informazioni",@@ -1879,6 +1880,62 @@"viewPlans": "View plans"},"openFailed": "Couldn't open billing for this workspace"+ },+ "syncRules": {+ "addLabel": "Add label",+ "advancedHint": "Enable Advanced settings in Preferences to edit these rules.",+ "all": "All tasks and issues",+ "allSummary": "All of: {{labels}}",+ "any": "Any selected label",+ "anySummary": "Any of: {{labels}}",+ "apply": "Apply sync rules",+ "closed": "Closed",+ "every": "All selected labels",+ "excluded": "Outside the current rule",+ "filtered": "Only matching labels",+ "filteredBadge": "Filtered by labels",+ "impact": "{{matching}} of {{total}} tasks match. {{create}} tasks will be exported, {{pause}} links will pause, and {{review}} links need review to resume.",+ "impactTitle": "What will change",+ "incoming": "Repository → Kaneo",+ "incomingHint": "Choose which issues can be imported or create tasks. Use exact repository label names. Existing links follow the Kaneo task rule.",+ "loadError": "Sync rules could not be loaded.",+ "loading": "Loading sync rules…",+ "matchLabels": "Label matching",+ "missingLabels": "A selected workspace label is unavailable. Sync stays paused until the rule is repaired.",+ "next": "Next",+ "noDescription": "No description",+ "noLabels": "Create workspace labels before configuring a task filter.",+ "open": "Open",+ "outgoing": "Kaneo → repository",+ "outgoingHint": "Choose which Kaneo tasks can sync. Losing a matching label pauses both directions for an existing task.",+ "paused": "Sync paused",+ "pausedCount_many": "{{count}} paused links",+ "pausedCount_one": "{{count}} paused link",+ "pausedCount_other": "{{count}} paused links",+ "pausedHint": "Records and links are preserved. Tasks that match again need review before syncing resumes.",+ "preserveHint": "Pausing keeps both records and their link. Resuming requires a comparison; historical comments are never replayed.",+ "previewing": "Checking sync impact…",+ "previous": "Previous",+ "refreshComparison": "Refresh comparison",+ "refreshPreview": "Refresh preview",+ "removeLabel": "Remove {{name}}",+ "repository": "Repository",+ "repositoryLabel": "Repository label name",+ "resumeError": "Could not resume. The task, issue or rule may have changed, or the provider is unavailable. Sync remains paused; refresh the comparison.",+ "review": "Review and resume",+ "reviewHint": "Compare the current title, description and open/closed state. Choose which side to keep for these fields. Labels and historical comments remain unchanged.",+ "reviewRequired": "Matches the rule · review required",+ "reviewTitle": "Review before resuming sync",+ "saved": "Sync rules saved",+ "saveError": "Could not apply these rules. The integration or task scope may have changed. Refresh the preview and try again.",+ "selectLabel": "Select at least one label to preview this rule.",+ "sharedHint": "These rules apply to everyone using this project. Hiding advanced settings does not disable them.",+ "title": "Sync scope",+ "unavailableLabel": "Unavailable label",+ "useKaneo": "Keep Kaneo values",+ "useRepository": "Keep repository values",+ "exportPending": "Export matching tasks",+ "inactiveHint": "This integration is paused. No tasks will be exported until it is reactivated."}},"navigation": {diff --git a/i18n/ja-JP.json b/i18n/ja-JP.jsonindex 8332cf0a7..a6b6ec41f 100644--- a/i18n/ja-JP.json+++ b/i18n/ja-JP.json@@ -422,6 +422,7 @@}},"settings": {+ "advancedSettings": "詳細設定","account": "アカウント","developer": "開発者","information": "基本情報",@@ -1865,6 +1866,60 @@"viewPlans": "View plans"},"openFailed": "Couldn't open billing for this workspace"+ },+ "syncRules": {+ "addLabel": "Add label",+ "advancedHint": "Enable Advanced settings in Preferences to edit these rules.",+ "all": "All tasks and issues",+ "allSummary": "All of: {{labels}}",+ "any": "Any selected label",+ "anySummary": "Any of: {{labels}}",+ "apply": "Apply sync rules",+ "closed": "Closed",+ "every": "All selected labels",+ "excluded": "Outside the current rule",+ "filtered": "Only matching labels",+ "filteredBadge": "Filtered by labels",+ "impact": "{{matching}} of {{total}} tasks match. {{create}} tasks will be exported, {{pause}} links will pause, and {{review}} links need review to resume.",+ "impactTitle": "What will change",+ "incoming": "Repository → Kaneo",+ "incomingHint": "Choose which issues can be imported or create tasks. Use exact repository label names. Existing links follow the Kaneo task rule.",+ "loadError": "Sync rules could not be loaded.",+ "loading": "Loading sync rules…",+ "matchLabels": "Label matching",+ "missingLabels": "A selected workspace label is unavailable. Sync stays paused until the rule is repaired.",+ "next": "Next",+ "noDescription": "No description",+ "noLabels": "Create workspace labels before configuring a task filter.",+ "open": "Open",+ "outgoing": "Kaneo → repository",+ "outgoingHint": "Choose which Kaneo tasks can sync. Losing a matching label pauses both directions for an existing task.",+ "paused": "Sync paused",+ "pausedCount_other": "{{count}} paused links",+ "pausedHint": "Records and links are preserved. Tasks that match again need review before syncing resumes.",+ "preserveHint": "Pausing keeps both records and their link. Resuming requires a comparison; historical comments are never replayed.",+ "previewing": "Checking sync impact…",+ "previous": "Previous",+ "refreshComparison": "Refresh comparison",+ "refreshPreview": "Refresh preview",+ "removeLabel": "Remove {{name}}",+ "repository": "Repository",+ "repositoryLabel": "Repository label name",+ "resumeError": "Could not resume. The task, issue or rule may have changed, or the provider is unavailable. Sync remains paused; refresh the comparison.",+ "review": "Review and resume",+ "reviewHint": "Compare the current title, description and open/closed state. Choose which side to keep for these fields. Labels and historical comments remain unchanged.",+ "reviewRequired": "Matches the rule · review required",+ "reviewTitle": "Review before resuming sync",+ "saved": "Sync rules saved",+ "saveError": "Could not apply these rules. The integration or task scope may have changed. Refresh the preview and try again.",+ "selectLabel": "Select at least one label to preview this rule.",+ "sharedHint": "These rules apply to everyone using this project. Hiding advanced settings does not disable them.",+ "title": "Sync scope",+ "unavailableLabel": "Unavailable label",+ "useKaneo": "Keep Kaneo values",+ "useRepository": "Keep repository values",+ "exportPending": "Export matching tasks",+ "inactiveHint": "This integration is paused. No tasks will be exported until it is reactivated."}},"navigation": {diff --git a/i18n/ko-KR.json b/i18n/ko-KR.jsonindex aaedd4990..5db079387 100644--- a/i18n/ko-KR.json+++ b/i18n/ko-KR.json@@ -422,6 +422,7 @@}},"settings": {+ "advancedSettings": "고급 설정","account": "계정","developer": "개발자","information": "정보",@@ -1865,6 +1866,60 @@"viewPlans": "View plans"},"openFailed": "Couldn't open billing for this workspace"+ },+ "syncRules": {+ "addLabel": "Add label",+ "advancedHint": "Enable Advanced settings in Preferences to edit these rules.",+ "all": "All tasks and issues",+ "allSummary": "All of: {{labels}}",+ "any": "Any selected label",+ "anySummary": "Any of: {{labels}}",+ "apply": "Apply sync rules",+ "closed": "Closed",+ "every": "All selected labels",+ "excluded": "Outside the current rule",+ "filtered": "Only matching labels",+ "filteredBadge": "Filtered by labels",+ "impact": "{{matching}} of {{total}} tasks match. {{create}} tasks will be exported, {{pause}} links will pause, and {{review}} links need review to resume.",+ "impactTitle": "What will change",+ "incoming": "Repository → Kaneo",+ "incomingHint": "Choose which issues can be imported or create tasks. Use exact repository label names. Existing links follow the Kaneo task rule.",+ "loadError": "Sync rules could not be loaded.",+ "loading": "Loading sync rules…",+ "matchLabels": "Label matching",+ "missingLabels": "A selected workspace label is unavailable. Sync stays paused until the rule is repaired.",+ "next": "Next",+ "noDescription": "No description",+ "noLabels": "Create workspace labels before configuring a task filter.",+ "open": "Open",+ "outgoing": "Kaneo → repository",+ "outgoingHint": "Choose which Kaneo tasks can sync. Losing a matching label pauses both directions for an existing task.",+ "paused": "Sync paused",+ "pausedCount_other": "{{count}} paused links",+ "pausedHint": "Records and links are preserved. Tasks that match again need review before syncing resumes.",+ "preserveHint": "Pausing keeps both records and their link. Resuming requires a comparison; historical comments are never replayed.",+ "previewing": "Checking sync impact…",+ "previous": "Previous",+ "refreshComparison": "Refresh comparison",+ "refreshPreview": "Refresh preview",+ "removeLabel": "Remove {{name}}",+ "repository": "Repository",+ "repositoryLabel": "Repository label name",+ "resumeError": "Could not resume. The task, issue or rule may have changed, or the provider is unavailable. Sync remains paused; refresh the comparison.",+ "review": "Review and resume",+ "reviewHint": "Compare the current title, description and open/closed state. Choose which side to keep for these fields. Labels and historical comments remain unchanged.",+ "reviewRequired": "Matches the rule · review required",+ "reviewTitle": "Review before resuming sync",+ "saved": "Sync rules saved",+ "saveError": "Could not apply these rules. The integration or task scope may have changed. Refresh the preview and try again.",+ "selectLabel": "Select at least one label to preview this rule.",+ "sharedHint": "These rules apply to everyone using this project. Hiding advanced settings does not disable them.",+ "title": "Sync scope",+ "unavailableLabel": "Unavailable label",+ "useKaneo": "Keep Kaneo values",+ "useRepository": "Keep repository values",+ "exportPending": "Export matching tasks",+ "inactiveHint": "This integration is paused. No tasks will be exported until it is reactivated."}},"navigation": {diff --git a/i18n/mk-MK.json b/i18n/mk-MK.jsonindex ccdbac066..e7d1fa4fa 100644--- a/i18n/mk-MK.json+++ b/i18n/mk-MK.json@@ -423,6 +423,7 @@}},"settings": {+ "advancedSettings": "Напредни поставки","account": "Сметка","developer": "Програмер","information": "Информации",@@ -1872,6 +1873,61 @@"viewPlans": "View plans"},"openFailed": "Couldn't open billing for this workspace"+ },+ "syncRules": {+ "addLabel": "Add label",+ "advancedHint": "Enable Advanced settings in Preferences to edit these rules.",+ "all": "All tasks and issues",+ "allSummary": "All of: {{labels}}",+ "any": "Any selected label",+ "anySummary": "Any of: {{labels}}",+ "apply": "Apply sync rules",+ "closed": "Closed",+ "every": "All selected labels",+ "excluded": "Outside the current rule",+ "filtered": "Only matching labels",+ "filteredBadge": "Filtered by labels",+ "impact": "{{matching}} of {{total}} tasks match. {{create}} tasks will be exported, {{pause}} links will pause, and {{review}} links need review to resume.",+ "impactTitle": "What will change",+ "incoming": "Repository → Kaneo",+ "incomingHint": "Choose which issues can be imported or create tasks. Use exact repository label names. Existing links follow the Kaneo task rule.",+ "loadError": "Sync rules could not be loaded.",+ "loading": "Loading sync rules…",+ "matchLabels": "Label matching",+ "missingLabels": "A selected workspace label is unavailable. Sync stays paused until the rule is repaired.",+ "next": "Next",+ "noDescription": "No description",+ "noLabels": "Create workspace labels before configuring a task filter.",+ "open": "Open",+ "outgoing": "Kaneo → repository",+ "outgoingHint": "Choose which Kaneo tasks can sync. Losing a matching label pauses both directions for an existing task.",+ "paused": "Sync paused",+ "pausedCount_one": "{{count}} paused link",+ "pausedCount_other": "{{count}} paused links",+ "pausedHint": "Records and links are preserved. Tasks that match again need review before syncing resumes.",+ "preserveHint": "Pausing keeps both records and their link. Resuming requires a comparison; historical comments are never replayed.",+ "previewing": "Checking sync impact…",+ "previous": "Previous",+ "refreshComparison": "Refresh comparison",+ "refreshPreview": "Refresh preview",+ "removeLabel": "Remove {{name}}",+ "repository": "Repository",+ "repositoryLabel": "Repository label name",+ "resumeError": "Could not resume. The task, issue or rule may have changed, or the provider is unavailable. Sync remains paused; refresh the comparison.",+ "review": "Review and resume",+ "reviewHint": "Compare the current title, description and open/closed state. Choose which side to keep for these fields. Labels and historical comments remain unchanged.",+ "reviewRequired": "Matches the rule · review required",+ "reviewTitle": "Review before resuming sync",+ "saved": "Sync rules saved",+ "saveError": "Could not apply these rules. The integration or task scope may have changed. Refresh the preview and try again.",+ "selectLabel": "Select at least one label to preview this rule.",+ "sharedHint": "These rules apply to everyone using this project. Hiding advanced settings does not disable them.",+ "title": "Sync scope",+ "unavailableLabel": "Unavailable label",+ "useKaneo": "Keep Kaneo values",+ "useRepository": "Keep repository values",+ "exportPending": "Export matching tasks",+ "inactiveHint": "This integration is paused. No tasks will be exported until it is reactivated."}},"navigation": {diff --git a/i18n/nl-NL.json b/i18n/nl-NL.jsonindex 8714d152d..523d469e6 100644--- a/i18n/nl-NL.json+++ b/i18n/nl-NL.json@@ -423,6 +423,7 @@}},"settings": {+ "advancedSettings": "Geavanceerde instellingen","account": "Account","developer": "Ontwikkelaar","information": "Informatie",@@ -1872,6 +1873,61 @@"viewPlans": "View plans"},"openFailed": "Couldn't open billing for this workspace"+ },+ "syncRules": {+ "addLabel": "Add label",+ "advancedHint": "Enable Advanced settings in Preferences to edit these rules.",+ "all": "All tasks and issues",+ "allSummary": "All of: {{labels}}",+ "any": "Any selected label",+ "anySummary": "Any of: {{labels}}",+ "apply": "Apply sync rules",+ "closed": "Closed",+ "every": "All selected labels",+ "excluded": "Outside the current rule",+ "filtered": "Only matching labels",+ "filteredBadge": "Filtered by labels",+ "impact": "{{matching}} of {{total}} tasks match. {{create}} tasks will be exported, {{pause}} links will pause, and {{review}} links need review to resume.",+ "impactTitle": "What will change",+ "incoming": "Repository → Kaneo",+ "incomingHint": "Choose which issues can be imported or create tasks. Use exact repository label names. Existing links follow the Kaneo task rule.",+ "loadError": "Sync rules could not be loaded.",+ "loading": "Loading sync rules…",+ "matchLabels": "Label matching",+ "missingLabels": "A selected workspace label is unavailable. Sync stays paused until the rule is repaired.",+ "next": "Next",+ "noDescription": "No description",+ "noLabels": "Create workspace labels before configuring a task filter.",+ "open": "Open",+ "outgoing": "Kaneo → repository",+ "outgoingHint": "Choose which Kaneo tasks can sync. Losing a matching label pauses both directions for an existing task.",+ "paused": "Sync paused",+ "pausedCount_one": "{{count}} paused link",+ "pausedCount_other": "{{count}} paused links",+ "pausedHint": "Records and links are preserved. Tasks that match again need review before syncing resumes.",+ "preserveHint": "Pausing keeps both records and their link. Resuming requires a comparison; historical comments are never replayed.",+ "previewing": "Checking sync impact…",+ "previous": "Previous",+ "refreshComparison": "Refresh comparison",+ "refreshPreview": "Refresh preview",+ "removeLabel": "Remove {{name}}",+ "repository": "Repository",+ "repositoryLabel": "Repository label name",+ "resumeError": "Could not resume. The task, issue or rule may have changed, or the provider is unavailable. Sync remains paused; refresh the comparison.",+ "review": "Review and resume",+ "reviewHint": "Compare the current title, description and open/closed state. Choose which side to keep for these fields. Labels and historical comments remain unchanged.",+ "reviewRequired": "Matches the rule · review required",+ "reviewTitle": "Review before resuming sync",+ "saved": "Sync rules saved",+ "saveError": "Could not apply these rules. The integration or task scope may have changed. Refresh the preview and try again.",+ "selectLabel": "Select at least one label to preview this rule.",+ "sharedHint": "These rules apply to everyone using this project. Hiding advanced settings does not disable them.",+ "title": "Sync scope",+ "unavailableLabel": "Unavailable label",+ "useKaneo": "Keep Kaneo values",+ "useRepository": "Keep repository values",+ "exportPending": "Export matching tasks",+ "inactiveHint": "This integration is paused. No tasks will be exported until it is reactivated."}},"navigation": {diff --git a/i18n/pl-PL.json b/i18n/pl-PL.jsonindex a56b94c7e..113d511af 100644--- a/i18n/pl-PL.json+++ b/i18n/pl-PL.json@@ -982,6 +982,7 @@"unassigned": "usunął(ęła) przypisanie zadania"},"settings": {+ "advancedSettings": "Ustawienia zaawansowane","account": "Konto","apiKey": {"createDialog": {@@ -2443,6 +2444,63 @@"viewPlans": "View plans"},"openFailed": "Couldn't open billing for this workspace"+ },+ "syncRules": {+ "addLabel": "Add label",+ "advancedHint": "Enable Advanced settings in Preferences to edit these rules.",+ "all": "All tasks and issues",+ "allSummary": "All of: {{labels}}",+ "any": "Any selected label",+ "anySummary": "Any of: {{labels}}",+ "apply": "Apply sync rules",+ "closed": "Closed",+ "every": "All selected labels",+ "excluded": "Outside the current rule",+ "filtered": "Only matching labels",+ "filteredBadge": "Filtered by labels",+ "impact": "{{matching}} of {{total}} tasks match. {{create}} tasks will be exported, {{pause}} links will pause, and {{review}} links need review to resume.",+ "impactTitle": "What will change",+ "incoming": "Repository → Kaneo",+ "incomingHint": "Choose which issues can be imported or create tasks. Use exact repository label names. Existing links follow the Kaneo task rule.",+ "loadError": "Sync rules could not be loaded.",+ "loading": "Loading sync rules…",+ "matchLabels": "Label matching",+ "missingLabels": "A selected workspace label is unavailable. Sync stays paused until the rule is repaired.",+ "next": "Next",+ "noDescription": "No description",+ "noLabels": "Create workspace labels before configuring a task filter.",+ "open": "Open",+ "outgoing": "Kaneo → repository",+ "outgoingHint": "Choose which Kaneo tasks can sync. Losing a matching label pauses both directions for an existing task.",+ "paused": "Sync paused",+ "pausedCount_few": "{{count}} paused links",+ "pausedCount_many": "{{count}} paused links",+ "pausedCount_one": "{{count}} paused link",+ "pausedCount_other": "{{count}} paused links",+ "pausedHint": "Records and links are preserved. Tasks that match again need review before syncing resumes.",+ "preserveHint": "Pausing keeps both records and their link. Resuming requires a comparison; historical comments are never replayed.",+ "previewing": "Checking sync impact…",+ "previous": "Previous",+ "refreshComparison": "Refresh comparison",+ "refreshPreview": "Refresh preview",+ "removeLabel": "Remove {{name}}",+ "repository": "Repository",+ "repositoryLabel": "Repository label name",+ "resumeError": "Could not resume. The task, issue or rule may have changed, or the provider is unavailable. Sync remains paused; refresh the comparison.",+ "review": "Review and resume",+ "reviewHint": "Compare the current title, description and open/closed state. Choose which side to keep for these fields. Labels and historical comments remain unchanged.",+ "reviewRequired": "Matches the rule · review required",+ "reviewTitle": "Review before resuming sync",+ "saved": "Sync rules saved",+ "saveError": "Could not apply these rules. The integration or task scope may have changed. Refresh the preview and try again.",+ "selectLabel": "Select at least one label to preview this rule.",+ "sharedHint": "These rules apply to everyone using this project. Hiding advanced settings does not disable them.",+ "title": "Sync scope",+ "unavailableLabel": "Unavailable label",+ "useKaneo": "Keep Kaneo values",+ "useRepository": "Keep repository values",+ "exportPending": "Export matching tasks",+ "inactiveHint": "This integration is paused. No tasks will be exported until it is reactivated."}},"tasks": {diff --git a/i18n/pt-BR.json b/i18n/pt-BR.jsonindex 496238e1b..e400cb49e 100644--- a/i18n/pt-BR.json+++ b/i18n/pt-BR.json@@ -424,6 +424,7 @@}},"settings": {+ "advancedSettings": "Configurações avançadas","account": "Conta","developer": "Desenvolvedor","information": "Informações",@@ -1879,6 +1880,62 @@"viewPlans": "View plans"},"openFailed": "Couldn't open billing for this workspace"+ },+ "syncRules": {+ "addLabel": "Add label",+ "advancedHint": "Enable Advanced settings in Preferences to edit these rules.",+ "all": "All tasks and issues",+ "allSummary": "All of: {{labels}}",+ "any": "Any selected label",+ "anySummary": "Any of: {{labels}}",+ "apply": "Apply sync rules",+ "closed": "Closed",+ "every": "All selected labels",+ "excluded": "Outside the current rule",+ "filtered": "Only matching labels",+ "filteredBadge": "Filtered by labels",+ "impact": "{{matching}} of {{total}} tasks match. {{create}} tasks will be exported, {{pause}} links will pause, and {{review}} links need review to resume.",+ "impactTitle": "What will change",+ "incoming": "Repository → Kaneo",+ "incomingHint": "Choose which issues can be imported or create tasks. Use exact repository label names. Existing links follow the Kaneo task rule.",+ "loadError": "Sync rules could not be loaded.",+ "loading": "Loading sync rules…",+ "matchLabels": "Label matching",+ "missingLabels": "A selected workspace label is unavailable. Sync stays paused until the rule is repaired.",+ "next": "Next",+ "noDescription": "No description",+ "noLabels": "Create workspace labels before configuring a task filter.",+ "open": "Open",+ "outgoing": "Kaneo → repository",+ "outgoingHint": "Choose which Kaneo tasks can sync. Losing a matching label pauses both directions for an existing task.",+ "paused": "Sync paused",+ "pausedCount_many": "{{count}} paused links",+ "pausedCount_one": "{{count}} paused link",+ "pausedCount_other": "{{count}} paused links",+ "pausedHint": "Records and links are preserved. Tasks that match again need review before syncing resumes.",+ "preserveHint": "Pausing keeps both records and their link. Resuming requires a comparison; historical comments are never replayed.",+ "previewing": "Checking sync impact…",+ "previous": "Previous",+ "refreshComparison": "Refresh comparison",+ "refreshPreview": "Refresh preview",+ "removeLabel": "Remove {{name}}",+ "repository": "Repository",+ "repositoryLabel": "Repository label name",+ "resumeError": "Could not resume. The task, issue or rule may have changed, or the provider is unavailable. Sync remains paused; refresh the comparison.",+ "review": "Review and resume",+ "reviewHint": "Compare the current title, description and open/closed state. Choose which side to keep for these fields. Labels and historical comments remain unchanged.",+ "reviewRequired": "Matches the rule · review required",+ "reviewTitle": "Review before resuming sync",+ "saved": "Sync rules saved",+ "saveError": "Could not apply these rules. The integration or task scope may have changed. Refresh the preview and try again.",+ "selectLabel": "Select at least one label to preview this rule.",+ "sharedHint": "These rules apply to everyone using this project. Hiding advanced settings does not disable them.",+ "title": "Sync scope",+ "unavailableLabel": "Unavailable label",+ "useKaneo": "Keep Kaneo values",+ "useRepository": "Keep repository values",+ "exportPending": "Export matching tasks",+ "inactiveHint": "This integration is paused. No tasks will be exported until it is reactivated."}},"navigation": {diff --git a/i18n/ru-RU.json b/i18n/ru-RU.jsonindex 729ebfe18..489fdd286 100644--- a/i18n/ru-RU.json+++ b/i18n/ru-RU.json@@ -425,6 +425,7 @@}},"settings": {+ "advancedSettings": "Расширенные настройки","account": "Аккаунт","developer": "Разработчик","information": "Информация",@@ -1894,6 +1895,63 @@"viewPlans": "View plans"},"openFailed": "Couldn't open billing for this workspace"+ },+ "syncRules": {+ "addLabel": "Add label",+ "advancedHint": "Enable Advanced settings in Preferences to edit these rules.",+ "all": "All tasks and issues",+ "allSummary": "All of: {{labels}}",+ "any": "Any selected label",+ "anySummary": "Any of: {{labels}}",+ "apply": "Apply sync rules",+ "closed": "Closed",+ "every": "All selected labels",+ "excluded": "Outside the current rule",+ "filtered": "Only matching labels",+ "filteredBadge": "Filtered by labels",+ "impact": "{{matching}} of {{total}} tasks match. {{create}} tasks will be exported, {{pause}} links will pause, and {{review}} links need review to resume.",+ "impactTitle": "What will change",+ "incoming": "Repository → Kaneo",+ "incomingHint": "Choose which issues can be imported or create tasks. Use exact repository label names. Existing links follow the Kaneo task rule.",+ "loadError": "Sync rules could not be loaded.",+ "loading": "Loading sync rules…",+ "matchLabels": "Label matching",+ "missingLabels": "A selected workspace label is unavailable. Sync stays paused until the rule is repaired.",+ "next": "Next",+ "noDescription": "No description",+ "noLabels": "Create workspace labels before configuring a task filter.",+ "open": "Open",+ "outgoing": "Kaneo → repository",+ "outgoingHint": "Choose which Kaneo tasks can sync. Losing a matching label pauses both directions for an existing task.",+ "paused": "Sync paused",+ "pausedCount_few": "{{count}} paused links",+ "pausedCount_many": "{{count}} paused links",+ "pausedCount_one": "{{count}} paused link",+ "pausedCount_other": "{{count}} paused links",+ "pausedHint": "Records and links are preserved. Tasks that match again need review before syncing resumes.",+ "preserveHint": "Pausing keeps both records and their link. Resuming requires a comparison; historical comments are never replayed.",+ "previewing": "Checking sync impact…",+ "previous": "Previous",+ "refreshComparison": "Refresh comparison",+ "refreshPreview": "Refresh preview",+ "removeLabel": "Remove {{name}}",+ "repository": "Repository",+ "repositoryLabel": "Repository label name",+ "resumeError": "Could not resume. The task, issue or rule may have changed, or the provider is unavailable. Sync remains paused; refresh the comparison.",+ "review": "Review and resume",+ "reviewHint": "Compare the current title, description and open/closed state. Choose which side to keep for these fields. Labels and historical comments remain unchanged.",+ "reviewRequired": "Matches the rule · review required",+ "reviewTitle": "Review before resuming sync",+ "saved": "Sync rules saved",+ "saveError": "Could not apply these rules. The integration or task scope may have changed. Refresh the preview and try again.",+ "selectLabel": "Select at least one label to preview this rule.",+ "sharedHint": "These rules apply to everyone using this project. Hiding advanced settings does not disable them.",+ "title": "Sync scope",+ "unavailableLabel": "Unavailable label",+ "useKaneo": "Keep Kaneo values",+ "useRepository": "Keep repository values",+ "exportPending": "Export matching tasks",+ "inactiveHint": "This integration is paused. No tasks will be exported until it is reactivated."}},"navigation": {diff --git a/i18n/schema.json b/i18n/schema.jsonindex d62064603..b3cb2cc8b 100644--- a/i18n/schema.json+++ b/i18n/schema.json@@ -1686,6 +1686,239 @@"type": "object","additionalProperties": false,"properties": {+ "advancedSettings": {+ "type": "string"+ },+ "syncRules": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "title": {+ "type": "string"+ },+ "filteredBadge": {+ "type": "string"+ },+ "sharedHint": {+ "type": "string"+ },+ "outgoing": {+ "type": "string"+ },+ "incoming": {+ "type": "string"+ },+ "outgoingHint": {+ "type": "string"+ },+ "incomingHint": {+ "type": "string"+ },+ "all": {+ "type": "string"+ },+ "filtered": {+ "type": "string"+ },+ "any": {+ "type": "string"+ },+ "every": {+ "type": "string"+ },+ "matchLabels": {+ "type": "string"+ },+ "repositoryLabel": {+ "type": "string"+ },+ "addLabel": {+ "type": "string"+ },+ "removeLabel": {+ "type": "string"+ },+ "noLabels": {+ "type": "string"+ },+ "selectLabel": {+ "type": "string"+ },+ "anySummary": {+ "type": "string"+ },+ "allSummary": {+ "type": "string"+ },+ "unavailableLabel": {+ "type": "string"+ },+ "impactTitle": {+ "type": "string"+ },+ "impact": {+ "type": "string"+ },+ "preserveHint": {+ "type": "string"+ },+ "previewing": {+ "type": "string"+ },+ "saveError": {+ "type": "string"+ },+ "refreshPreview": {+ "type": "string"+ },+ "missingLabels": {+ "type": "string"+ },+ "apply": {+ "type": "string"+ },+ "saved": {+ "type": "string"+ },+ "loading": {+ "type": "string"+ },+ "loadError": {+ "type": "string"+ },+ "advancedHint": {+ "type": "string"+ },+ "paused": {+ "type": "string"+ },+ "pausedCount_one": {+ "type": "string"+ },+ "pausedCount_zero": {+ "type": "string"+ },+ "pausedCount_two": {+ "type": "string"+ },+ "pausedCount_few": {+ "type": "string"+ },+ "pausedCount_many": {+ "type": "string"+ },+ "pausedCount_other": {+ "type": "string"+ },+ "pausedHint": {+ "type": "string"+ },+ "reviewRequired": {+ "type": "string"+ },+ "excluded": {+ "type": "string"+ },+ "review": {+ "type": "string"+ },+ "previous": {+ "type": "string"+ },+ "next": {+ "type": "string"+ },+ "reviewTitle": {+ "type": "string"+ },+ "reviewHint": {+ "type": "string"+ },+ "resumeError": {+ "type": "string"+ },+ "refreshComparison": {+ "type": "string"+ },+ "repository": {+ "type": "string"+ },+ "open": {+ "type": "string"+ },+ "closed": {+ "type": "string"+ },+ "noDescription": {+ "type": "string"+ },+ "useRepository": {+ "type": "string"+ },+ "useKaneo": {+ "type": "string"+ },+ "exportPending": {+ "type": "string"+ },+ "inactiveHint": {+ "type": "string"+ }+ },+ "required": [+ "title",+ "filteredBadge",+ "sharedHint",+ "outgoing",+ "incoming",+ "outgoingHint",+ "incomingHint",+ "all",+ "filtered",+ "any",+ "every",+ "matchLabels",+ "repositoryLabel",+ "addLabel",+ "removeLabel",+ "noLabels",+ "selectLabel",+ "anySummary",+ "allSummary",+ "unavailableLabel",+ "impactTitle",+ "impact",+ "preserveHint",+ "previewing",+ "saveError",+ "refreshPreview",+ "missingLabels",+ "apply",+ "saved",+ "loading",+ "loadError",+ "advancedHint",+ "paused",+ "pausedHint",+ "reviewRequired",+ "excluded",+ "review",+ "previous",+ "next",+ "reviewTitle",+ "reviewHint",+ "resumeError",+ "refreshComparison",+ "repository",+ "open",+ "closed",+ "noDescription",+ "useRepository",+ "useKaneo",+ "exportPending",+ "inactiveHint"+ ]+ },"account": {"type": "string"},@@ -7533,6 +7766,8 @@}},"required": [+ "advancedSettings",+ "syncRules","account","administration","developer",diff --git a/i18n/tr-TR.json b/i18n/tr-TR.jsonindex 51f7b73ae..954639956 100644--- a/i18n/tr-TR.json+++ b/i18n/tr-TR.json@@ -423,6 +423,7 @@}},"settings": {+ "advancedSettings": "Gelişmiş ayarlar","account": "Hesap","developer": "Geliştirici","information": "Bilgiler",@@ -1872,6 +1873,61 @@"viewPlans": "View plans"},"openFailed": "Couldn't open billing for this workspace"+ },+ "syncRules": {+ "addLabel": "Add label",+ "advancedHint": "Enable Advanced settings in Preferences to edit these rules.",+ "all": "All tasks and issues",+ "allSummary": "All of: {{labels}}",+ "any": "Any selected label",+ "anySummary": "Any of: {{labels}}",+ "apply": "Apply sync rules",+ "closed": "Closed",+ "every": "All selected labels",+ "excluded": "Outside the current rule",+ "filtered": "Only matching labels",+ "filteredBadge": "Filtered by labels",+ "impact": "{{matching}} of {{total}} tasks match. {{create}} tasks will be exported, {{pause}} links will pause, and {{review}} links need review to resume.",+ "impactTitle": "What will change",+ "incoming": "Repository → Kaneo",+ "incomingHint": "Choose which issues can be imported or create tasks. Use exact repository label names. Existing links follow the Kaneo task rule.",+ "loadError": "Sync rules could not be loaded.",+ "loading": "Loading sync rules…",+ "matchLabels": "Label matching",+ "missingLabels": "A selected workspace label is unavailable. Sync stays paused until the rule is repaired.",+ "next": "Next",+ "noDescription": "No description",+ "noLabels": "Create workspace labels before configuring a task filter.",+ "open": "Open",+ "outgoing": "Kaneo → repository",+ "outgoingHint": "Choose which Kaneo tasks can sync. Losing a matching label pauses both directions for an existing task.",+ "paused": "Sync paused",+ "pausedCount_one": "{{count}} paused link",+ "pausedCount_other": "{{count}} paused links",+ "pausedHint": "Records and links are preserved. Tasks that match again need review before syncing resumes.",+ "preserveHint": "Pausing keeps both records and their link. Resuming requires a comparison; historical comments are never replayed.",+ "previewing": "Checking sync impact…",+ "previous": "Previous",+ "refreshComparison": "Refresh comparison",+ "refreshPreview": "Refresh preview",+ "removeLabel": "Remove {{name}}",+ "repository": "Repository",+ "repositoryLabel": "Repository label name",+ "resumeError": "Could not resume. The task, issue or rule may have changed, or the provider is unavailable. Sync remains paused; refresh the comparison.",+ "review": "Review and resume",+ "reviewHint": "Compare the current title, description and open/closed state. Choose which side to keep for these fields. Labels and historical comments remain unchanged.",+ "reviewRequired": "Matches the rule · review required",+ "reviewTitle": "Review before resuming sync",+ "saved": "Sync rules saved",+ "saveError": "Could not apply these rules. The integration or task scope may have changed. Refresh the preview and try again.",+ "selectLabel": "Select at least one label to preview this rule.",+ "sharedHint": "These rules apply to everyone using this project. Hiding advanced settings does not disable them.",+ "title": "Sync scope",+ "unavailableLabel": "Unavailable label",+ "useKaneo": "Keep Kaneo values",+ "useRepository": "Keep repository values",+ "exportPending": "Export matching tasks",+ "inactiveHint": "This integration is paused. No tasks will be exported until it is reactivated."}},"navigation": {diff --git a/i18n/uk-UA.json b/i18n/uk-UA.jsonindex 628394764..887732c71 100644--- a/i18n/uk-UA.json+++ b/i18n/uk-UA.json@@ -425,6 +425,7 @@}},"settings": {+ "advancedSettings": "Розширені налаштування","account": "Обліковий запис","developer": "Розробник","information": "Інформація",@@ -1886,6 +1887,63 @@"viewPlans": "View plans"},"openFailed": "Couldn't open billing for this workspace"+ },+ "syncRules": {+ "addLabel": "Add label",+ "advancedHint": "Enable Advanced settings in Preferences to edit these rules.",+ "all": "All tasks and issues",+ "allSummary": "All of: {{labels}}",+ "any": "Any selected label",+ "anySummary": "Any of: {{labels}}",+ "apply": "Apply sync rules",+ "closed": "Closed",+ "every": "All selected labels",+ "excluded": "Outside the current rule",+ "filtered": "Only matching labels",+ "filteredBadge": "Filtered by labels",+ "impact": "{{matching}} of {{total}} tasks match. {{create}} tasks will be exported, {{pause}} links will pause, and {{review}} links need review to resume.",+ "impactTitle": "What will change",+ "incoming": "Repository → Kaneo",+ "incomingHint": "Choose which issues can be imported or create tasks. Use exact repository label names. Existing links follow the Kaneo task rule.",+ "loadError": "Sync rules could not be loaded.",+ "loading": "Loading sync rules…",+ "matchLabels": "Label matching",+ "missingLabels": "A selected workspace label is unavailable. Sync stays paused until the rule is repaired.",+ "next": "Next",+ "noDescription": "No description",+ "noLabels": "Create workspace labels before configuring a task filter.",+ "open": "Open",+ "outgoing": "Kaneo → repository",+ "outgoingHint": "Choose which Kaneo tasks can sync. Losing a matching label pauses both directions for an existing task.",+ "paused": "Sync paused",+ "pausedCount_few": "{{count}} paused links",+ "pausedCount_many": "{{count}} paused links",+ "pausedCount_one": "{{count}} paused link",+ "pausedCount_other": "{{count}} paused links",+ "pausedHint": "Records and links are preserved. Tasks that match again need review before syncing resumes.",+ "preserveHint": "Pausing keeps both records and their link. Resuming requires a comparison; historical comments are never replayed.",+ "previewing": "Checking sync impact…",+ "previous": "Previous",+ "refreshComparison": "Refresh comparison",+ "refreshPreview": "Refresh preview",+ "removeLabel": "Remove {{name}}",+ "repository": "Repository",+ "repositoryLabel": "Repository label name",+ "resumeError": "Could not resume. The task, issue or rule may have changed, or the provider is unavailable. Sync remains paused; refresh the comparison.",+ "review": "Review and resume",+ "reviewHint": "Compare the current title, description and open/closed state. Choose which side to keep for these fields. Labels and historical comments remain unchanged.",+ "reviewRequired": "Matches the rule · review required",+ "reviewTitle": "Review before resuming sync",+ "saved": "Sync rules saved",+ "saveError": "Could not apply these rules. The integration or task scope may have changed. Refresh the preview and try again.",+ "selectLabel": "Select at least one label to preview this rule.",+ "sharedHint": "These rules apply to everyone using this project. Hiding advanced settings does not disable them.",+ "title": "Sync scope",+ "unavailableLabel": "Unavailable label",+ "useKaneo": "Keep Kaneo values",+ "useRepository": "Keep repository values",+ "exportPending": "Export matching tasks",+ "inactiveHint": "This integration is paused. No tasks will be exported until it is reactivated."}},"navigation": {diff --git a/i18n/vi-VN.json b/i18n/vi-VN.jsonindex 07fe05feb..13d171edf 100644--- a/i18n/vi-VN.json+++ b/i18n/vi-VN.json@@ -422,6 +422,7 @@}},"settings": {+ "advancedSettings": "Cài đặt nâng cao","account": "Tài khoản","developer": "Nhà phát triển","information": "Thông tin",@@ -1865,6 +1866,60 @@"viewPlans": "View plans"},"openFailed": "Couldn't open billing for this workspace"+ },+ "syncRules": {+ "addLabel": "Add label",+ "advancedHint": "Enable Advanced settings in Preferences to edit these rules.",+ "all": "All tasks and issues",+ "allSummary": "All of: {{labels}}",+ "any": "Any selected label",+ "anySummary": "Any of: {{labels}}",+ "apply": "Apply sync rules",+ "closed": "Closed",+ "every": "All selected labels",+ "excluded": "Outside the current rule",+ "filtered": "Only matching labels",+ "filteredBadge": "Filtered by labels",+ "impact": "{{matching}} of {{total}} tasks match. {{create}} tasks will be exported, {{pause}} links will pause, and {{review}} links need review to resume.",+ "impactTitle": "What will change",+ "incoming": "Repository → Kaneo",+ "incomingHint": "Choose which issues can be imported or create tasks. Use exact repository label names. Existing links follow the Kaneo task rule.",+ "loadError": "Sync rules could not be loaded.",+ "loading": "Loading sync rules…",+ "matchLabels": "Label matching",+ "missingLabels": "A selected workspace label is unavailable. Sync stays paused until the rule is repaired.",+ "next": "Next",+ "noDescription": "No description",+ "noLabels": "Create workspace labels before configuring a task filter.",+ "open": "Open",+ "outgoing": "Kaneo → repository",+ "outgoingHint": "Choose which Kaneo tasks can sync. Losing a matching label pauses both directions for an existing task.",+ "paused": "Sync paused",+ "pausedCount_other": "{{count}} paused links",+ "pausedHint": "Records and links are preserved. Tasks that match again need review before syncing resumes.",+ "preserveHint": "Pausing keeps both records and their link. Resuming requires a comparison; historical comments are never replayed.",+ "previewing": "Checking sync impact…",+ "previous": "Previous",+ "refreshComparison": "Refresh comparison",+ "refreshPreview": "Refresh preview",+ "removeLabel": "Remove {{name}}",+ "repository": "Repository",+ "repositoryLabel": "Repository label name",+ "resumeError": "Could not resume. The task, issue or rule may have changed, or the provider is unavailable. Sync remains paused; refresh the comparison.",+ "review": "Review and resume",+ "reviewHint": "Compare the current title, description and open/closed state. Choose which side to keep for these fields. Labels and historical comments remain unchanged.",+ "reviewRequired": "Matches the rule · review required",+ "reviewTitle": "Review before resuming sync",+ "saved": "Sync rules saved",+ "saveError": "Could not apply these rules. The integration or task scope may have changed. Refresh the preview and try again.",+ "selectLabel": "Select at least one label to preview this rule.",+ "sharedHint": "These rules apply to everyone using this project. Hiding advanced settings does not disable them.",+ "title": "Sync scope",+ "unavailableLabel": "Unavailable label",+ "useKaneo": "Keep Kaneo values",+ "useRepository": "Keep repository values",+ "exportPending": "Export matching tasks",+ "inactiveHint": "This integration is paused. No tasks will be exported until it is reactivated."}},"navigation": {diff --git a/i18n/zh-CN.json b/i18n/zh-CN.jsonindex 2c20a394e..411333c1e 100644--- a/i18n/zh-CN.json+++ b/i18n/zh-CN.json@@ -422,6 +422,7 @@}},"settings": {+ "advancedSettings": "高级设置","account": "账户","developer": "开发者","information": "信息",@@ -1865,6 +1866,60 @@"viewPlans": "View plans"},"openFailed": "Couldn't open billing for this workspace"+ },+ "syncRules": {+ "addLabel": "Add label",+ "advancedHint": "Enable Advanced settings in Preferences to edit these rules.",+ "all": "All tasks and issues",+ "allSummary": "All of: {{labels}}",+ "any": "Any selected label",+ "anySummary": "Any of: {{labels}}",+ "apply": "Apply sync rules",+ "closed": "Closed",+ "every": "All selected labels",+ "excluded": "Outside the current rule",+ "filtered": "Only matching labels",+ "filteredBadge": "Filtered by labels",+ "impact": "{{matching}} of {{total}} tasks match. {{create}} tasks will be exported, {{pause}} links will pause, and {{review}} links need review to resume.",+ "impactTitle": "What will change",+ "incoming": "Repository → Kaneo",+ "incomingHint": "Choose which issues can be imported or create tasks. Use exact repository label names. Existing links follow the Kaneo task rule.",+ "loadError": "Sync rules could not be loaded.",+ "loading": "Loading sync rules…",+ "matchLabels": "Label matching",+ "missingLabels": "A selected workspace label is unavailable. Sync stays paused until the rule is repaired.",+ "next": "Next",+ "noDescription": "No description",+ "noLabels": "Create workspace labels before configuring a task filter.",+ "open": "Open",+ "outgoing": "Kaneo → repository",+ "outgoingHint": "Choose which Kaneo tasks can sync. Losing a matching label pauses both directions for an existing task.",+ "paused": "Sync paused",+ "pausedCount_other": "{{count}} paused links",+ "pausedHint": "Records and links are preserved. Tasks that match again need review before syncing resumes.",+ "preserveHint": "Pausing keeps both records and their link. Resuming requires a comparison; historical comments are never replayed.",+ "previewing": "Checking sync impact…",+ "previous": "Previous",+ "refreshComparison": "Refresh comparison",+ "refreshPreview": "Refresh preview",+ "removeLabel": "Remove {{name}}",+ "repository": "Repository",+ "repositoryLabel": "Repository label name",+ "resumeError": "Could not resume. The task, issue or rule may have changed, or the provider is unavailable. Sync remains paused; refresh the comparison.",+ "review": "Review and resume",+ "reviewHint": "Compare the current title, description and open/closed state. Choose which side to keep for these fields. Labels and historical comments remain unchanged.",+ "reviewRequired": "Matches the rule · review required",+ "reviewTitle": "Review before resuming sync",+ "saved": "Sync rules saved",+ "saveError": "Could not apply these rules. The integration or task scope may have changed. Refresh the preview and try again.",+ "selectLabel": "Select at least one label to preview this rule.",+ "sharedHint": "These rules apply to everyone using this project. Hiding advanced settings does not disable them.",+ "title": "Sync scope",+ "unavailableLabel": "Unavailable label",+ "useKaneo": "Keep Kaneo values",+ "useRepository": "Keep repository values",+ "exportPending": "Export matching tasks",+ "inactiveHint": "This integration is paused. No tasks will be exported until it is reactivated."}},"navigation": {diff --git a/tests/api-integration/integration-sync-providers.test.ts b/tests/api-integration/integration-sync-providers.test.tsnew file mode 100644index 000000000..4d3fbd8c5--- /dev/null+++ b/tests/api-integration/integration-sync-providers.test.ts@@ -0,0 +1,358 @@+import { eq } from "drizzle-orm";+import {+ beforeAll,+ beforeEach,+ describe,+ expect,+ it,+ vi,+} from "vite-plus/test";+import db, { schema } from "../../apps/api/src/database";+import { giteaPlugin } from "../../apps/api/src/plugins/gitea";+import { handleGiteaIssueOpened } from "../../apps/api/src/plugins/gitea/webhooks/issue-opened";+import { githubPlugin } from "../../apps/api/src/plugins/github";+import { handleIssueOpened } from "../../apps/api/src/plugins/github/webhooks/issue-opened";+import { gitlabPlugin } from "../../apps/api/src/plugins/gitlab";+import { handleGitlabIssueOpened } from "../../apps/api/src/plugins/gitlab/webhooks/issue-opened";+import { registerPlugin } from "../../apps/api/src/plugins/registry";+import {+ reconcileProjectSync,+ reconcileTaskSync,+} from "../../apps/api/src/plugins/sync/reconcile";+import { canSyncTask } from "../../apps/api/src/plugins/sync/eligibility";+import { resetTestDatabase } from "./helpers/database";+import {+ createProjectFixture,+ createWorkspaceMember,+} from "./helpers/fixtures";++const mocks = vi.hoisted(() => ({+ githubCreate: vi.fn(),+ giteaCreate: vi.fn(),+ gitlabCreate: vi.fn(),+ update: vi.fn(),+ labels: vi.fn(),+ comment: vi.fn(),+}));+vi.mock("../../apps/api/src/plugins/github/utils/github-app", () => ({+ getGithubApp: () => ({+ getInstallationOctokit: async () => ({+ rest: { issues: { createComment: mocks.comment } },+ }),+ }),+ getVerifiedInstallationOctokit: async () => ({+ rest: {+ issues: {+ create: mocks.githubCreate,+ update: mocks.update,+ createComment: mocks.comment,+ },+ },+ }),+}));+vi.mock("../../apps/api/src/plugins/gitea/utils/gitea-api", () => ({+ createGiteaClient: () => ({+ createIssue: mocks.giteaCreate,+ updateIssue: mocks.update,+ createIssueComment: mocks.comment,+ }),+}));+vi.mock("../../apps/api/src/plugins/gitlab/utils/gitlab-api", () => ({+ createGitlabClient: () => ({+ createIssue: mocks.gitlabCreate,+ updateIssue: mocks.update,+ createIssueNote: mocks.comment,+ }),+}));+vi.mock("../../apps/api/src/plugins/github/utils/labels", () => ({+ addLabelsToIssue: mocks.labels,+}));+vi.mock("../../apps/api/src/plugins/gitea/utils/labels", () => ({+ addLabelsToIssueGitea: mocks.labels,+}));+vi.mock("../../apps/api/src/plugins/gitlab/utils/labels", () => ({+ addLabelsToIssueGitlab: mocks.labels,+}));++beforeAll(() => {+ registerPlugin(githubPlugin);+ registerPlugin(giteaPlugin);+ registerPlugin(gitlabPlugin);+});+beforeEach(async () => {+ await resetTestDatabase();+ vi.clearAllMocks();+ mocks.githubCreate.mockResolvedValue({+ data: {+ number: 12,+ html_url: "https://github.com/team/repo/issues/12",+ title: "Export task",+ state: "open",+ },+ });+ mocks.giteaCreate.mockResolvedValue({+ number: 12,+ html_url: "https://git.example/team/repo/issues/12",+ title: "Export task",+ state: "open",+ });+ mocks.gitlabCreate.mockResolvedValue({+ iid: 12,+ web_url: "https://gitlab.example/team/repo/-/issues/12",+ title: "Export task",+ state: "opened",+ });+});+async function setup(type: "github" | "gitea" | "gitlab") {+ const { workspace } = await createWorkspaceMember();+ const { project, columns } = await createProjectFixture({+ workspaceId: workspace.id,+ });+ const [label] = await db+ .insert(schema.labelTable)+ .values({ workspaceId: workspace.id, name: "export", color: "#123456" })+ .returning();+ const config = {+ repositoryOwner: "team",+ repositoryName: "repo",+ repositoryId: 1,+ installationId: 2,+ verifiedGithubAccountId: "3",+ verifiedByUserId: "test-user",+ baseUrl:+ type === "gitlab" ? "https://gitlab.example" : "https://git.example",+ projectPath: "team/repo",+ accessToken: "fake-test-token",+ commentTaskLinkOnGitHubIssue: false,+ commentTaskLinkOnGiteaIssue: false,+ commentTaskLinkOnGitlabIssue: false,+ syncRules: {+ outgoing: { mode: "labels", match: "any", labels: [label!.id] },+ incoming: { mode: "labels", match: "any", labels: ["export"] },+ },+ };+ const [integration] = await db+ .insert(schema.integrationTable)+ .values({+ type,+ projectId: project.id,+ isActive: true,+ config: JSON.stringify(config),+ })+ .returning();+ await db+ .update(schema.projectTable)+ .set({ lastTaskNumber: 1 })+ .where(eq(schema.projectTable.id, project.id));+ const [task] = await db+ .insert(schema.taskTable)+ .values({+ projectId: project.id,+ title: "Export task",+ number: 1,+ status: "to-do",+ columnId: columns.todo.id,+ })+ .returning();+ const assign = () =>+ db.insert(schema.labelTable).values({+ taskId: task!.id,+ workspaceId: workspace.id,+ name: label!.name,+ color: label!.color,+ });+ return {+ workspace,+ columns,+ project,+ integration: integration!,+ task: task!,+ assign,+ config,+ };+}++describe.each(["github", "gitea", "gitlab"] as const)(+ "%s label-filtered sync",+ (type) => {+ const plugin = {+ github: githubPlugin,+ gitea: giteaPlugin,+ gitlab: gitlabPlugin,+ }[type];+ const create = {+ github: mocks.githubCreate,+ gitea: mocks.giteaCreate,+ gitlab: mocks.gitlabCreate,+ }[type];+ it("exports newly eligible tasks once, including their custom labels", async () => {+ const f = await setup(type);+ await reconcileProjectSync(f.project.id, f.integration.id);+ expect(create).not.toHaveBeenCalled();+ await f.assign();+ await Promise.all([+ reconcileTaskSync(f.project.id, f.task.id),+ reconcileProjectSync(f.project.id, f.integration.id),+ ]);+ expect(create).toHaveBeenCalledOnce();+ expect(mocks.labels.mock.calls[0]!.at(-1)).toContain("export");+ expect(+ await db.query.externalLinkTable.findMany({+ where: eq(schema.externalLinkTable.taskId, f.task.id),+ }),+ ).toHaveLength(1);+ await db+ .delete(schema.labelTable)+ .where(eq(schema.labelTable.taskId, f.task.id));+ await reconcileTaskSync(f.project.id, f.task.id);+ await plugin.onTaskTitleChanged!(+ {+ taskId: f.task.id,+ projectId: f.project.id,+ userId: null,+ oldTitle: "Export task",+ newTitle: "Excluded edit",+ },+ {+ integrationId: f.integration.id,+ projectId: f.project.id,+ config: f.config,+ },+ );+ expect(mocks.update).not.toHaveBeenCalled();+ await f.assign();+ await reconcileTaskSync(f.project.id, f.task.id);+ expect(create).toHaveBeenCalledOnce();+ expect(await canSyncTask(f.task.id, f.integration.id)).toBe(false);+ });++ it("exports completed tasks with a closed issue and current link status", async () => {+ const f = await setup(type);+ await f.assign();+ await db+ .update(schema.taskTable)+ .set({ status: f.columns.done.slug, columnId: f.columns.done.id })+ .where(eq(schema.taskTable.id, f.task.id));+ await reconcileProjectSync(f.project.id, f.integration.id);+ expect(mocks.update).toHaveBeenCalledOnce();+ expect(mocks.update.mock.calls[0]!.at(-1)).toMatchObject(+ type === "gitlab" ? { state_event: "close" } : { state: "closed" },+ );+ const link = await db.query.externalLinkTable.findFirst({+ where: eq(schema.externalLinkTable.taskId, f.task.id),+ });+ expect(JSON.parse(link!.metadata!)).toMatchObject({ state: "closed" });+ });++ it("admits only matching repository issues and deduplicates concurrent webhooks", async () => {+ const f = await setup(type);+ async function receive(labels: string[]) {+ if (type === "github")+ return handleIssueOpened(+ {+ action: "opened",+ installation: { id: 2 },+ issue: {+ number: 99,+ title: "Repository issue",+ body: "Body",+ html_url: "https://github.com/team/repo/issues/99",+ labels,+ user: { login: "author" },+ },+ repository: {+ id: 1,+ owner: { login: "team" },+ name: "repo",+ full_name: "team/repo",+ },+ },+ f.integration.id,+ );+ if (type === "gitea")+ return handleGiteaIssueOpened(+ {+ action: "opened",+ issue: {+ number: 99,+ title: "Repository issue",+ body: "Body",+ html_url: "https://git.example/team/repo/issues/99",+ labels,+ user: { login: "author" },+ },+ repository: {+ owner: { login: "team" },+ name: "repo",+ html_url: "https://git.example/team/repo",+ },+ },+ f.integration.id,+ );+ return handleGitlabIssueOpened(+ {+ object_attributes: {+ iid: 99,+ title: "Repository issue",+ description: "Body",+ url: "https://gitlab.example/team/repo/-/issues/99",+ },+ labels: labels.map((title) => ({ title })),+ project: {+ name: "repo",+ path_with_namespace: "team/repo",+ web_url: "https://gitlab.example/team/repo",+ },+ },+ f.integration.id,+ );+ }+ await receive(["other"]);+ expect(await db.query.externalLinkTable.findMany()).toHaveLength(0);+ await Promise.all([receive(["export"]), receive(["export"])]);+ const links = await db.query.externalLinkTable.findMany();+ expect(links).toHaveLength(1);+ expect(links[0]!.externalId).toBe("99");+ expect(await canSyncTask(links[0]!.taskId, f.integration.id)).toBe(true);+ expect(+ await db.query.taskTable.findMany({+ where: eq(schema.taskTable.projectId, f.project.id),+ }),+ ).toHaveLength(2);+ });+ },+);++it("exports a burst larger than the database pool without exhausting lease connections", async () => {+ const f = await setup("gitea");+ const tasks = await db+ .insert(schema.taskTable)+ .values(+ Array.from({ length: 20 }, (_, index) => ({+ projectId: f.project.id,+ number: index + 2,+ title: `Burst task ${index}`,+ })),+ )+ .returning();+ await db.insert(schema.labelTable).values(+ tasks.map((task) => ({+ workspaceId: f.workspace.id,+ taskId: task.id,+ name: "export",+ color: "#123456",+ })),+ );+ let number = 100;+ mocks.giteaCreate.mockImplementation(async () => ({+ number: ++number,+ title: "Burst issue",+ html_url: `https://git.example/team/repo/issues/${number}`,+ state: "open",+ }));+ await Promise.all(+ tasks.map((task) => reconcileTaskSync(f.project.id, task.id)),+ );+ expect(mocks.giteaCreate).toHaveBeenCalledTimes(20);+ expect(await db.query.externalLinkTable.findMany()).toHaveLength(20);+});diff --git a/tests/api-integration/integration-sync-rules.test.ts b/tests/api-integration/integration-sync-rules.test.tsnew file mode 100644index 000000000..0b3b86913--- /dev/null+++ b/tests/api-integration/integration-sync-rules.test.ts@@ -0,0 +1,494 @@+import { and, eq } from "drizzle-orm";+import { beforeEach, describe, expect, it, vi } from "vite-plus/test";+import db, { schema } from "../../apps/api/src/database";+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 { resumeSync } from "../../apps/api/src/integration-sync/controllers/resume-sync";+import { reviewSyncResume } from "../../apps/api/src/integration-sync/controllers/review-resume";+import { saveSyncRules } from "../../apps/api/src/integration-sync/controllers/save-rules";+import { createExternalLink } from "../../apps/api/src/plugins/github/services/link-manager";+import { withIntegrationTask } from "../../apps/api/src/plugins/github/services/integration-task-scope";+import { withTaskSyncCreation } from "../../apps/api/src/plugins/sync/create-task-issue";+import {+ canSyncTask,+ taskMatchesRule,+} from "../../apps/api/src/plugins/sync/eligibility";+import {+ acceptsIssue,+ defaultSyncRules,+ isSyncPaused,+ readSyncRules,+ 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";++const provider = vi.hoisted(() => ({ read: vi.fn(), write: vi.fn() }));+vi.mock("../../apps/api/src/plugins/sync/provider-issue", () => ({+ providerIssue: async () => provider,+}));++beforeEach(async () => {+ await resetTestDatabase();+ vi.clearAllMocks();+ provider.read.mockResolvedValue({+ title: "Repository title",+ description: "Repository body",+ state: "closed",+ updatedAt: "2026-01-01T00:00:00Z",+ });+ provider.write.mockResolvedValue({ updatedAt: "2026-01-02T00:00:00Z" });+});++async function setup(role = "owner") {+ const member = await createWorkspaceMember({ role });+ const { project, columns } = await createProjectFixture({+ workspaceId: member.workspace.id,+ });+ const [integration] = await db+ .insert(schema.integrationTable)+ .values({+ projectId: project.id,+ type: "gitea",+ isActive: true,+ config: JSON.stringify({+ baseUrl: "https://git.example",+ accessToken: "test-only",+ repositoryOwner: "team",+ repositoryName: "repo",+ }),+ })+ .returning();+ const [label] = await db+ .insert(schema.labelTable)+ .values({+ workspaceId: member.workspace.id,+ name: "sync",+ color: "#123456",+ })+ .returning();+ const [task] = await db+ .insert(schema.taskTable)+ .values({+ projectId: project.id,+ title: "Kaneo title",+ description: "Kaneo body",+ status: columns.todo.slug,+ columnId: columns.todo.id,+ number: 1,+ })+ .returning();+ mockAuthenticatedSession(member.user);+ const { app } = createApp();+ const path = `/api/integration-sync/project/${project.id}/gitea`;+ const rules: SyncRules = {+ outgoing: { mode: "labels", match: "any", labels: [label.id] },+ incoming: { mode: "labels", match: "any", labels: ["sync"] },+ };+ const assign = () =>+ db.insert(schema.labelTable).values({+ taskId: task.id,+ workspaceId: member.workspace.id,+ name: label.name,+ color: label.color,+ });+ const link = async (paused = false) =>+ (+ await db+ .insert(schema.externalLinkTable)+ .values({+ taskId: task.id,+ integrationId: integration.id,+ resourceType: "issue",+ externalId: "9",+ url: "https://git.example/team/repo/issues/9",+ metadata: JSON.stringify({+ syncFilterPaused: paused,+ retained: "preserve-me",+ }),+ })+ .returning()+ )[0]!;+ const request = (suffix: string, method: string, body?: unknown) =>+ app.request(path + suffix, {+ method,+ headers: { "Content-Type": "application/json" },+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),+ });+ const setRules = () =>+ db+ .update(schema.integrationTable)+ .set({+ config: JSON.stringify({+ ...JSON.parse(integration.config),+ syncRules: rules,+ }),+ })+ .where(eq(schema.integrationTable.id, integration.id));+ const preview = async (selected = rules) =>+ previewSyncRules(await getSyncIntegration(project.id, "gitea"), selected);+ return {+ ...member,+ project,+ columns,+ integration,+ label,+ task,+ rules,+ assign,+ link,+ request,+ setRules,+ preview,+ };+}++describe("integration label policies", () => {+ it("keeps legacy sync unrestricted and rejects malformed policies", () => {+ expect(readSyncRules("{}")).toEqual(defaultSyncRules);+ expect(+ readSyncRules('{"syncRules":{"outgoing":{"mode":"labels","labels":[]}}}'),+ ).toBeNull();+ expect(+ acceptsIssue(+ {+ syncRules: {+ ...defaultSyncRules,+ incoming: { mode: "labels", match: "all", labels: ["one", "two"] },+ },+ },+ [{ name: "one" }, "two"],+ ),+ ).toBe(true);+ expect(+ acceptsIssue(+ {+ syncRules: {+ ...defaultSyncRules,+ incoming: { mode: "labels", match: "all", labels: ["one", "two"] },+ },+ },+ ["one"],+ ),+ ).toBe(false);+ });++ it("previews any/all matching, missing labels, and new exports", async () => {+ const f = await setup();+ await f.assign();+ const [second] = await db+ .insert(schema.labelTable)+ .values({ workspaceId: f.workspace.id, name: "ready", color: "#123456" })+ .returning();+ const any = {+ ...f.rules,+ outgoing: {+ mode: "labels" as const,+ match: "any" as const,+ labels: [f.label.id, second!.id],+ },+ };+ expect(await f.preview(any)).toMatchObject({+ total: 1,+ matching: 1,+ willCreate: 1,+ });+ expect(+ await f.preview({ ...any, outgoing: { ...any.outgoing, match: "all" } }),+ ).toMatchObject({ matching: 0 });+ expect(+ await f.preview({+ ...any,+ outgoing: { ...any.outgoing, labels: [f.label.id, "missing"] },+ }),+ ).toMatchObject({ matching: 0, missingLabels: ["missing"] });+ });++ it("uses stable workspace label IDs across renames and fails closed during deletion", async () => {+ const f = await setup();+ await f.assign();+ await db+ .update(schema.labelTable)+ .set({ name: "renamed" })+ .where(+ and(+ eq(schema.labelTable.workspaceId, f.workspace.id),+ eq(schema.labelTable.name, "sync"),+ ),+ );+ expect(+ await taskMatchesRule(f.task.id, f.project.id, f.rules.outgoing),+ ).toBe(true);+ await db+ .update(schema.labelTable)+ .set({ deletionStartedAt: new Date() })+ .where(eq(schema.labelTable.id, f.label.id));+ expect(+ await taskMatchesRule(f.task.id, f.project.id, f.rules.outgoing),+ ).toBe(false);+ });++ it("rejects changed impact rather than applying a stale preview", async () => {+ const f = await setup();+ const preview = await f.preview();+ await f.assign();+ const response = await f.request("", "PATCH", {+ rules: f.rules,+ previewToken: preview.previewToken,+ });+ expect(response.status).toBe(409);+ expect(+ readSyncRules((await getSyncIntegration(f.project.id, "gitea")).config),+ ).toEqual(defaultSyncRules);+ });++ it("rejects labels belonging to another workspace", async () => {+ const f = await setup();+ const other = await createWorkspaceMember();+ const [label] = await db+ .insert(schema.labelTable)+ .values({+ workspaceId: other.workspace.id,+ name: "sync",+ color: "#000000",+ })+ .returning();+ const rules = {+ ...f.rules,+ outgoing: {+ mode: "labels" as const,+ match: "any" as const,+ labels: [label!.id],+ },+ };+ const preview = await f.preview(rules);+ expect(preview.labels.some((item) => item.id === label!.id)).toBe(false);+ expect(+ (+ await f.request("", "PATCH", {+ rules,+ previewToken: preview.previewToken,+ })+ ).status,+ ).toBe(400);+ });++ it("lets members inspect rules but reserves preview and writes for settings managers", async () => {+ const f = await setup("member");+ expect((await f.request("", "GET")).status).toBe(200);+ expect(+ (await f.request("/preview", "POST", { rules: f.rules })).status,+ ).toBe(403);+ expect(+ (+ await f.request("", "PATCH", {+ rules: f.rules,+ previewToken: "a".repeat(64),+ })+ ).status,+ ).toBe(403);+ const outsider = await createWorkspaceMember({ role: "owner" });+ mockAuthenticatedSession(outsider.user);+ expect((await f.request("", "GET")).status).toBe(403);+ });++ it("pauses excluded links, preserves metadata, and never silently resumes", async () => {+ const f = await setup();+ const link = await f.link();+ const preview = await f.preview();+ expect(preview).toMatchObject({ willPause: 1, matching: 0 });+ await saveSyncRules(f.project.id, "gitea", f.rules, preview.previewToken);+ expect(await canSyncTask(f.task.id, f.integration.id)).toBe(false);+ let stored = await db.query.externalLinkTable.findFirst({+ where: eq(schema.externalLinkTable.id, link.id),+ });+ expect(JSON.parse(stored!.metadata!)).toMatchObject({+ syncFilterPaused: true,+ retained: "preserve-me",+ });+ 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) =>+ tx+ .update(schema.taskTable)+ .set({ title: "Should not be applied" })+ .where(eq(schema.taskTable.id, f.task.id)),+ );+ expect(+ (await db.query.taskTable.findFirst({+ where: eq(schema.taskTable.id, f.task.id),+ }))!.title,+ ).toBe("Kaneo title");+ stored = await db.query.externalLinkTable.findFirst({+ where: eq(schema.externalLinkTable.id, link.id),+ });+ expect(isSyncPaused(stored!.metadata)).toBe(true);+ });++ it("pauses a linked task when its last qualifying label is removed", async () => {+ const f = await setup();+ await f.assign();+ await f.setRules();+ const link = await f.link();+ expect(await canSyncTask(f.task.id, f.integration.id)).toBe(true);+ await db+ .delete(schema.labelTable)+ .where(eq(schema.labelTable.taskId, f.task.id));+ expect(await canSyncTask(f.task.id, f.integration.id)).toBe(false);+ expect(+ isSyncPaused(+ (await db.query.externalLinkTable.findFirst({+ where: eq(schema.externalLinkTable.id, link.id),+ }))!.metadata,+ ),+ ).toBe(true);+ });++ it("counts tasks once even when older duplicate issue links exist", async () => {+ const f = await setup();+ await f.link();+ await f.link(true);+ expect(await f.preview()).toMatchObject({+ total: 1,+ paused: 1,+ willPause: 0,+ });+ });++ it("serializes simultaneous task-created and label events", async () => {+ const f = await setup();+ await f.assign();+ await f.setRules();+ const binding = await getSyncIntegration(f.project.id, "gitea");+ const event = {+ taskId: f.task.id,+ projectId: f.project.id,+ title: "Stale queued title",+ number: 1,+ status: "to-do",+ userId: f.user.id,+ description: null,+ priority: null,+ };+ const context = {+ integrationId: f.integration.id,+ projectId: f.project.id,+ config: JSON.parse(binding.config),+ };+ const create = vi.fn(async (current: typeof event) => {+ expect(current.title).toBe("Kaneo title");+ const existing = await db.query.externalLinkTable.findFirst({+ where: eq(schema.externalLinkTable.taskId, f.task.id),+ });+ if (!existing)+ await createExternalLink({+ taskId: f.task.id,+ integrationId: f.integration.id,+ resourceType: "issue",+ externalId: "123",+ url: "https://git.example/123",+ });+ });+ await Promise.all([+ withTaskSyncCreation(event, context, create),+ withTaskSyncCreation(event, context, create),+ ]);+ expect(create).toHaveBeenCalledOnce();+ expect(+ await db.query.externalLinkTable.findMany({+ where: eq(schema.externalLinkTable.taskId, f.task.id),+ }),+ ).toHaveLength(1);+ });+});++describe("reviewed sync resume", () => {+ async function paused() {+ const f = await setup();+ await f.assign();+ await f.setRules();+ const link = await f.link(true);+ return { ...f, link };+ }+ it("adopts repository values and completion state using the existing link", async () => {+ const f = await paused();+ const review = await reviewSyncResume(f.project.id, "gitea", f.link.id);+ expect(review.local.title).toBe("Kaneo title");+ await resumeSync(+ f.project.id,+ "gitea",+ f.link.id,+ review.token,+ "provider",+ );+ const task = await db.query.taskTable.findFirst({+ where: eq(schema.taskTable.id, f.task.id),+ });+ expect(task).toMatchObject({+ title: "Repository title",+ description: "Repository body",+ columnId: f.columns.done.id,+ });+ expect(provider.write).not.toHaveBeenCalled();+ expect(await canSyncTask(f.task.id, f.integration.id)).toBe(true);+ expect(+ await db.query.externalLinkTable.findMany({+ where: eq(schema.externalLinkTable.taskId, f.task.id),+ }),+ ).toHaveLength(1);+ });+ it("keeps Kaneo values only after the repository update succeeds", async () => {+ const f = await paused();+ const review = await reviewSyncResume(f.project.id, "gitea", f.link.id);+ await resumeSync(f.project.id, "gitea", f.link.id, review.token, "kaneo");+ expect(provider.write).toHaveBeenCalledWith({+ title: "Kaneo title",+ description: "Kaneo body",+ state: "open",+ });+ expect(await canSyncTask(f.task.id, f.integration.id)).toBe(true);+ });+ it("requires a fresh comparison after either side changes", async () => {+ const f = await paused();+ const review = await reviewSyncResume(f.project.id, "gitea", f.link.id);+ provider.read.mockResolvedValue({+ ...review.remote,+ title: "Changed remotely",+ updatedAt: "2026-01-03T00:00:00Z",+ });+ await expect(+ resumeSync(f.project.id, "gitea", f.link.id, review.token, "kaneo"),+ ).rejects.toMatchObject({ status: 409 });+ expect(provider.write).not.toHaveBeenCalled();+ expect(await canSyncTask(f.task.id, f.integration.id)).toBe(false);+ });+ it("keeps the link paused when a provider request fails", async () => {+ const f = await paused();+ const review = await reviewSyncResume(f.project.id, "gitea", f.link.id);+ provider.write.mockRejectedValue(new Error("offline"));+ await expect(+ resumeSync(f.project.id, "gitea", f.link.id, review.token, "kaneo"),+ ).rejects.toMatchObject({ status: 502 });+ expect(await canSyncTask(f.task.id, f.integration.id)).toBe(false);+ });+ it("does not review an excluded task or a link from another integration", async () => {+ const f = await paused();+ await db+ .delete(schema.labelTable)+ .where(eq(schema.labelTable.taskId, f.task.id));+ await expect(+ reviewSyncResume(f.project.id, "gitea", f.link.id),+ ).rejects.toMatchObject({ status: 409 });+ const other = await setup();+ await expect(+ reviewSyncResume(other.project.id, "gitea", f.link.id),+ ).rejects.toMatchObject({ status: 404 });+ expect(provider.read).not.toHaveBeenCalled();+ });+});diff --git a/tests/api/label/assign-and-unassign-label.test.ts b/tests/api/label/assign-and-unassign-label.test.tsindex 0ea28cddd..7d39ee688 100644--- a/tests/api/label/assign-and-unassign-label.test.ts+++ b/tests/api/label/assign-and-unassign-label.test.ts@@ -23,6 +23,7 @@ function createMockTxContext() {insert: (...args: unknown[]) => mockInsert(...args),delete: (...args: unknown[]) => mockDelete(...args),query: {+ taskTable: { findFirst: async () => ({ projectId: "proj-1" }) },labelTable: {findFirst: (...args: unknown[]) => mockFindFirst(...args),},@@ -37,6 +38,7 @@ const mockTransaction = vi.fn(async (cb: (tx: unknown) => unknown) =>vi.mock("../../../apps/api/src/database", () => ({default: {query: {+ taskTable: { findFirst: async () => ({ projectId: "proj-1" }) },labelTable: {findFirst: (...args: unknown[]) => mockFindFirst(...args),},@@ -144,6 +146,7 @@ describe("unassignLabelFromTask", () => {mockSelect.mockReturnValue(makeSelectMock([TASK]));mockDelete.mockReturnValue(makeDeleteMock(TASK_LABEL));mockRemoveLabelFromGitHub.mockResolvedValue(undefined);+ mockRemoveLabelFromGitea.mockResolvedValue(undefined);await unassignLabelFromTask("label-task-1", "user-1");@@ -163,6 +166,7 @@ describe("unassignLabelFromTask", () => {mockSelect.mockReturnValue(makeSelectMock([TASK]));mockDelete.mockReturnValue(makeDeleteMock(TASK_LABEL));mockRemoveLabelFromGitHub.mockResolvedValue(undefined);+ mockRemoveLabelFromGitea.mockResolvedValue(undefined);await unassignLabelFromTask("label-task-1", "user-1");@@ -258,6 +262,10 @@ describe("assignLabelToTask", () => {await assignLabelToTask("label-task-1", "task-1", "user-1");+ expect(mockPublishEvent).toHaveBeenCalledWith("task.labels_updated", {+ projectId: "proj-1",+ taskId: "task-old",+ });expect(mockRemoveLabelFromGitHub).toHaveBeenCalledWith("task-old", "bug");expect(mockRemoveLabelFromGitea).toHaveBeenCalledWith("task-old", "bug");expect(mockSyncLabelToGitHub).toHaveBeenCalledWith(@@ -345,3 +353,11 @@ describe("assignLabelToTask", () => {expect(mockInsert).not.toHaveBeenCalled();});});++vi.mock(+ "../../../apps/api/src/plugins/gitlab/utils/sync-label-to-gitlab",+ () => ({+ removeLabelFromGitlab: async () => undefined,+ syncLabelToGitlab: async () => undefined,+ }),+);diff --git a/tests/api/plugins/gitea/comment-sync.test.ts b/tests/api/plugins/gitea/comment-sync.test.tsindex 2e16fa697..9ac68332d 100644--- a/tests/api/plugins/gitea/comment-sync.test.ts+++ b/tests/api/plugins/gitea/comment-sync.test.ts@@ -223,3 +223,8 @@ vi.mock(},}),);++// Policy enforcement is covered by the PostgreSQL sync-rules integration tests.+vi.mock("../../../../apps/api/src/plugins/sync/eligibility", () => ({+ canSyncTask: async () => true,+}));diff --git a/tests/api/plugins/gitea/webhooks/issue-opened.test.ts b/tests/api/plugins/gitea/webhooks/issue-opened.test.tsindex f2a7e714a..a1be2930b 100644--- a/tests/api/plugins/gitea/webhooks/issue-opened.test.ts+++ b/tests/api/plugins/gitea/webhooks/issue-opened.test.ts@@ -13,11 +13,17 @@ const mocks = vi.hoisted(() => {claimTaskNumber: vi.fn(),resolveTargetStatus: vi.fn(),publishEvent: vi.fn(),+ lockedIntegration: vi.fn(),columnFindFirst: vi.fn(),projectFindFirst: vi.fn(),createGiteaClient: vi.fn(),addLabelsToIssueGitea: vi.fn(),db: {+ transaction: async (run: (tx: unknown) => Promise<unknown>) =>+ run(mocks.db),+ select: () => ({+ from: () => ({ where: () => ({ for: mocks.lockedIntegration }) }),+ }),insert: () => ({values: (values: Record<string, unknown>) => {insertedValues.push(values);@@ -88,6 +94,7 @@ vi.mock("../../../../../apps/api/src/plugins/gitea/utils/labels", () => ({const integration = {id: "integration-1",projectId: "project-1",+ project: { workspaceId: "workspace-1" },isActive: true,type: "gitea",config: JSON.stringify({@@ -119,6 +126,7 @@ function issueOpenedPayload(labels: Array<string | { name?: string }>) {beforeEach(() => {vi.clearAllMocks();+ mocks.lockedIntegration.mockResolvedValue([integration]);mocks.insertedValues.length = 0;mocks.findAllIntegrationsByGiteaRepo.mockResolvedValue([integration]);mocks.findExternalLink.mockResolvedValue(null);@@ -180,3 +188,7 @@ describe("handleGiteaIssueOpened", () => {expect(mocks.insertedValues[0].priority).toBe("high");});});++vi.mock("../../../../../apps/api/src/plugins/sync/issue-labels", () => ({+ importIssueLabels: async () => undefined,+}));diff --git a/tests/api/plugins/github/integration-task-scope.test.ts b/tests/api/plugins/github/integration-task-scope.test.tsindex 701540fef..76b2fce88 100644--- a/tests/api/plugins/github/integration-task-scope.test.ts+++ b/tests/api/plugins/github/integration-task-scope.test.ts@@ -111,3 +111,8 @@ describe("integration task ownership", () => {expect(effect).not.toHaveBeenCalled();});});++// Policy enforcement is covered by the PostgreSQL sync-rules integration tests.+vi.mock("../../../../apps/api/src/plugins/sync/eligibility", () => ({+ canSyncTask: async () => true,+}));diff --git a/tests/api/plugins/github/outbound-intent.test.ts b/tests/api/plugins/github/outbound-intent.test.tsindex ae8b0e263..a8a450132 100644--- a/tests/api/plugins/github/outbound-intent.test.ts+++ b/tests/api/plugins/github/outbound-intent.test.ts@@ -503,3 +503,8 @@ it("bounds confirmation retries and durably defers continuous sync changes", asyvi.useRealTimers();}});++// Policy enforcement is covered by the PostgreSQL sync-rules integration tests.+vi.mock("../../../../apps/api/src/plugins/sync/eligibility", () => ({+ canSyncTask: async () => true,+}));diff --git a/tests/api/plugins/github/rapid-state-sync.test.ts b/tests/api/plugins/github/rapid-state-sync.test.tsindex 5beb0f54b..54c002549 100644--- a/tests/api/plugins/github/rapid-state-sync.test.ts+++ b/tests/api/plugins/github/rapid-state-sync.test.ts@@ -133,3 +133,8 @@ it.each([});},);++// Policy enforcement is covered by the PostgreSQL sync-rules integration tests.+vi.mock("../../../../apps/api/src/plugins/sync/eligibility", () => ({+ canSyncTask: async () => true,+}));diff --git a/tests/api/plugins/github/rapid-text-sync.test.ts b/tests/api/plugins/github/rapid-text-sync.test.tsindex 8349d86da..6c743eb8d 100644--- a/tests/api/plugins/github/rapid-text-sync.test.ts+++ b/tests/api/plugins/github/rapid-text-sync.test.ts@@ -231,3 +231,8 @@ it.each([expect(m.save.mock.calls.at(-1)?.[1].outbound.value).toBe("B");},);++// Policy enforcement is covered by the PostgreSQL sync-rules integration tests.+vi.mock("../../../../apps/api/src/plugins/sync/eligibility", () => ({+ canSyncTask: async () => true,+}));diff --git a/tests/api/plugins/github/webhooks/issue-opened.test.ts b/tests/api/plugins/github/webhooks/issue-opened.test.tsindex 1fff5bb92..41f15b67b 100644--- a/tests/api/plugins/github/webhooks/issue-opened.test.ts+++ b/tests/api/plugins/github/webhooks/issue-opened.test.ts@@ -130,7 +130,7 @@ const integration = {onPRMerge: "done",},}),- project: null,+ project: { workspaceId: "workspace-1" },};function issueOpenedPayload(labels: Array<string | { name?: string }>) {@@ -191,3 +191,7 @@ describe("handleIssueOpened", () => {expect(mocks.insertedValues[0].priority).toBe("high");});});++vi.mock("../../../../../apps/api/src/plugins/sync/issue-labels", () => ({+ importIssueLabels: async () => undefined,+}));diff --git a/tests/api/plugins/gitlab/events/task-status-changed.test.ts b/tests/api/plugins/gitlab/events/task-status-changed.test.tsindex 2e7575a2c..80a6210c1 100644--- a/tests/api/plugins/gitlab/events/task-status-changed.test.ts+++ b/tests/api/plugins/gitlab/events/task-status-changed.test.ts@@ -128,3 +128,8 @@ describe("GitLab status webhook feedback", () => {});});});++// Policy enforcement is covered by the PostgreSQL sync-rules integration tests.+vi.mock("../../../../../apps/api/src/plugins/sync/eligibility", () => ({+ canSyncTask: async () => true,+}));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.tsindex f1eb2c383..09c7f9c40 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@@ -101,3 +101,8 @@ it("still removes ordinary labels", async () => {remove_labels: "bug",});});++// Policy enforcement is covered by the PostgreSQL sync-rules integration tests.+vi.mock("../../../../../apps/api/src/plugins/sync/eligibility", () => ({+ canSyncTask: async () => true,+}));diff --git a/tests/api/plugins/gitlab/webhooks/issue-opened.test.ts b/tests/api/plugins/gitlab/webhooks/issue-opened.test.tsindex 3077ec603..3076fe102 100644--- a/tests/api/plugins/gitlab/webhooks/issue-opened.test.ts+++ b/tests/api/plugins/gitlab/webhooks/issue-opened.test.ts@@ -12,11 +12,17 @@ const mocks = vi.hoisted(() => {claimTaskNumber: vi.fn(),resolveTargetStatus: vi.fn(),publishEvent: vi.fn(),+ lockedIntegration: vi.fn(),columnFindFirst: vi.fn(),projectFindFirst: vi.fn(),createGitlabClient: vi.fn(),addLabelsToIssueGitlab: vi.fn(),db: {+ transaction: async (run: (tx: unknown) => Promise<unknown>) =>+ run(mocks.db),+ select: () => ({+ from: () => ({ where: () => ({ for: mocks.lockedIntegration }) }),+ }),insert: () => ({values: (values: Record<string, unknown>) => {insertedValues.push(values);@@ -85,6 +91,7 @@ vi.mock("../../../../../apps/api/src/plugins/gitlab/utils/labels", () => ({const integration = {id: "integration-1",projectId: "project-1",+ project: { workspaceId: "workspace-1" },isActive: true,type: "gitlab",config: JSON.stringify({@@ -115,6 +122,7 @@ function issueOpenedPayload(labels: Array<{ title: string }>) {beforeEach(() => {vi.clearAllMocks();+ mocks.lockedIntegration.mockResolvedValue([integration]);mocks.insertedValues.length = 0;mocks.findAllIntegrationsByGitlabProject.mockResolvedValue([integration]);mocks.findExternalLink.mockResolvedValue(null);@@ -155,6 +163,7 @@ describe("handleGitlabIssueOpened", () => {externalId: "42",url: "https://gitlab.com/usekaneo/kaneo/-/issues/42",}),+ mocks.db,);});@@ -181,3 +190,7 @@ describe("handleGitlabIssueOpened", () => {expect(mocks.claimTaskNumber).not.toHaveBeenCalled();});});++vi.mock("../../../../../apps/api/src/plugins/sync/issue-labels", () => ({+ importIssueLabels: async () => undefined,+}));