Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

fix(integrations): repair late writes and retain guarded links

Tin043214fbeb47
diff --cc apps/api/src/plugins/gitea/events/task-description-changed.ts
index 260193090,8eb8b148c..970091a96
--- a/apps/api/src/plugins/gitea/events/task-description-changed.ts
+++ b/apps/api/src/plugins/gitea/events/task-description-changed.ts
@@@ -1,9 -1,7 +1,7 @@@
-import {
- findExternalLinksByTask,
- updateExternalLink,
-} from "../../github/services/link-manager";
++import { syncLatestTaskText } from "../../github/services/sync-latest-task-text";
+import db from "../../../database";
+import { linkedTaskScope } from "../../github/services/integration-task-scope";
- import {
- findExternalLinksByTask,
- updateExternalLink,
- } from "../../github/services/link-manager";
++import { findExternalLinksByTask } from "../../github/services/link-manager";
import { formatIssueBody } from "../../github/utils/format";
import type { PluginContext, TaskDescriptionChangedEvent } from "../../types";
import type { GiteaConfig } from "../config";
@@@ -92,25 -97,26 +90,25 @@@ export async function handleTaskDescrip
return;
}
-- const formattedBody = formatIssueBody(event.newDescription, event.taskId);
--
- const response = await client.updateIssue(
- repositoryOwner,
- repositoryName,
- issueNumber,
- {
- body: formattedBody,
- await client.updateIssue(repositoryOwner, repositoryName, issueNumber, {
- body: formattedBody,
- });
-
- await updateExternalLink(issueLink.id, {
- metadata: {
- ...metadata,
- lastSync: {
- ...metadata.lastSync,
- description: {
- timestamp: new Date().toISOString(),
- source: "kaneo",
- value: newDescNormalized,
++ await syncLatestTaskText(
++ event.taskId,
++ context.projectId,
++ issueLink,
++ "description",
++ newDescNormalized,
++ async (value) => {
++ const response = await client.updateIssue(
++ repositoryOwner,
++ repositoryName,
++ issueNumber,
++ {
++ body: formatIssueBody(value, event.taskId),
+ },
- },
++ );
++ return response?.updated_at;
},
- });
+ );
- await updateExternalLink(issueLink.id, {
- outbound: {
- field: "description",
- value: newDescNormalized,
- updatedAt: response?.updated_at,
- },
- });
-
console.log(`Synced task description to Gitea issue #${issueNumber}`);
} catch (error) {
console.error("Failed to update Gitea issue description:", error);
diff --cc apps/api/src/plugins/gitea/events/task-title-changed.ts
index 5400faa47,f5be824f1..57c1bfa10
--- a/apps/api/src/plugins/gitea/events/task-title-changed.ts
+++ b/apps/api/src/plugins/gitea/events/task-title-changed.ts
@@@ -1,9 -1,7 +1,7 @@@
-import {
- findExternalLinksByTask,
- updateExternalLink,
-} from "../../github/services/link-manager";
++import { syncLatestTaskText } from "../../github/services/sync-latest-task-text";
+import db from "../../../database";
+import { linkedTaskScope } from "../../github/services/integration-task-scope";
- import {
- findExternalLinksByTask,
- updateExternalLink,
- } from "../../github/services/link-manager";
++import { findExternalLinksByTask } from "../../github/services/link-manager";
import type { PluginContext, TaskTitleChangedEvent } from "../../types";
import type { GiteaConfig } from "../config";
import { createGiteaClient } from "../utils/gitea-api";
@@@ -85,24 -90,25 +83,25 @@@ export async function handleTaskTitleCh
return;
}
- const response = await client.updateIssue(
- repositoryOwner,
- repositoryName,
- issueNumber,
- {
- title: event.newTitle,
- await client.updateIssue(repositoryOwner, repositoryName, issueNumber, {
- title: event.newTitle,
- });
-
- await updateExternalLink(issueLink.id, {
- title: event.newTitle,
- metadata: {
- ...metadata,
- lastSync: {
- ...metadata.lastSync,
- title: {
- timestamp: new Date().toISOString(),
- source: "kaneo",
- value: event.newTitle,
++ await syncLatestTaskText(
++ event.taskId,
++ context.projectId,
++ issueLink,
++ "title",
++ event.newTitle,
++ async (value) => {
++ const response = await client.updateIssue(
++ repositoryOwner,
++ repositoryName,
++ issueNumber,
++ {
++ title: value,
+ },
- },
++ );
++ return response?.updated_at;
},
- });
+ );
- await updateExternalLink(issueLink.id, {
- title: event.newTitle,
- outbound: {
- field: "title",
- value: event.newTitle,
- updatedAt: response?.updated_at,
- },
- });
-
console.log(`Synced task title to Gitea issue #${issueNumber}`);
} catch (error) {
console.error("Failed to update Gitea issue title:", error);
diff --cc apps/api/src/plugins/gitea/webhooks/issue-closed.ts
index 4b00cdb6e,a8e010486..d02e395dc
--- a/apps/api/src/plugins/gitea/webhooks/issue-closed.ts
+++ b/apps/api/src/plugins/gitea/webhooks/issue-closed.ts
@@@ -1,15 -1,5 +1,13 @@@
+ import { withIntegrationLink } from "../../github/services/with-integration-link";
+import type { GiteaConfig } from "../config";
+import { createGiteaClient } from "../utils/gitea-api";
+import { parseLinkMetadata } from "../../github/utils/parse-link-metadata";
+import type { SyncStamp } from "../../github/utils/sync-echo";
+import {
+ inboundEcho,
+ withEchoConfirmation,
+} from "../../github/utils/inbound-echo";
- import {
- linkedTaskScope,
- withIntegrationTask,
- } from "../../github/services/integration-task-scope";
+ import { linkedTaskScope } from "../../github/services/integration-task-scope";
import { and, eq } from "drizzle-orm";
import db from "../../../database";
import { externalLinkTable } from "../../../database/schema";
@@@ -80,105 -67,85 +75,112 @@@ export async function handleGiteaIssueC
continue;
}
- await withIntegrationLink(
- externalLink,
- integration,
- async (db, afterCommit, externalLink) => {
- const task = await db.query.taskTable.findFirst({
- where: linkedTaskScope(externalLink.taskId, integration.projectId),
- });
-
- if (!task) {
- return;
- }
+ const readCurrent = async () => {
+ try {
+ const config = JSON.parse(integration.config) as GiteaConfig;
+ return await createGiteaClient(config).getIssue(
+ config.repositoryOwner,
+ config.repositoryName,
+ issue.number,
+ );
+ } catch {
+ return issue;
+ }
+ };
+ await withEchoConfirmation(readCurrent, (current) =>
- withIntegrationTask(
- externalLink.taskId,
++ withIntegrationLink(
++ externalLink,
+ integration,
- async (db, afterCommit) => {
++ async (db, afterCommit, externalLink) => {
+ const task = await db.query.taskTable.findFirst({
+ where: linkedTaskScope(externalLink.taskId, integration.projectId),
+ });
- let existingMetadata: Record<string, unknown> = {};
- if (externalLink.metadata) {
- try {
- existingMetadata = JSON.parse(externalLink.metadata) as Record<
- string,
- unknown
- >;
- } catch (error) {
- console.warn(
- "Failed to parse Gitea issue metadata for close sync",
- {
- externalLinkId: externalLink.id,
- metadata: externalLink.metadata,
- error,
- },
- );
+ if (!task) {
+ return;
}
- }
- const lockedLink = await lockExternalLink(externalLink.id, db);
- if (!lockedLink) return;
- const lastOutbound = existingMetadata.lastOutboundStateSyncAt;
- if (typeof lastOutbound === "number" && Number.isFinite(lastOutbound)) {
- const eventMs = parseIssueUpdatedAtMs(issue);
+ const existingMetadata = parseLinkMetadata<
+ Record<string, unknown> & { lastSync?: { state?: SyncStamp } }
- >(lockedLink.metadata, {
++ >(externalLink.metadata, {
+ externalLinkId: externalLink.id,
+ source: "gitea_issue_closed",
+ });
if (
- eventMs !== null &&
- Math.abs(eventMs - lastOutbound) <= OUTBOUND_STATE_ECHO_WINDOW_MS
- ) {
+ inboundEcho(
+ existingMetadata.lastSync?.state,
+ "closed",
+ issue.updated_at,
+ current ? (current.state ?? issue.state) : undefined,
+ )
+ )
return;
+ const lastOutbound = existingMetadata.lastOutboundStateSyncAt;
+ if (
+ typeof lastOutbound === "number" &&
+ Number.isFinite(lastOutbound) &&
+ existingMetadata.state === "closed"
+ ) {
+ const eventMs = parseIssueUpdatedAtMs(issue);
+ if (
+ eventMs !== null &&
+ Math.abs(eventMs - lastOutbound) <= OUTBOUND_STATE_ECHO_WINDOW_MS
+ ) {
+ return;
+ }
}
- }
- const targetStatus = await resolveTargetStatus(
- task.projectId,
- "issue_closed",
- "done",
- db,
- );
+ const targetStatus = await resolveTargetStatus(
+ task.projectId,
+ "issue_closed",
+ "done",
+ db,
+ );
- const statusResult = await updateTaskStatus(task.id, targetStatus, db);
- if (
- statusResult.applied &&
- statusResult.before.status !== statusResult.after.status
- ) {
- afterCommit(() =>
- publishEvent("task.status_changed", {
- taskId: statusResult.after.id,
- projectId: statusResult.after.projectId,
- userId: null,
- oldStatus: statusResult.before.status,
- newStatus: statusResult.after.status,
- title: statusResult.after.title,
- assigneeId: statusResult.after.userId,
- type: "status_changed",
- }),
+ const statusResult = await updateTaskStatus(
+ task.id,
+ targetStatus,
+ db,
);
- }
+ if (
+ statusResult.applied &&
+ statusResult.before.status !== statusResult.after.status
+ ) {
+ afterCommit(() =>
+ publishEvent("task.status_changed", {
+ taskId: statusResult.after.id,
+ projectId: statusResult.after.projectId,
+ userId: null,
+ oldStatus: statusResult.before.status,
+ newStatus: statusResult.after.status,
+ title: statusResult.after.title,
+ assigneeId: statusResult.after.userId,
+ type: "status_changed",
+ }),
+ );
+ }
- await updateExternalLink(
- externalLink.id,
- {
- metadata: {
- ...existingMetadata,
- state: "closed",
+ await updateExternalLink(
+ externalLink.id,
+ {
+ metadata: {
+ ...existingMetadata,
+ state: "closed",
++ lastSync: {
++ ...existingMetadata.lastSync,
++ state: {
++ ...existingMetadata.lastSync?.state,
++ source: "gitea",
++ value: "closed",
++ timestamp: new Date().toISOString(),
++ },
++ },
+ },
},
- },
- db,
- );
- },
+ db,
+ );
+ },
+ ),
);
}
}
diff --cc apps/api/src/plugins/gitea/webhooks/issue-edited.ts
index b226094c6,687c70e48..f10cdd587
--- a/apps/api/src/plugins/gitea/webhooks/issue-edited.ts
+++ b/apps/api/src/plugins/gitea/webhooks/issue-edited.ts
@@@ -1,13 -1,5 +1,11 @@@
+ import { withIntegrationLink } from "../../github/services/with-integration-link";
+import type { GiteaConfig } from "../config";
+import { createGiteaClient } from "../utils/gitea-api";
+import {
+ inboundEcho,
+ withEchoConfirmation,
+} from "../../github/utils/inbound-echo";
- import {
- linkedTaskScope,
- withIntegrationTask,
- } from "../../github/services/integration-task-scope";
+ import { linkedTaskScope } from "../../github/services/integration-task-scope";
import { taskTable } from "../../../database/schema";
import {
findExternalLink,
@@@ -73,126 -63,108 +70,127 @@@ export async function handleGiteaIssueE
continue;
}
- await withIntegrationLink(
- externalLink,
- integration,
- async (db, _afterCommit, externalLink) => {
- const task = await db.query.taskTable.findFirst({
- where: linkedTaskScope(externalLink.taskId, integration.projectId),
- });
-
- if (!task) {
- return;
- }
-
- const metadata = externalLink.metadata
- ? JSON.parse(externalLink.metadata)
- : {};
-
- const updateData: Record<string, unknown> = {};
- const updatedMetadata = { ...metadata };
-
- if (!updatedMetadata.lastSync) {
- updatedMetadata.lastSync = {};
- }
+ const readCurrent = async () => {
+ try {
+ const config = JSON.parse(integration.config) as GiteaConfig;
+ return await createGiteaClient(config).getIssue(
+ config.repositoryOwner,
+ config.repositoryName,
+ issue.number,
+ );
+ } catch {
+ return issue;
+ }
+ };
+ await withEchoConfirmation(readCurrent, (current) =>
- withIntegrationTask(externalLink.taskId, integration, async (db) => {
- const task = await db.query.taskTable.findFirst({
- where: linkedTaskScope(externalLink.taskId, integration.projectId),
- });
++ withIntegrationLink(
++ externalLink,
++ integration,
++ async (db, _afterCommit, externalLink) => {
++ const task = await db.query.taskTable.findFirst({
++ where: linkedTaskScope(externalLink.taskId, integration.projectId),
++ });
++
++ if (!task) {
++ return;
++ }
++ const metadata = externalLink.metadata
++ ? JSON.parse(externalLink.metadata)
++ : {};
- if (!task) {
- return;
- }
-
- const lockedLink = await lockExternalLink(externalLink.id, db);
- if (!lockedLink) return;
- const metadata = lockedLink.metadata
- ? JSON.parse(lockedLink.metadata)
- : {};
-
- const updateData: Record<string, unknown> = {};
- const updatedMetadata = { ...metadata };
-
- if (!updatedMetadata.lastSync) {
- updatedMetadata.lastSync = {};
- }
-
-- if (changes.title) {
-- const lastTitleSync = metadata.lastSync?.title;
-
- let shouldUpdateTitle = true;
-
- if (lastTitleSync) {
- if (
- inboundEcho(
- lastTitleSync,
- issue.title,
- issue.updated_at,
- current?.title,
- )
- ) {
- shouldUpdateTitle = false;
- }
++ const updateData: Record<string, unknown> = {};
++ const updatedMetadata = { ...metadata };
+
- let shouldUpdateTitle = true;
++ if (!updatedMetadata.lastSync) {
++ updatedMetadata.lastSync = {};
+ }
- if (shouldUpdateTitle) {
- updateData.title = issue.title;
- updatedMetadata.lastSync.title = {
- outbound: metadata.lastSync?.title?.outbound,
- timestamp: new Date().toISOString(),
- source: "gitea",
- value: issue.title,
- };
- if (lastTitleSync) {
- if (
- lastTitleSync.value === issue.title &&
- lastTitleSync.source === "kaneo"
- ) {
- shouldUpdateTitle = false;
++ if (changes.title) {
++ const lastTitleSync = metadata.lastSync?.title;
++
++ let shouldUpdateTitle = true;
++
++ if (lastTitleSync) {
++ if (
++ inboundEcho(
++ lastTitleSync,
++ issue.title,
++ issue.updated_at,
++ current?.title,
++ )
++ ) {
++ shouldUpdateTitle = false;
++ }
+ }
- const timeSinceLastSync =
- Date.now() - new Date(lastTitleSync.timestamp).getTime();
- if (timeSinceLastSync < 2000 && shouldUpdateTitle) {
- shouldUpdateTitle = false;
++
++ if (shouldUpdateTitle) {
++ updateData.title = issue.title;
++ updatedMetadata.lastSync.title = {
++ outbound: metadata.lastSync?.title?.outbound,
++ timestamp: new Date().toISOString(),
++ source: "gitea",
++ value: issue.title,
++ };
+ }
}
- }
-
- if (changes.body) {
- const lastDescSync = metadata.lastSync?.description;
- const formattedDescription = formatTaskDescriptionFromIssue(
- issue.body,
- externalLink.taskId,
- );
-
- let shouldUpdateDescription = true;
-
- if (lastDescSync) {
- if (
- inboundEcho(
- lastDescSync,
- formattedDescription,
- issue.updated_at,
- current
- ? formatTaskDescriptionFromIssue(
- current.body ?? null,
- task.id,
- )
- : undefined,
- )
- ) {
- shouldUpdateDescription = false;
+
- if (shouldUpdateTitle) {
- updateData.title = issue.title;
- updatedMetadata.lastSync.title = {
- timestamp: new Date().toISOString(),
- source: "gitea",
- value: issue.title,
- };
- }
- }
-
- if (changes.body) {
- const lastDescSync = metadata.lastSync?.description;
- const formattedDescription = formatTaskDescriptionFromIssue(
- issue.body,
- );
-
- let shouldUpdateDescription = true;
-
- if (lastDescSync) {
- if (
- lastDescSync.value === formattedDescription &&
- lastDescSync.source === "kaneo"
- ) {
- shouldUpdateDescription = false;
++ if (changes.body) {
++ const lastDescSync = metadata.lastSync?.description;
++ const formattedDescription = formatTaskDescriptionFromIssue(
++ issue.body,
++ externalLink.taskId,
++ );
++
++ let shouldUpdateDescription = true;
++
++ if (lastDescSync) {
++ if (
++ inboundEcho(
++ lastDescSync,
++ formattedDescription,
++ issue.updated_at,
++ current
++ ? formatTaskDescriptionFromIssue(
++ current.body ?? null,
++ task.id,
++ )
++ : undefined,
++ )
++ ) {
++ shouldUpdateDescription = false;
++ }
+ }
- const timeSinceLastSync =
- Date.now() - new Date(lastDescSync.timestamp).getTime();
- if (timeSinceLastSync < 2000 && shouldUpdateDescription) {
- shouldUpdateDescription = false;
++
++ if (shouldUpdateDescription) {
++ updateData.description = formattedDescription;
++ updatedMetadata.lastSync.description = {
++ outbound: metadata.lastSync?.description?.outbound,
++ timestamp: new Date().toISOString(),
++ source: "gitea",
++ value: formattedDescription,
++ };
}
}
-- if (shouldUpdateDescription) {
-- updateData.description = formattedDescription;
-- updatedMetadata.lastSync.description = {
- outbound: metadata.lastSync?.description?.outbound,
-- timestamp: new Date().toISOString(),
-- source: "gitea",
-- value: formattedDescription,
-- };
++ if (Object.keys(updateData).length > 0) {
++ await db
++ .update(taskTable)
++ .set(updateData)
++ .where(linkedTaskScope(task.id, integration.projectId));
++
++ await updateExternalLink(
++ externalLink.id,
++ {
++ title: issue.title,
++ metadata: updatedMetadata,
++ },
++ db,
++ );
}
-- }
--
-- if (Object.keys(updateData).length > 0) {
-- await db
-- .update(taskTable)
-- .set(updateData)
-- .where(linkedTaskScope(task.id, integration.projectId));
--
-- await updateExternalLink(
-- externalLink.id,
-- {
-- title: issue.title,
-- metadata: updatedMetadata,
-- },
-- db,
-- );
-- }
--
-- return;
- }),
- },
++
++ return;
++ },
++ ),
);
}
}
diff --cc apps/api/src/plugins/gitea/webhooks/issue-reopened.ts
index cb83c20f4,2f6dd8460..ddadc28eb
--- a/apps/api/src/plugins/gitea/webhooks/issue-reopened.ts
+++ b/apps/api/src/plugins/gitea/webhooks/issue-reopened.ts
@@@ -1,15 -1,5 +1,13 @@@
+ import { withIntegrationLink } from "../../github/services/with-integration-link";
+import type { GiteaConfig } from "../config";
+import { createGiteaClient } from "../utils/gitea-api";
+import { parseLinkMetadata } from "../../github/utils/parse-link-metadata";
+import type { SyncStamp } from "../../github/utils/sync-echo";
+import {
+ inboundEcho,
+ withEchoConfirmation,
+} from "../../github/utils/inbound-echo";
- import {
- linkedTaskScope,
- withIntegrationTask,
- } from "../../github/services/integration-task-scope";
+ import { linkedTaskScope } from "../../github/services/integration-task-scope";
import { and, eq } from "drizzle-orm";
import db from "../../../database";
import { externalLinkTable } from "../../../database/schema";
@@@ -81,109 -68,92 +76,115 @@@ export async function handleGiteaIssueR
continue;
}
- await withIntegrationLink(
- externalLink,
- integration,
- async (db, afterCommit, externalLink) => {
- const task = await db.query.taskTable.findFirst({
- where: linkedTaskScope(externalLink.taskId, integration.projectId),
- });
-
- if (!task) {
- return;
- }
+ const readCurrent = async () => {
+ try {
+ const config = JSON.parse(integration.config) as GiteaConfig;
+ return await createGiteaClient(config).getIssue(
+ config.repositoryOwner,
+ config.repositoryName,
+ issue.number,
+ );
+ } catch {
+ return issue;
+ }
+ };
+ await withEchoConfirmation(readCurrent, (current) =>
- withIntegrationTask(
- externalLink.taskId,
++ withIntegrationLink(
++ externalLink,
+ integration,
- async (db, afterCommit) => {
++ async (db, afterCommit, externalLink) => {
+ const task = await db.query.taskTable.findFirst({
+ where: linkedTaskScope(
+ externalLink.taskId,
+ integration.projectId,
+ ),
+ });
- let existingMetadata: Record<string, unknown> = {};
- if (externalLink.metadata) {
- try {
- existingMetadata = JSON.parse(externalLink.metadata) as Record<
- string,
- unknown
- >;
- } catch (error) {
- console.warn(
- "Failed to parse Gitea issue metadata for reopen sync",
- {
- externalLinkId: externalLink.id,
- metadata: externalLink.metadata,
- error,
- },
- );
+ if (!task) {
+ return;
}
- }
--
- const lockedLink = await lockExternalLink(externalLink.id, db);
- if (!lockedLink) return;
- const lastOutbound = existingMetadata.lastOutboundStateSyncAt;
- if (
- typeof lastOutbound === "number" &&
- Number.isFinite(lastOutbound)
- ) {
- const eventMs = parseIssueUpdatedAtMs(issue);
+ const existingMetadata = parseLinkMetadata<
+ Record<string, unknown> & { lastSync?: { state?: SyncStamp } }
- >(lockedLink.metadata, {
++ >(externalLink.metadata, {
+ externalLinkId: externalLink.id,
+ source: "gitea_issue_reopened",
+ });
if (
- eventMs !== null &&
- Math.abs(eventMs - lastOutbound) <= OUTBOUND_STATE_ECHO_WINDOW_MS
- ) {
+ inboundEcho(
+ existingMetadata.lastSync?.state,
+ "open",
+ issue.updated_at,
+ current ? (current.state ?? issue.state) : undefined,
+ )
+ )
return;
+ const lastOutbound = existingMetadata.lastOutboundStateSyncAt;
+ if (
+ typeof lastOutbound === "number" &&
+ Number.isFinite(lastOutbound) &&
+ existingMetadata.state === "open"
+ ) {
+ const eventMs = parseIssueUpdatedAtMs(issue);
+ if (
+ eventMs !== null &&
+ Math.abs(eventMs - lastOutbound) <=
+ OUTBOUND_STATE_ECHO_WINDOW_MS
+ ) {
+ return;
+ }
}
- }
- const targetStatus = await resolveTargetStatus(
- task.projectId,
- "issue_reopened",
- "to-do",
- db,
- );
+ const targetStatus = await resolveTargetStatus(
+ task.projectId,
+ "issue_reopened",
+ "to-do",
+ db,
+ );
- const statusResult = await updateTaskStatus(
- task.id,
- targetStatus,
- db,
- );
- if (
- statusResult.applied &&
- statusResult.before.status !== statusResult.after.status
- ) {
- afterCommit(() =>
- publishEvent("task.status_changed", {
- taskId: statusResult.after.id,
- projectId: statusResult.after.projectId,
- userId: null,
- oldStatus: statusResult.before.status,
- newStatus: statusResult.after.status,
- title: statusResult.after.title,
- assigneeId: statusResult.after.userId,
- type: "status_changed",
- }),
+ const statusResult = await updateTaskStatus(
+ task.id,
+ targetStatus,
+ db,
);
- }
+ if (
+ statusResult.applied &&
+ statusResult.before.status !== statusResult.after.status
+ ) {
+ afterCommit(() =>
+ publishEvent("task.status_changed", {
+ taskId: statusResult.after.id,
+ projectId: statusResult.after.projectId,
+ userId: null,
+ oldStatus: statusResult.before.status,
+ newStatus: statusResult.after.status,
+ title: statusResult.after.title,
+ assigneeId: statusResult.after.userId,
+ type: "status_changed",
+ }),
+ );
+ }
- await updateExternalLink(
- externalLink.id,
- {
- metadata: {
- ...existingMetadata,
- state: "open",
+ await updateExternalLink(
+ externalLink.id,
+ {
+ metadata: {
+ ...existingMetadata,
+ state: "open",
++ lastSync: {
++ ...existingMetadata.lastSync,
++ state: {
++ ...existingMetadata.lastSync?.state,
++ source: "gitea",
++ value: "open",
++ timestamp: new Date().toISOString(),
++ },
++ },
+ },
},
- },
- db,
- );
- },
+ db,
+ );
+ },
+ ),
);
} catch (error) {
console.error("Gitea issue_reopened handler failed for integration", {
diff --cc apps/api/src/plugins/github/events/task-description-changed.ts
index 03cc2078d,efe559293..2b2cef15d
--- a/apps/api/src/plugins/github/events/task-description-changed.ts
+++ b/apps/api/src/plugins/github/events/task-description-changed.ts
@@@ -1,11 -1,9 +1,9 @@@
++import { syncLatestTaskText } from "../services/sync-latest-task-text";
+import db from "../../../database";
+import { linkedTaskScope } from "../services/integration-task-scope";
import type { PluginContext, TaskDescriptionChangedEvent } from "../../types";
import { type GitHubConfig, hasVerifiedGitHubBinding } from "../config";
--import {
-- findExternalLinksByTask,
-- updateExternalLink,
--} from "../services/link-manager";
++import { findExternalLinksByTask } from "../services/link-manager";
import { formatIssueBody } from "../utils/format";
import {
getGithubApp,
@@@ -68,23 -66,29 +66,22 @@@ export async function handleTaskDescrip
const issueNumber = Number.parseInt(issueLink.externalId, 10);
// Format description with task ID footer
-- const formattedBody = formatIssueBody(event.newDescription, event.taskId);
--
- const response = await octokit.rest.issues.update({
- await octokit.rest.issues.update({
-- owner: repositoryOwner,
-- repo: repositoryName,
-- issue_number: issueNumber,
-- body: formattedBody,
-- });
--
-- // Update metadata to track this sync
-- await updateExternalLink(issueLink.id, {
- outbound: {
- field: "description",
- value: newDescNormalized,
- updatedAt: response?.data?.updated_at,
- metadata: {
- ...metadata,
- lastSync: {
- ...metadata.lastSync,
- description: {
- timestamp: new Date().toISOString(),
- source: "kaneo",
- value: newDescNormalized,
- },
- },
++ await syncLatestTaskText(
++ event.taskId,
++ context.projectId,
++ issueLink,
++ "description",
++ newDescNormalized,
++ async (value) => {
++ const response = await octokit.rest.issues.update({
++ owner: repositoryOwner,
++ repo: repositoryName,
++ issue_number: issueNumber,
++ body: formatIssueBody(value, event.taskId),
++ });
++ return response?.data?.updated_at;
},
-- });
++ );
console.log(`Synced task description to GitHub issue #${issueNumber}`);
} catch (error) {
diff --cc apps/api/src/plugins/github/events/task-title-changed.ts
index 1a4d9daa8,d0e18c8df..28e8a9b14
--- a/apps/api/src/plugins/github/events/task-title-changed.ts
+++ b/apps/api/src/plugins/github/events/task-title-changed.ts
@@@ -1,11 -1,9 +1,9 @@@
++import { syncLatestTaskText } from "../services/sync-latest-task-text";
+import db from "../../../database";
+import { linkedTaskScope } from "../services/integration-task-scope";
import type { PluginContext, TaskTitleChangedEvent } from "../../types";
import { type GitHubConfig, hasVerifiedGitHubBinding } from "../config";
--import {
-- findExternalLinksByTask,
-- updateExternalLink,
--} from "../services/link-manager";
++import { findExternalLinksByTask } from "../services/link-manager";
import {
getGithubApp,
getVerifiedInstallationOctokit,
@@@ -60,22 -62,28 +58,22 @@@ export async function handleTaskTitleCh
const octokit = await getVerifiedInstallationOctokit(config);
const issueNumber = Number.parseInt(issueLink.externalId, 10);
- const response = await octokit.rest.issues.update({
- await octokit.rest.issues.update({
-- owner: repositoryOwner,
-- repo: repositoryName,
-- issue_number: issueNumber,
-- title: event.newTitle,
-- });
--
-- // Update metadata to track this sync
-- await updateExternalLink(issueLink.id, {
-- title: event.newTitle,
- outbound: {
- field: "title",
- value: event.newTitle,
- updatedAt: response?.data?.updated_at,
- metadata: {
- ...metadata,
- lastSync: {
- ...metadata.lastSync,
- title: {
- timestamp: new Date().toISOString(),
- source: "kaneo",
- value: event.newTitle,
- },
- },
++ await syncLatestTaskText(
++ event.taskId,
++ context.projectId,
++ issueLink,
++ "title",
++ event.newTitle,
++ async (value) => {
++ const response = await octokit.rest.issues.update({
++ owner: repositoryOwner,
++ repo: repositoryName,
++ issue_number: issueNumber,
++ title: value,
++ });
++ return response?.data?.updated_at;
},
-- });
++ );
console.log(`Synced task title to GitHub issue #${issueNumber}`);
} catch (error) {
diff --cc apps/api/src/plugins/github/services/sync-latest-task-text.ts
index 000000000,000000000..ded1a9758
new file mode 100644
--- /dev/null
+++ b/apps/api/src/plugins/github/services/sync-latest-task-text.ts
@@@ -1,0 -1,0 +1,38 @@@
++import db from "../../../database";
++import { linkedTaskScope } from "./integration-task-scope";
++import { findExternalLinksByTask, updateExternalLink } from "./link-manager";
++
++// Provider requests may complete out of order across API instances. Every late
++// completion repairs the provider using the current, still-linked task value.
++export async function syncLatestTaskText(
++ taskId: string,
++ projectId: string,
++ link: { id: string; integrationId: string | null },
++ field: "title" | "description",
++ initialValue: string,
++ write: (value: string) => Promise<string | undefined>,
++) {
++ let value = initialValue;
++ for (;;) {
++ const updatedAt = await write(value);
++ await updateExternalLink(link.id, {
++ ...(field === "title" ? { title: value } : {}),
++ outbound: { field, value, updatedAt },
++ });
++ const task = await db.query.taskTable.findFirst({
++ where: linkedTaskScope(taskId, projectId),
++ columns: { title: true, description: true },
++ });
++ if (!task) return;
++ const current = field === "title" ? task.title : task.description || "";
++ if (current === value) return;
++ const stillLinked = (await findExternalLinksByTask(taskId)).some(
++ (currentLink) =>
++ currentLink.id === link.id &&
++ currentLink.integrationId === link.integrationId &&
++ currentLink.resourceType === "issue",
++ );
++ if (!stillLinked) return;
++ value = current;
++ }
++}
diff --cc apps/api/src/plugins/github/webhooks/issue-edited.ts
index 87848acf9,8ce77232f..c0bc13e81
--- a/apps/api/src/plugins/github/webhooks/issue-edited.ts
+++ b/apps/api/src/plugins/github/webhooks/issue-edited.ts
@@@ -1,16 -1,7 +1,10 @@@
+ import { withIntegrationLink } from "../services/with-integration-link";
+import type { GitHubConfig } from "../config";
+import { getVerifiedInstallationOctokit } from "../utils/github-app";
+import { inboundEcho, withEchoConfirmation } from "../utils/inbound-echo";
- import {
- linkedTaskScope,
- withIntegrationTask,
- } from "../services/integration-task-scope";
+ import { linkedTaskScope } from "../services/integration-task-scope";
import { taskTable } from "../../../database/schema";
- import {
- findExternalLink,
- updateExternalLink,
- lockExternalLink,
- } from "../services/link-manager";
+ import { findExternalLink, updateExternalLink } from "../services/link-manager";
import { findAllIntegrationsByRepo } from "../services/task-service";
import { formatTaskDescriptionFromIssue } from "../utils/format";
import { parseLinkMetadata } from "../utils/parse-link-metadata";
@@@ -75,150 -69,136 +69,153 @@@ export async function handleIssueEdited
continue;
}
- await withIntegrationLink(
- externalLink,
- integration,
- async (db, _afterCommit, externalLink) => {
- const task = await db.query.taskTable.findFirst({
- where: linkedTaskScope(externalLink.taskId, integration.projectId),
- });
+ const readCurrent = async () => {
+ try {
+ const config = JSON.parse(integration.config) as GitHubConfig;
+ const octokit = await getVerifiedInstallationOctokit(config);
+ return (
+ await octokit.rest.issues.get({
+ owner: config.repositoryOwner,
+ repo: config.repositoryName,
+ issue_number: issue.number,
+ })
+ ).data;
+ } catch {
+ return issue;
+ }
+ };
+ await withEchoConfirmation(readCurrent, (current) =>
- withIntegrationTask(externalLink.taskId, integration, async (db) => {
- const task = await db.query.taskTable.findFirst({
- where: linkedTaskScope(externalLink.taskId, integration.projectId),
- });
-
- if (!task) {
- console.error(`Task ${externalLink.taskId} not found`);
- return;
- }
-
- const lockedLink = await lockExternalLink(externalLink.id, db);
- if (!lockedLink) return;
- const metadata = parseLinkMetadata<IssueEditedMetadata>(
- lockedLink.metadata,
- {
- externalLinkId: externalLink.id,
- source: "issue_edited",
- },
- );
-
- const updateData: Record<string, unknown> = {};
- const updatedMetadata: IssueEditedMetadata = { ...metadata };
-
- if (!updatedMetadata.lastSync) {
- updatedMetadata.lastSync = {};
- }
-
- if (changes.title) {
- const lastTitleSync = metadata.lastSync?.title;
-
- let shouldUpdateTitle = true;
-
- if (lastTitleSync) {
- if (
- inboundEcho(
- lastTitleSync,
- issue.title,
- issue.updated_at,
- current?.title,
- )
- ) {
- console.log("Skipping title update - already synced from Kaneo");
- shouldUpdateTitle = false;
- }
++ withIntegrationLink(
++ externalLink,
++ integration,
++ async (db, _afterCommit, externalLink) => {
++ const task = await db.query.taskTable.findFirst({
++ where: linkedTaskScope(externalLink.taskId, integration.projectId),
++ });
++
++ if (!task) {
++ console.error(`Task ${externalLink.taskId} not found`);
++ return;
+ }
++ const metadata = parseLinkMetadata<IssueEditedMetadata>(
++ externalLink.metadata,
++ {
++ externalLinkId: externalLink.id,
++ source: "issue_edited",
++ },
++ );
- if (shouldUpdateTitle) {
- updateData.title = issue.title;
- updatedMetadata.lastSync.title = {
- outbound: metadata.lastSync?.title?.outbound,
- timestamp: new Date().toISOString(),
- source: "github",
- value: issue.title,
- };
- console.log(
- `Updating task title from GitHub: "${changes.title.from}" → "${issue.title}"`,
- );
- if (!task) {
- console.error(`Task ${externalLink.taskId} not found`);
- return;
- }
-
- const metadata = parseLinkMetadata<IssueEditedMetadata>(
- externalLink.metadata,
- {
- externalLinkId: externalLink.id,
- source: "issue_edited",
- },
- );
-
- const updateData: Record<string, unknown> = {};
- const updatedMetadata: IssueEditedMetadata = { ...metadata };
-
- if (!updatedMetadata.lastSync) {
- updatedMetadata.lastSync = {};
- }
-
- if (changes.title) {
- const lastTitleSync = metadata.lastSync?.title;
-
- let shouldUpdateTitle = true;
-
- if (lastTitleSync) {
- if (
- lastTitleSync.value === issue.title &&
- lastTitleSync.source === "kaneo"
- ) {
- console.log("Skipping title update - already synced from Kaneo");
- shouldUpdateTitle = false;
++ const updateData: Record<string, unknown> = {};
++ const updatedMetadata: IssueEditedMetadata = { ...metadata };
++
++ if (!updatedMetadata.lastSync) {
++ updatedMetadata.lastSync = {};
+ }
- }
+
- if (changes.body) {
- const lastDescSync = metadata.lastSync?.description;
- const formattedDescription = formatTaskDescriptionFromIssue(
- issue.body,
- task.id,
- );
++ if (changes.title) {
++ const lastTitleSync = metadata.lastSync?.title;
++
++ let shouldUpdateTitle = true;
++
++ if (lastTitleSync) {
++ if (
++ inboundEcho(
++ lastTitleSync,
++ issue.title,
++ issue.updated_at,
++ current?.title,
++ )
++ ) {
++ console.log(
++ "Skipping title update - already synced from Kaneo",
++ );
++ shouldUpdateTitle = false;
++ }
+ }
- const timeSinceLastSync =
- Date.now() - new Date(lastTitleSync.timestamp ?? 0).getTime();
- if (timeSinceLastSync < 2000 && shouldUpdateTitle) {
+
- let shouldUpdateDescription = true;
-
- if (lastDescSync) {
- if (
- inboundEcho(
- lastDescSync,
- formattedDescription,
- issue.updated_at,
- current
- ? formatTaskDescriptionFromIssue(
- current.body ?? null,
- task.id,
- )
- : undefined,
- )
- ) {
++ if (shouldUpdateTitle) {
++ updateData.title = issue.title;
++ updatedMetadata.lastSync.title = {
++ outbound: metadata.lastSync?.title?.outbound,
++ timestamp: new Date().toISOString(),
++ source: "github",
++ value: issue.title,
++ };
console.log(
- "Skipping description update - already synced from Kaneo",
- `Skipping title update - recent sync detected (${timeSinceLastSync}ms ago)`,
++ `Updating task title from GitHub: "${changes.title.from}" → "${issue.title}"`,
);
- shouldUpdateDescription = false;
- shouldUpdateTitle = false;
}
}
- if (shouldUpdateDescription) {
- updateData.description = formattedDescription;
- updatedMetadata.lastSync.description = {
- outbound: metadata.lastSync?.description?.outbound,
- if (shouldUpdateTitle) {
- updateData.title = issue.title;
- updatedMetadata.lastSync.title = {
-- timestamp: new Date().toISOString(),
-- source: "github",
- value: formattedDescription,
- value: issue.title,
-- };
- console.log("Updating task description from GitHub");
- }
- }
- console.log(
- `Updating task title from GitHub: "${changes.title.from}" → "${issue.title}"`,
++ if (changes.body) {
++ const lastDescSync = metadata.lastSync?.description;
++ const formattedDescription = formatTaskDescriptionFromIssue(
++ issue.body,
++ task.id,
+ );
- }
- }
- if (Object.keys(updateData).length > 0) {
- await db
- .update(taskTable)
- .set(updateData)
- .where(linkedTaskScope(task.id, integration.projectId));
- if (changes.body) {
- const lastDescSync = metadata.lastSync?.description;
- const formattedDescription = formatTaskDescriptionFromIssue(
- issue.body,
- task.id,
- );
-
- let shouldUpdateDescription = true;
-
- if (lastDescSync) {
- if (
- lastDescSync.value === formattedDescription &&
- lastDescSync.source === "kaneo"
- ) {
- console.log(
- "Skipping description update - already synced from Kaneo",
- );
- shouldUpdateDescription = false;
++ let shouldUpdateDescription = true;
++
++ if (lastDescSync) {
++ if (
++ inboundEcho(
++ lastDescSync,
++ formattedDescription,
++ issue.updated_at,
++ current
++ ? formatTaskDescriptionFromIssue(
++ current.body ?? null,
++ task.id,
++ )
++ : undefined,
++ )
++ ) {
++ console.log(
++ "Skipping description update - already synced from Kaneo",
++ );
++ shouldUpdateDescription = false;
++ }
+ }
- const timeSinceLastSync =
- Date.now() - new Date(lastDescSync.timestamp ?? 0).getTime();
- if (timeSinceLastSync < 2000 && shouldUpdateDescription) {
- console.log(
- `Skipping description update - recent sync detected (${timeSinceLastSync}ms ago)`,
- );
- shouldUpdateDescription = false;
- }
- }
- await updateExternalLink(
- externalLink.id,
- {
- title: issue.title,
- metadata: updatedMetadata,
- },
- db,
- );
- if (shouldUpdateDescription) {
- updateData.description = formattedDescription;
- updatedMetadata.lastSync.description = {
- timestamp: new Date().toISOString(),
- source: "github",
- value: formattedDescription,
- };
- console.log("Updating task description from GitHub");
++ if (shouldUpdateDescription) {
++ updateData.description = formattedDescription;
++ updatedMetadata.lastSync.description = {
++ outbound: metadata.lastSync?.description?.outbound,
++ timestamp: new Date().toISOString(),
++ source: "github",
++ value: formattedDescription,
++ };
++ console.log("Updating task description from GitHub");
++ }
+ }
- }
- console.log(
- `Synced ${Object.keys(updateData).join(", ")} from GitHub issue #${issue.number} to task ${task.id}`,
- );
- } else {
- console.log(
- `No updates needed for task ${task.id} from issue #${issue.number}`,
- if (Object.keys(updateData).length > 0) {
- await db
- .update(taskTable)
- .set(updateData)
- .where(linkedTaskScope(task.id, integration.projectId));
-
- await updateExternalLink(
- externalLink.id,
- {
- title: issue.title,
- metadata: updatedMetadata,
- },
- db,
-- );
- }
++ if (Object.keys(updateData).length > 0) {
++ await db
++ .update(taskTable)
++ .set(updateData)
++ .where(linkedTaskScope(task.id, integration.projectId));
++
++ await updateExternalLink(
++ externalLink.id,
++ {
++ title: issue.title,
++ metadata: updatedMetadata,
++ },
++ db,
++ );
- return;
- }),
- console.log(
- `Synced ${Object.keys(updateData).join(", ")} from GitHub issue #${issue.number} to task ${task.id}`,
- );
- } else {
- console.log(
- `No updates needed for task ${task.id} from issue #${issue.number}`,
- );
- }
++ console.log(
++ `Synced ${Object.keys(updateData).join(", ")} from GitHub issue #${issue.number} to task ${task.id}`,
++ );
++ } else {
++ console.log(
++ `No updates needed for task ${task.id} from issue #${issue.number}`,
++ );
++ }
+
- return;
- },
++ return;
++ },
++ ),
);
}
}
diff --cc tests/api-integration/integration-task-ownership.test.ts
index d8eb8766e,5b515b38f..493f647b7
--- a/tests/api-integration/integration-task-ownership.test.ts
+++ b/tests/api-integration/integration-task-ownership.test.ts
@@@ -415,109 -414,72 +415,178 @@@ it("preserves legacy links belonging t
expect(await db.query.externalLinkTable.findMany()).toEqual([compatible]);
});
+it("preserves outbound history and unrelated fields across concurrent sync completions", async () => {
+ const { updateExternalLink } =
+ await import("../../apps/api/src/plugins/github/services/link-manager");
+ const { isOutboundEcho } =
+ await import("../../apps/api/src/plugins/github/utils/sync-echo");
+ const { link } = await setup();
+ await db
+ .update(schema.externalLinkTable)
+ .set({ metadata: JSON.stringify({ remoteMarker: "keep" }) })
+ .where(eq(schema.externalLinkTable.id, link.id));
+ await Promise.all(
+ Array.from({ length: 12 }, (_, i) =>
+ updateExternalLink(link.id, {
+ outbound: {
+ field: i % 2 ? "description" : "title",
+ value: `edit-${i}`,
+ updatedAt: `time-${i}`,
+ },
+ }),
+ ),
+ );
+ const beforeStateWebhook = await db.query.externalLinkTable.findFirst({
+ where: eq(schema.externalLinkTable.id, link.id),
+ });
+ const latestTitleStamp = JSON.parse(beforeStateWebhook!.metadata!).lastSync
+ .title;
+ // A state webhook can hold a metadata snapshot predating every outbound write.
+ await updateExternalLink(link.id, {
+ metadata: {
+ remoteMarker: "keep",
+ state: "closed",
+ lastSync: {
+ title: {
+ source: "github",
+ value: "remote",
+ timestamp: "2000-01-01T00:00:00Z",
+ outbound: [],
+ },
+ },
+ },
+ });
+ const saved = await db.query.externalLinkTable.findFirst({
+ where: eq(schema.externalLinkTable.id, link.id),
+ });
+ const metadata = JSON.parse(saved!.metadata!);
+ expect(metadata.remoteMarker).toBe("keep");
+ expect(metadata.lastSync.title).toEqual(latestTitleStamp);
+ for (let i = 0; i < 12; i++)
+ expect(
+ isOutboundEcho(
+ metadata.lastSync[i % 2 ? "description" : "title"],
+ `edit-${i}`,
+ `time-${i}`,
+ ),
+ ).toBe(true);
+});
+
+it("keeps outbound history committed during an inbound provider read", async () => {
+ const { updateExternalLink } =
+ await import("../../apps/api/src/plugins/github/services/link-manager");
+ const { isOutboundEcho } =
+ await import("../../apps/api/src/plugins/github/utils/sync-echo");
+ const { link } = await setup();
+ const { outboundStamp } =
+ await import("../../apps/api/src/plugins/github/utils/sync-echo");
+ await db
+ .update(schema.externalLinkTable)
+ .set({
+ metadata: JSON.stringify({
+ lastSync: {
+ title: outboundStamp(
+ outboundStamp(undefined, remoteIssue.title),
+ "Latest local",
+ ),
+ },
+ }),
+ })
+ .where(eq(schema.externalLinkTable.id, link.id));
+ m.getIssue.mockImplementationOnce(async () => {
+ await updateExternalLink(link.id, {
+ outbound: {
+ field: "title",
+ value: "Local edit",
+ updatedAt: "local-time",
+ },
+ });
+ return remoteIssue;
+ });
+ await handleGiteaIssueEdited({
+ action: "edited",
+ repository,
+ issue: remoteIssue,
+ changes: { title: { from: "Old" } },
+ });
+ expect(m.getIssue).toHaveBeenCalledOnce();
+ const saved = await db.query.externalLinkTable.findFirst({
+ where: eq(schema.externalLinkTable.id, link.id),
+ });
+ expect(
+ isOutboundEcho(
+ JSON.parse(saved!.metadata!).lastSync.title,
+ "Local edit",
+ "local-time",
+ ),
+ ).toBe(true);
+});
+ it.each(["edit", "labels", "comment"])(
+ "ignores a stale %s webhook after its link is removed during a move and return",
+ async (kind) => {
+ const f = await setup();
+ const transaction = getDatabase().transaction.bind(getDatabase());
+ const intercepted = vi
+ .spyOn(getDatabase(), "transaction")
+ .mockImplementationOnce(async (apply, config) => {
+ await moveTask({
+ taskId: f.task.id,
+ destinationProjectId: f.destination.id,
+ userId: f.source.user.id,
+ });
+ await moveTask({
+ taskId: f.task.id,
+ destinationProjectId: f.project.id,
+ userId: f.source.user.id,
+ });
+ return transaction(apply, config);
+ });
+ try {
+ if (kind === "edit")
+ await handleGiteaIssueEdited(
+ {
+ action: "edited",
+ issue: remoteIssue,
+ repository,
+ changes: {
+ title: { from: "Private title" },
+ body: { from: "Private description" },
+ },
+ },
+ f.integration.id,
+ );
+ if (kind === "labels")
+ await handleGiteaIssueLabeled(
+ {
+ action: "labeled",
+ issue: {
+ number: 1,
+ labels: [{ name: "priority:high" }, { name: "bug" }],
+ },
+ label: { name: "bug", color: "ff0000" },
+ repository,
+ },
+ f.integration.id,
+ );
+ if (kind === "comment")
+ await handleGiteaIssueCommentCreated(
+ {
+ action: "created",
+ issue: { number: 1 },
+ repository,
+ comment: {
+ id: 4,
+ body: "Wrong workspace",
+ html_url: `${remoteIssue.html_url}#comment-4`,
+ user: { login: "author", avatar_url: "" },
+ created_at: new Date().toISOString(),
+ },
+ },
+ f.integration.id,
+ );
+ await expectPrivateTask(f.task.id);
+ } finally {
+ intercepted.mockRestore();
+ }
+ },
+ );
diff --cc tests/api/plugins/gitea/rapid-text-sync.test.ts
index d70f4f462,000000000..5caf5fd4c
mode 100644,000000..100644
--- a/tests/api/plugins/gitea/rapid-text-sync.test.ts
+++ b/tests/api/plugins/gitea/rapid-text-sync.test.ts
@@@ -1,370 -1,0 +1,423 @@@
+import { outboundStamp } from "../../../../apps/api/src/plugins/github/utils/sync-echo";
+import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
+import { handleGiteaIssueEdited } from "../../../../apps/api/src/plugins/gitea/webhooks/issue-edited";
+const m = vi.hoisted(() => ({
+ metadata: "",
+ lockedMetadata: undefined as string | undefined,
+ getIssue: vi.fn(),
+ status: vi.fn(),
+ writes: vi.fn(),
+ linkWrites: vi.fn(),
+}));
+vi.mock("../../../../apps/api/src/database", () => ({
+ default: {
+ query: {
+ externalLinkTable: {
+ findFirst: async () => ({
+ id: "link",
+ taskId: "task",
+ metadata: m.metadata,
+ }),
+ },
+ taskTable: {
+ findFirst: async () => ({ id: "task", projectId: "project" }),
+ },
+ },
+ update: () => ({
+ set: m.writes.mockReturnValue({ where: async () => undefined }),
+ }),
+ },
+}));
+vi.mock(
+ "../../../../apps/api/src/plugins/github/services/integration-task-scope",
+ async (original) => ({
+ ...(await original<
+ typeof import("../../../../apps/api/src/plugins/github/services/integration-task-scope")
+ >()),
+ withIntegrationTask: async (
+ _id: string,
+ _scope: unknown,
+ apply: (database: unknown) => Promise<unknown>,
+ ) => apply((await import("../../../../apps/api/src/database")).default),
+ }),
+);
+vi.mock(
+ "../../../../apps/api/src/plugins/github/services/link-manager",
+ () => ({
+ findExternalLink: async () => ({
+ id: "link",
+ taskId: "task",
+ metadata: m.metadata,
+ }),
+ updateExternalLink: m.linkWrites,
+ lockExternalLink: async () => ({
+ id: "link",
+ metadata: m.lockedMetadata ?? m.metadata,
+ }),
+ }),
+);
+vi.mock(
+ "../../../../apps/api/src/plugins/gitea/services/integration-lookup",
+ () => ({
+ findAllIntegrationsByGiteaRepo: async () => [
+ {
+ id: "integration",
+ projectId: "project",
+ config: JSON.stringify({
+ baseUrl: "https://gitea.example",
+ accessToken: "test",
+ repositoryOwner: "owner",
+ repositoryName: "repo",
+ }),
+ },
+ ],
+ repoOwnerLogin: () => "owner",
+ }),
+);
+vi.mock("../../../../apps/api/src/plugins/gitea/utils/gitea-api", () => ({
+ createGiteaClient: () => ({ getIssue: m.getIssue }),
+}));
++vi.mock(
++ "../../../../apps/api/src/plugins/github/services/with-integration-link",
++ () => ({
++ withIntegrationLink: async (
++ _link: unknown,
++ _scope: unknown,
++ apply: (
++ database: unknown,
++ afterCommit: unknown,
++ link: unknown,
++ ) => Promise<unknown>,
++ ) =>
++ apply(
++ (await import("../../../../apps/api/src/database")).default,
++ () => {},
++ {
++ id: "link",
++ taskId: "task",
++ metadata: m.lockedMetadata ?? m.metadata,
++ },
++ ),
++ }),
++);
+const payload = {
+ action: "edited",
+ repository: {
+ owner: { login: "owner" },
+ name: "repo",
+ html_url: "https://gitea.example/owner/repo",
+ },
+ issue: {
+ number: 1,
+ title: "Remote correction",
+ body: "Remote description",
+ html_url: "https://gitea.example/owner/repo/issues/1",
+ },
+ changes: { title: { from: "Old" }, body: { from: "Old body" } },
+};
+beforeEach(() => {
+ vi.clearAllMocks();
+ m.lockedMetadata = undefined;
+ m.getIssue.mockResolvedValue({ title: "Newest title", body: "Newest body" });
+ m.metadata = JSON.stringify({
+ lastSync: {
+ title: {
+ source: "kaneo",
+ value: "Local title",
+ timestamp: new Date().toISOString(),
+ },
+ description: {
+ source: "kaneo",
+ value: "Local description",
+ timestamp: new Date().toISOString(),
+ },
+ },
+ });
+});
+describe("rapid gitea text edits", () => {
+ it("applies a different title and description immediately after an outbound sync", async () => {
+ await handleGiteaIssueEdited(payload);
+ expect(m.writes).toHaveBeenCalledWith({
+ title: "Remote correction",
+ description: "Remote description",
+ });
+ });
+ it("still ignores exact title and description echoes", async () => {
+ await handleGiteaIssueEdited({
+ ...payload,
+ issue: {
+ ...payload.issue,
+ title: "Local title",
+ body: "Local description",
+ },
+ });
+ expect(m.writes).not.toHaveBeenCalled();
+ });
+});
+
+it("ignores a delayed first echo after a newer outbound edit", async () => {
+ m.metadata = JSON.stringify({
+ lastSync: {
+ title: outboundStamp(
+ outboundStamp(undefined, "Earlier title", "2026-01-01T00:00:00Z"),
+ "Newest title",
+ "2026-01-01T00:00:01Z",
+ ),
+ description: outboundStamp(
+ outboundStamp(undefined, "Earlier body", "2026-01-01T00:00:00Z"),
+ "Newest body",
+ "2026-01-01T00:00:01Z",
+ ),
+ },
+ });
+ await handleGiteaIssueEdited({
+ ...payload,
+ issue: {
+ ...payload.issue,
+ title: "Earlier title",
+ body: "Earlier body",
+ updated_at: "2026-01-01T00:00:00Z",
+ },
+ });
+ expect(m.writes).not.toHaveBeenCalled();
+});
+it("allows a new remote edit back to an older outbound value", async () => {
+ m.metadata = JSON.stringify({
+ lastSync: {
+ title: outboundStamp(
+ outboundStamp(undefined, "Earlier title", "2026-01-01T00:00:00Z"),
+ "Newest title",
+ "2026-01-01T00:00:01Z",
+ ),
+ },
+ });
+ await handleGiteaIssueEdited({
+ ...payload,
+ changes: { title: { from: "Newest title" } },
+ issue: {
+ ...payload.issue,
+ title: "Earlier title",
+ updated_at: "2026-01-01T00:00:02Z",
+ },
+ });
+ expect(m.writes).toHaveBeenCalledWith({ title: "Earlier title" });
+});
+
+vi.mock(
+ "../../../../apps/api/src/plugins/github/services/task-service",
+ () => ({ updateTaskStatus: m.status }),
+);
+vi.mock("../../../../apps/api/src/plugins/gitea/utils/resolve-column", () => ({
+ resolveTargetStatus: async (
+ _project: string,
+ _event: string,
+ fallback: string,
+ ) => fallback,
+}));
+it("ignores an older close echo after a newer outbound reopen", async () => {
+ const { handleGiteaIssueClosed } =
+ await import("../../../../apps/api/src/plugins/gitea/webhooks/issue-closed");
+ m.metadata = JSON.stringify({
+ state: "open",
+ lastSync: {
+ state: outboundStamp(
+ outboundStamp(undefined, "closed", "2026-01-01T00:00:00Z"),
+ "open",
+ "2026-01-01T00:00:01Z",
+ ),
+ },
+ });
+ m.getIssue.mockResolvedValue({ state: "open" });
+ await handleGiteaIssueClosed({
+ ...payload,
+ action: "closed",
+ issue: {
+ ...payload.issue,
+ state: "closed",
+ updated_at: "2026-01-01T00:00:00Z",
+ },
+ });
+ expect(m.status).not.toHaveBeenCalled();
+});
+it("ignores an older reopen echo after a newer outbound close", async () => {
+ const { handleGiteaIssueReopened } =
+ await import("../../../../apps/api/src/plugins/gitea/webhooks/issue-reopened");
+ m.metadata = JSON.stringify({
+ state: "closed",
+ lastSync: {
+ state: outboundStamp(
+ outboundStamp(undefined, "open", "2026-01-01T00:00:00Z"),
+ "closed",
+ "2026-01-01T00:00:01Z",
+ ),
+ },
+ });
+ m.getIssue.mockResolvedValue({ state: "closed" });
+ await handleGiteaIssueReopened({
+ ...payload,
+ action: "reopened",
+ issue: {
+ ...payload.issue,
+ state: "open",
+ updated_at: "2026-01-01T00:00:00Z",
+ },
+ });
+ expect(m.status).not.toHaveBeenCalled();
+});
+
+it("accepts a legitimate remote edit matching a historical outbound value within the same timestamp", async () => {
+ const stamp = "2026-01-01T00:00:00Z";
+ m.metadata = JSON.stringify({
+ lastSync: {
+ title: outboundStamp(
+ outboundStamp(undefined, "Earlier title", stamp),
+ "Newest title",
+ stamp,
+ ),
+ description: outboundStamp(
+ outboundStamp(undefined, "Earlier body", stamp),
+ "Newest body",
+ stamp,
+ ),
+ },
+ });
+ m.getIssue.mockResolvedValue({
+ title: "Earlier title",
+ body: "Earlier body",
+ });
+ await handleGiteaIssueEdited({
+ ...payload,
+ issue: {
+ ...payload.issue,
+ title: "Earlier title",
+ body: "Earlier body",
+ updated_at: stamp,
+ },
+ });
+ expect(m.writes).toHaveBeenCalledWith({
+ title: "Earlier title",
+ description: "Earlier body",
+ });
+ expect(m.getIssue).toHaveBeenCalledTimes(1);
+});
+
+it("ignores the linked task footer when detecting a description echo", async () => {
+ await handleGiteaIssueEdited({
+ ...payload,
+ changes: { body: { from: "Old" } },
+ issue: {
+ ...payload.issue,
+ body: "Local description\n\n---\n<sub>Task: task</sub>",
+ },
+ });
+ expect(m.writes).not.toHaveBeenCalled();
+});
+it("accepts a same-timestamp remote close matching historical outbound state", async () => {
+ const { handleGiteaIssueClosed } =
+ await import("../../../../apps/api/src/plugins/gitea/webhooks/issue-closed");
+ const stamp = "2026-01-01T00:00:00Z";
+ m.metadata = JSON.stringify({
+ state: "open",
+ lastSync: {
+ state: outboundStamp(
+ outboundStamp(undefined, "closed", stamp),
+ "open",
+ stamp,
+ ),
+ },
+ });
+ m.getIssue.mockResolvedValue({ state: "closed" });
+ m.status.mockResolvedValue({ applied: false });
+ await handleGiteaIssueClosed({
+ ...payload,
+ action: "closed",
+ issue: { ...payload.issue, state: "closed", updated_at: stamp },
+ });
+ expect(m.status).toHaveBeenCalled();
+});
+
+it("retains outbound stamps added after the initial inbound snapshot", async () => {
+ m.metadata = JSON.stringify({ lastSync: {} });
+ const stamp = outboundStamp(undefined, "New local title", "new-time");
+ m.lockedMetadata = JSON.stringify({
+ marker: "preserve",
+ lastSync: { title: stamp },
+ });
+ await handleGiteaIssueEdited(payload);
+ expect(
+ m.linkWrites.mock.calls[0][1].metadata.lastSync.title.outbound,
+ ).toEqual(stamp.outbound);
+ expect(m.linkWrites.mock.calls[0][1].metadata.marker).toBe("preserve");
+});
+
+it("recognizes a delayed echo whose stamp arrives before the locked reread", async () => {
+ m.metadata = JSON.stringify({ lastSync: {} });
+ m.lockedMetadata = JSON.stringify({
+ lastSync: {
+ title: outboundStamp(undefined, payload.issue.title, undefined),
+ },
+ });
+ await handleGiteaIssueEdited({
+ ...payload,
+ changes: { title: payload.changes.title },
+ });
+ expect(m.writes).not.toHaveBeenCalled();
+});
+
+it("applies an ordinary complete webhook without consulting an unavailable provider", async () => {
+ m.metadata = JSON.stringify({ lastSync: {} });
+ m.getIssue.mockRejectedValue(new Error("provider unavailable"));
+ await handleGiteaIssueEdited(payload);
+ expect(m.getIssue).not.toHaveBeenCalled();
+ expect(m.writes).toHaveBeenCalledWith(
+ expect.objectContaining({
+ title: payload.issue.title,
+ description: payload.issue.body,
+ }),
+ );
+});
+
+it("rechecks a close echo from the locked state snapshot", async () => {
+ m.metadata = JSON.stringify({ lastSync: {} });
+ m.lockedMetadata = JSON.stringify({
+ lastSync: { state: outboundStamp(undefined, "closed") },
+ });
+ const { handleGiteaIssueClosed } =
+ await import("../../../../apps/api/src/plugins/gitea/webhooks/issue-closed");
+ await handleGiteaIssueClosed({
+ action: "closed",
+ repository: payload.repository,
+ issue: { ...payload.issue, state: "closed" },
+ });
+ expect(m.status).not.toHaveBeenCalled();
+});
++
++it("applies a close following an inbound reopen within the same provider timestamp", async () => {
++ const { handleGiteaIssueClosed } =
++ await import("../../../../apps/api/src/plugins/gitea/webhooks/issue-closed");
++ const { handleGiteaIssueReopened } =
++ await import("../../../../apps/api/src/plugins/gitea/webhooks/issue-reopened");
++ const stamp = "2026-01-01T00:00:00Z";
++ m.metadata = JSON.stringify({
++ state: "closed",
++ lastSync: { state: outboundStamp(undefined, "closed", stamp) },
++ });
++ m.status.mockResolvedValue({ applied: false });
++ m.linkWrites.mockImplementation(async (_id, update) => {
++ m.metadata = JSON.stringify(update.metadata);
++ });
++ await handleGiteaIssueReopened({
++ ...payload,
++ action: "reopened",
++ issue: { ...payload.issue, state: "open", updated_at: stamp },
++ });
++ expect(JSON.parse(m.metadata).lastSync.state.value).toBe("open");
++ m.getIssue.mockResolvedValue({ state: "closed" });
++ await handleGiteaIssueClosed({
++ ...payload,
++ action: "closed",
++ issue: { ...payload.issue, state: "closed", updated_at: stamp },
++ });
++ expect(m.status).toHaveBeenCalledTimes(2);
++ expect(JSON.parse(m.metadata).state).toBe("closed");
++});
diff --cc tests/api/plugins/github/rapid-text-sync.test.ts
index dc01551bb,000000000..8349d86da
mode 100644,000000..100644
--- a/tests/api/plugins/github/rapid-text-sync.test.ts
+++ b/tests/api/plugins/github/rapid-text-sync.test.ts
@@@ -1,140 -1,0 +1,233 @@@
+import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
+
+const m = vi.hoisted(() => ({
+ current: { title: "", description: "" },
+ links: vi.fn(),
+ update: vi.fn(),
+ save: vi.fn(),
+}));
+vi.mock(
+ "../../../../apps/api/src/plugins/github/services/link-manager",
+ () => ({ findExternalLinksByTask: m.links, updateExternalLink: m.save }),
+);
+vi.mock("../../../../apps/api/src/plugins/github/utils/github-app", () => ({
+ getGithubApp: () => ({}),
+ getVerifiedInstallationOctokit: async () => ({
+ rest: { issues: { update: m.update } },
+ }),
+}));
+vi.mock("../../../../apps/api/src/database", () => ({
+ default: { query: { taskTable: { findFirst: async () => m.current } } },
+}));
+const { handleTaskTitleChanged } =
+ await import("../../../../apps/api/src/plugins/github/events/task-title-changed");
+const { handleTaskDescriptionChanged } =
+ await import("../../../../apps/api/src/plugins/github/events/task-description-changed");
+const context = {
+ integrationId: "integration",
+ projectId: "project",
+ config: {
+ repositoryOwner: "owner",
+ repositoryName: "repo",
+ installationId: 1,
+ repositoryId: 2,
+ verifiedGithubAccountId: "3",
+ verifiedByUserId: "user",
+ },
+};
- beforeEach(() => vi.clearAllMocks());
++beforeEach(() => vi.resetAllMocks());
+function link(field: string, source: string, value: string) {
+ return {
+ id: "link",
+ integrationId: "integration",
+ taskId: "task",
+ resourceType: "issue",
+ externalId: "1",
+ metadata: JSON.stringify({
+ lastSync: {
+ [field]: { source, value, timestamp: new Date().toISOString() },
+ },
+ }),
+ };
+}
+describe("rapid github text edits", () => {
+ it("sends a second local title even immediately after the first sync", async () => {
+ m.current.title = "Second title";
+ m.links.mockResolvedValue([link("title", "kaneo", "First title")]);
+ await handleTaskTitleChanged(
+ {
+ taskId: "task",
+ projectId: "project",
+ userId: "user",
+ oldTitle: "First title",
+ newTitle: "Second title",
+ },
+ context,
+ );
+ expect(m.update).toHaveBeenCalledWith(
+ expect.objectContaining({ title: "Second title" }),
+ );
+ });
+ it("sends a different title immediately after an incoming github title", async () => {
+ m.current.title = "Local correction";
+ m.links.mockResolvedValue([link("title", "github", "Remote title")]);
+ await handleTaskTitleChanged(
+ {
+ taskId: "task",
+ projectId: "project",
+ userId: "user",
+ oldTitle: "Remote title",
+ newTitle: "Local correction",
+ },
+ context,
+ );
+ expect(m.update).toHaveBeenCalledWith(
+ expect.objectContaining({ title: "Local correction" }),
+ );
+ });
+ it("keeps suppressing an exact incoming echo", async () => {
+ m.current.title = "Remote title";
+ m.links.mockResolvedValue([link("title", "github", "Remote title")]);
+ await handleTaskTitleChanged(
+ {
+ taskId: "task",
+ projectId: "project",
+ userId: "user",
+ oldTitle: "Old",
+ newTitle: "Remote title",
+ },
+ context,
+ );
+ expect(m.update).not.toHaveBeenCalled();
+ });
+ it("sends a second local description immediately after the first sync", async () => {
+ m.current.description = "Second description";
+ m.links.mockResolvedValue([
+ link("description", "kaneo", "First description"),
+ ]);
+ await handleTaskDescriptionChanged(
+ {
+ taskId: "task",
+ projectId: "project",
+ userId: "user",
+ oldDescription: "First description",
+ newDescription: "Second description",
+ },
+ context,
+ );
+ expect(m.update).toHaveBeenCalledWith(
+ expect.objectContaining({
+ body: expect.stringContaining("Second description"),
+ }),
+ );
+ });
+});
+
+it("does not send a queued title after a newer task edit", async () => {
+ m.current.title = "Newest";
+ m.links.mockResolvedValue([link("title", "kaneo", "Old")]);
+ await handleTaskTitleChanged(
+ {
+ taskId: "task",
+ projectId: "project",
+ userId: "user",
+ oldTitle: "Old",
+ newTitle: "Queued",
+ },
+ context,
+ );
+ expect(m.update).not.toHaveBeenCalled();
+});
++
++vi.mock("../../../../apps/api/src/plugins/gitea/utils/gitea-api", () => ({
++ createGiteaClient: () => ({
++ updateIssue: async (
++ _owner: string,
++ _repo: string,
++ _number: number,
++ input: unknown,
++ ) => m.update(input),
++ }),
++}));
++const giteaTitle = (
++ await import("../../../../apps/api/src/plugins/gitea/events/task-title-changed")
++).handleTaskTitleChanged;
++const giteaDescription = (
++ await import("../../../../apps/api/src/plugins/gitea/events/task-description-changed")
++).handleTaskDescriptionChanged;
++it.each([
++ ["github", "title"],
++ ["github", "description"],
++ ["gitea", "title"],
++ ["gitea", "description"],
++])(
++ "repairs %s %s when an older request completes after the latest edit",
++ async (provider, field) => {
++ let finishOld!: () => void;
++ let oldStarted!: () => void;
++ const started = new Promise<void>((resolve) => {
++ oldStarted = resolve;
++ });
++ const delayed = new Promise<void>((resolve) => {
++ finishOld = resolve;
++ });
++ let remote = "";
++ m.current.title = "A";
++ m.current.description = "A";
++ m.links.mockResolvedValue([link(field, "kaneo", "Before")]);
++ m.update.mockImplementation(async (input) => {
++ const value =
++ field === "title" ? input.title : input.body.split("\n\n---")[0];
++ if (value === "A") {
++ oldStarted();
++ await delayed;
++ }
++ remote = value;
++ return {
++ updated_at: "provider-time",
++ data: { updated_at: "provider-time" },
++ };
++ });
++ const handler =
++ provider === "github"
++ ? field === "title"
++ ? handleTaskTitleChanged
++ : handleTaskDescriptionChanged
++ : field === "title"
++ ? giteaTitle
++ : giteaDescription;
++ const config =
++ provider === "github"
++ ? context
++ : {
++ ...context,
++ config: {
++ ...context.config,
++ baseUrl: "https://gitea.example",
++ accessToken: "test",
++ },
++ };
++ function event(value: string) {
++ return {
++ taskId: "task",
++ projectId: "project",
++ userId: "user",
++ oldTitle: "Before",
++ newTitle: value,
++ oldDescription: "Before",
++ newDescription: value,
++ };
++ }
++ const first = handler(event("A"), config);
++ await started;
++ m.current.title = "B";
++ m.current.description = "B";
++ await handler(event("B"), config);
++ expect(remote).toBe("B");
++ finishOld();
++ await first;
++ expect(remote).toBe("B");
++ expect(m.update).toHaveBeenCalledTimes(3);
++ expect(m.save.mock.calls.at(-1)?.[1].outbound.value).toBe("B");
++ },
++);