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): confirm historical text echoes with provider state

Tin5af0a82dcead
diff --cc apps/api/src/plugins/gitea/webhooks/issue-edited.ts
index d96c51c43,7709dade2..61de0b600
--- a/apps/api/src/plugins/gitea/webhooks/issue-edited.ts
+++ b/apps/api/src/plugins/gitea/webhooks/issue-edited.ts
@@@ -1,4 -1,3 +1,6 @@@
- import { isOutboundEcho } from "../../github/utils/sync-echo";
++import type { GiteaConfig } from "../config";
++import { createGiteaClient } from "../utils/gitea-api";
++import { confirmedOutboundEcho } from "../../github/utils/sync-echo";
import {
linkedTaskScope,
withIntegrationTask,
@@@ -67,6 -65,6 +69,38 @@@ export async function handleGiteaIssueE
continue;
}
++ const echoMetadata = externalLink.metadata
++ ? JSON.parse(externalLink.metadata)
++ : {};
++ const fetchCurrentIssue = async () => {
++ const config = JSON.parse(integration.config) as GiteaConfig;
++ return createGiteaClient(config).getIssue(
++ config.repositoryOwner,
++ config.repositoryName,
++ issue.number,
++ );
++ };
++ let current: ReturnType<typeof fetchCurrentIssue> | undefined;
++ const currentIssue = () => (current ??= fetchCurrentIssue());
++ // Read the provider before taking task/project locks.
++ const titleEcho = changes.title
++ ? await confirmedOutboundEcho(
++ echoMetadata.lastSync?.title,
++ issue.title,
++ issue.updated_at,
++ async () => (await currentIssue()).title,
++ )
++ : false;
++ const descriptionEcho = changes.body
++ ? await confirmedOutboundEcho(
++ echoMetadata.lastSync?.description,
++ formatTaskDescriptionFromIssue(issue.body),
++ issue.updated_at,
++ async () =>
++ formatTaskDescriptionFromIssue((await currentIssue()).body ?? null),
++ )
++ : false;
++
await withIntegrationTask(externalLink.taskId, integration, async (db) => {
const task = await db.query.taskTable.findFirst({
where: linkedTaskScope(externalLink.taskId, integration.projectId),
@@@ -93,7 -91,15 +127,7 @@@
let shouldUpdateTitle = true;
if (lastTitleSync) {
- if (isOutboundEcho(lastTitleSync, issue.title, issue.updated_at)) {
- if (
- lastTitleSync.value === issue.title &&
- lastTitleSync.source === "kaneo"
- ) {
- shouldUpdateTitle = false;
- }
- const timeSinceLastSync =
- Date.now() - new Date(lastTitleSync.timestamp).getTime();
- if (timeSinceLastSync < 2000 && shouldUpdateTitle) {
++ if (titleEcho) {
shouldUpdateTitle = false;
}
}
@@@ -116,9 -121,15 +150,7 @@@
let shouldUpdateDescription = true;
if (lastDescSync) {
-- if (
- isOutboundEcho(lastDescSync, formattedDescription, issue.updated_at)
- lastDescSync.value === formattedDescription &&
- lastDescSync.source === "kaneo"
-- ) {
- shouldUpdateDescription = false;
- }
- const timeSinceLastSync =
- Date.now() - new Date(lastDescSync.timestamp).getTime();
- if (timeSinceLastSync < 2000 && shouldUpdateDescription) {
++ if (descriptionEcho) {
shouldUpdateDescription = false;
}
}
diff --cc apps/api/src/plugins/github/utils/sync-echo.ts
index 63c01f96c,000000000..81c411f6c
mode 100644,000000..100644
--- a/apps/api/src/plugins/github/utils/sync-echo.ts
+++ b/apps/api/src/plugins/github/utils/sync-echo.ts
@@@ -1,57 -1,0 +1,69 @@@
+import { createHash } from "node:crypto";
+
+export type SyncStamp = {
+ timestamp?: string;
+ source?: string;
+ value?: string;
+ outbound?: Array<{ hash: string; timestamp: string; updatedAt?: string }>;
+};
+
+const hash = (value: string) =>
+ createHash("sha256").update(value).digest("hex");
+
+export function outboundStamp(
+ previous: SyncStamp | undefined,
+ value: string,
+ updatedAt?: string,
+): SyncStamp {
+ const timestamp = new Date().toISOString();
+ const outbound = [...(previous?.outbound ?? [])];
+ // Older installations have only the last value, without a provider timestamp.
+ if (
+ previous?.source === "kaneo" &&
+ !previous.outbound?.length &&
+ previous.value !== undefined &&
+ previous.timestamp
+ )
+ outbound.push({
+ hash: hash(previous.value),
+ timestamp: previous.timestamp,
+ });
+ outbound.push({ hash: hash(value), timestamp, updatedAt });
+ return { timestamp, source: "kaneo", value, outbound: outbound.slice(-32) };
+}
+
+export function isOutboundEcho(
+ stamp: SyncStamp | undefined,
+ value: string,
+ updatedAt?: string,
+): boolean {
+ if (!stamp) return false;
+ const entries = stamp.outbound ?? [];
+ const valueHash = hash(value);
+ if (
+ entries.some(
+ (entry) =>
+ entry.hash === valueHash &&
+ (entry.updatedAt && updatedAt
+ ? entry.updatedAt === updatedAt
+ : Date.now() - Date.parse(entry.timestamp) < 300_000),
+ )
+ )
+ return true;
+ // Preserve compatibility with stamps written before outbound history existed.
+ return (
+ entries.length === 0 && stamp.source === "kaneo" && stamp.value === value
+ );
+}
++
++/** Provider timestamps can collide; historical values need current-provider confirmation. */
++export async function confirmedOutboundEcho(
++ stamp: SyncStamp | undefined,
++ value: string,
++ updatedAt: string | undefined,
++ readCurrent: () => Promise<string>,
++) {
++ if (!isOutboundEcho(stamp, value, updatedAt)) return false;
++ if (stamp?.value === value) return true;
++ return (await readCurrent()) !== value;
++}
diff --cc apps/api/src/plugins/github/webhooks/issue-edited.ts
index 3e3956d8d,7a91fd900..1fa8e4411
--- a/apps/api/src/plugins/github/webhooks/issue-edited.ts
+++ b/apps/api/src/plugins/github/webhooks/issue-edited.ts
@@@ -1,4 -1,3 +1,6 @@@
- import { isOutboundEcho } from "../utils/sync-echo";
++import type { GitHubConfig } from "../config";
++import { getVerifiedInstallationOctokit } from "../utils/github-app";
++import { confirmedOutboundEcho } from "../utils/sync-echo";
import {
linkedTaskScope,
withIntegrationTask,
@@@ -69,6 -71,6 +71,45 @@@ export async function handleIssueEdited
continue;
}
++ const echoMetadata = parseLinkMetadata<IssueEditedMetadata>(
++ externalLink.metadata,
++ { externalLinkId: externalLink.id, source: "issue_edited" },
++ );
++ const fetchCurrentIssue = async () => {
++ 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;
++ };
++ let current: ReturnType<typeof fetchCurrentIssue> | undefined;
++ const currentIssue = () => (current ??= fetchCurrentIssue());
++ // Read the provider before taking task/project locks.
++ const titleEcho = changes.title
++ ? await confirmedOutboundEcho(
++ echoMetadata.lastSync?.title,
++ issue.title,
++ issue.updated_at,
++ async () => (await currentIssue()).title,
++ )
++ : false;
++ const descriptionEcho = changes.body
++ ? await confirmedOutboundEcho(
++ echoMetadata.lastSync?.description,
++ formatTaskDescriptionFromIssue(issue.body, externalLink.taskId),
++ issue.updated_at,
++ async () =>
++ formatTaskDescriptionFromIssue(
++ (await currentIssue()).body ?? null,
++ externalLink.taskId,
++ ),
++ )
++ : false;
++
await withIntegrationTask(externalLink.taskId, integration, async (db) => {
const task = await db.query.taskTable.findFirst({
where: linkedTaskScope(externalLink.taskId, integration.projectId),
@@@ -100,7 -102,10 +141,7 @@@
let shouldUpdateTitle = true;
if (lastTitleSync) {
- if (isOutboundEcho(lastTitleSync, issue.title, issue.updated_at)) {
- if (
- lastTitleSync.value === issue.title &&
- lastTitleSync.source === "kaneo"
- ) {
++ if (titleEcho) {
console.log("Skipping title update - already synced from Kaneo");
shouldUpdateTitle = false;
}
@@@ -130,9 -142,10 +171,7 @@@
let shouldUpdateDescription = true;
if (lastDescSync) {
-- if (
- isOutboundEcho(lastDescSync, formattedDescription, issue.updated_at)
- lastDescSync.value === formattedDescription &&
- lastDescSync.source === "kaneo"
-- ) {
++ if (descriptionEcho) {
console.log(
"Skipping description update - already synced from Kaneo",
);
diff --cc tests/api/plugins/gitea/rapid-text-sync.test.ts
index 7c9d5dc6a,000000000..4e4acbb5a
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,221 -1,0 +1,271 @@@
+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: "",
++ 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,
+ }),
+);
+vi.mock(
+ "../../../../apps/api/src/plugins/gitea/services/integration-lookup",
+ () => ({
+ findAllIntegrationsByGiteaRepo: async () => [
- { id: "integration", projectId: "project" },
++ {
++ 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 }),
++}));
+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.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",
+ ),
+ },
+ });
+ 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",
+ ),
+ },
+ });
+ 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);
++});