Skip to content

armgit / kaneo

Public Imported from GitHub
0

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

fix(integrations): preserve timestamp collisions and bound pending webhook waits

Tinc7711aa90902
diff --git a/apps/api/src/plugins/gitea/events/task-description-changed.ts b/apps/api/src/plugins/gitea/events/task-description-changed.ts
index a76858a58..25a4c064c 100644
--- a/apps/api/src/plugins/gitea/events/task-description-changed.ts
+++ b/apps/api/src/plugins/gitea/events/task-description-changed.ts
@@ -2,7 +2,10 @@ import { syncLatestTaskValue } from "../../github/services/sync-latest-task-valu
import db from "../../../database";
import { linkedTaskScope } from "../../github/services/integration-task-scope";
import { findExternalLinksByTask } from "../../github/services/link-manager";
-import { formatIssueBody } from "../../github/utils/format";
+import {
+ formatIssueBody,
+ formatTaskDescriptionFromIssue,
+} from "../../github/utils/format";
import type { PluginContext, TaskDescriptionChangedEvent } from "../../types";
import type { GiteaConfig } from "../config";
import { createGiteaClient } from "../utils/gitea-api";
@@ -107,6 +110,12 @@ export async function handleTaskDescriptionChanged(
);
return response?.updated_at;
},
+ async () =>
+ formatTaskDescriptionFromIssue(
+ (await client.getIssue(repositoryOwner, repositoryName, issueNumber))
+ .body ?? null,
+ event.taskId,
+ ),
);
console.log(`Synced task description to Gitea issue #${issueNumber}`);
diff --git a/apps/api/src/plugins/gitea/events/task-status-changed.ts b/apps/api/src/plugins/gitea/events/task-status-changed.ts
index 4b03ab3ad..f0306bbcc 100644
--- a/apps/api/src/plugins/gitea/events/task-status-changed.ts
+++ b/apps/api/src/plugins/gitea/events/task-status-changed.ts
@@ -53,6 +53,9 @@ export async function handleTaskStatusChanged(
);
return response?.updated_at;
},
+ async () =>
+ (await client.getIssue(repositoryOwner, repositoryName, issueNumber))
+ .state ?? "open",
);
}
} catch (error) {
diff --git a/apps/api/src/plugins/gitea/events/task-title-changed.ts b/apps/api/src/plugins/gitea/events/task-title-changed.ts
index 3fecaf4d9..8d33f4c8e 100644
--- a/apps/api/src/plugins/gitea/events/task-title-changed.ts
+++ b/apps/api/src/plugins/gitea/events/task-title-changed.ts
@@ -100,6 +100,9 @@ export async function handleTaskTitleChanged(
);
return response?.updated_at;
},
+ async () =>
+ (await client.getIssue(repositoryOwner, repositoryName, issueNumber))
+ .title,
);
console.log(`Synced task title to Gitea issue #${issueNumber}`);
diff --git a/apps/api/src/plugins/gitea/webhooks/issue-closed.ts b/apps/api/src/plugins/gitea/webhooks/issue-closed.ts
index 33e6c4941..360e739b9 100644
--- a/apps/api/src/plugins/gitea/webhooks/issue-closed.ts
+++ b/apps/api/src/plugins/gitea/webhooks/issue-closed.ts
@@ -1,3 +1,4 @@
+import { inboundStamp } from "../../github/utils/sync-echo";
import { withIntegrationLink } from "../../github/services/with-integration-link";
import type { GiteaConfig } from "../config";
import { createGiteaClient } from "../utils/gitea-api";
@@ -169,12 +170,11 @@ export async function handleGiteaIssueClosed(
state: "closed",
lastSync: {
...existingMetadata.lastSync,
- state: {
- ...existingMetadata.lastSync?.state,
- source: "gitea",
- value: "closed",
- timestamp: new Date().toISOString(),
- },
+ state: inboundStamp(
+ existingMetadata.lastSync?.state,
+ "closed",
+ "gitea",
+ ),
},
},
},
diff --git a/apps/api/src/plugins/gitea/webhooks/issue-edited.ts b/apps/api/src/plugins/gitea/webhooks/issue-edited.ts
index 46597714d..5c92a83bb 100644
--- a/apps/api/src/plugins/gitea/webhooks/issue-edited.ts
+++ b/apps/api/src/plugins/gitea/webhooks/issue-edited.ts
@@ -1,3 +1,4 @@
+import { inboundStamp } from "../../github/utils/sync-echo";
import { publishEvent } from "../../../events";
import { withIntegrationLink } from "../../github/services/with-integration-link";
import type { GiteaConfig } from "../config";
@@ -127,12 +128,11 @@ export async function handleGiteaIssueEdited(
if (shouldUpdateTitle) {
updateData.title = issue.title;
- updatedMetadata.lastSync.title = {
- outbound: metadata.lastSync?.title?.outbound,
- timestamp: new Date().toISOString(),
- source: "gitea",
- value: issue.title,
- };
+ updatedMetadata.lastSync.title = inboundStamp(
+ metadata.lastSync?.title,
+ issue.title,
+ "gitea",
+ );
}
}
@@ -166,12 +166,11 @@ export async function handleGiteaIssueEdited(
if (shouldUpdateDescription) {
updateData.description = formattedDescription;
- updatedMetadata.lastSync.description = {
- outbound: metadata.lastSync?.description?.outbound,
- timestamp: new Date().toISOString(),
- source: "gitea",
- value: formattedDescription,
- };
+ updatedMetadata.lastSync.description = inboundStamp(
+ metadata.lastSync?.description,
+ formattedDescription,
+ "gitea",
+ );
}
}
diff --git a/apps/api/src/plugins/gitea/webhooks/issue-reopened.ts b/apps/api/src/plugins/gitea/webhooks/issue-reopened.ts
index 76188cff5..ee83a799f 100644
--- a/apps/api/src/plugins/gitea/webhooks/issue-reopened.ts
+++ b/apps/api/src/plugins/gitea/webhooks/issue-reopened.ts
@@ -1,3 +1,4 @@
+import { inboundStamp } from "../../github/utils/sync-echo";
import { withIntegrationLink } from "../../github/services/with-integration-link";
import type { GiteaConfig } from "../config";
import { createGiteaClient } from "../utils/gitea-api";
@@ -5,6 +6,7 @@ import { parseLinkMetadata } from "../../github/utils/parse-link-metadata";
import type { SyncStamp } from "../../github/utils/sync-echo";
import {
inboundEcho,
+ PendingResponseTimeout,
withEchoConfirmation,
} from "../../github/utils/inbound-echo";
import { linkedTaskScope } from "../../github/services/integration-task-scope";
@@ -173,12 +175,11 @@ export async function handleGiteaIssueReopened(
state: "open",
lastSync: {
...existingMetadata.lastSync,
- state: {
- ...existingMetadata.lastSync?.state,
- source: "gitea",
- value: "open",
- timestamp: new Date().toISOString(),
- },
+ state: inboundStamp(
+ existingMetadata.lastSync?.state,
+ "open",
+ "gitea",
+ ),
},
},
},
@@ -188,6 +189,7 @@ export async function handleGiteaIssueReopened(
),
);
} catch (error) {
+ if (error instanceof PendingResponseTimeout) throw error;
console.error("Gitea issue_reopened handler failed for integration", {
integrationId: integration.id,
issueNumber: issue.number,
diff --git a/apps/api/src/plugins/github/events/task-description-changed.ts b/apps/api/src/plugins/github/events/task-description-changed.ts
index ed4f07caf..54ea73108 100644
--- a/apps/api/src/plugins/github/events/task-description-changed.ts
+++ b/apps/api/src/plugins/github/events/task-description-changed.ts
@@ -4,7 +4,10 @@ import { linkedTaskScope } from "../services/integration-task-scope";
import type { PluginContext, TaskDescriptionChangedEvent } from "../../types";
import { type GitHubConfig, hasVerifiedGitHubBinding } from "../config";
import { findExternalLinksByTask } from "../services/link-manager";
-import { formatIssueBody } from "../utils/format";
+import {
+ formatIssueBody,
+ formatTaskDescriptionFromIssue,
+} from "../utils/format";
import {
getGithubApp,
getVerifiedInstallationOctokit,
@@ -81,6 +84,17 @@ export async function handleTaskDescriptionChanged(
});
return response?.data?.updated_at;
},
+ async () =>
+ formatTaskDescriptionFromIssue(
+ (
+ await octokit.rest.issues.get({
+ owner: repositoryOwner,
+ repo: repositoryName,
+ issue_number: issueNumber,
+ })
+ ).data.body ?? null,
+ event.taskId,
+ ),
);
console.log(`Synced task description to GitHub issue #${issueNumber}`);
diff --git a/apps/api/src/plugins/github/events/task-status-changed.ts b/apps/api/src/plugins/github/events/task-status-changed.ts
index cebdc6c80..4ab533bbb 100644
--- a/apps/api/src/plugins/github/events/task-status-changed.ts
+++ b/apps/api/src/plugins/github/events/task-status-changed.ts
@@ -68,6 +68,14 @@ export async function handleTaskStatusChanged(
});
return response?.data?.updated_at;
},
+ async () =>
+ (
+ await octokit.rest.issues.get({
+ owner: repositoryOwner,
+ repo: repositoryName,
+ issue_number: issueNumber,
+ })
+ ).data.state ?? "open",
);
}
} catch (error) {
diff --git a/apps/api/src/plugins/github/events/task-title-changed.ts b/apps/api/src/plugins/github/events/task-title-changed.ts
index 645872fc2..f50a560a0 100644
--- a/apps/api/src/plugins/github/events/task-title-changed.ts
+++ b/apps/api/src/plugins/github/events/task-title-changed.ts
@@ -73,6 +73,14 @@ export async function handleTaskTitleChanged(
});
return response?.data?.updated_at;
},
+ async () =>
+ (
+ await octokit.rest.issues.get({
+ owner: repositoryOwner,
+ repo: repositoryName,
+ issue_number: issueNumber,
+ })
+ ).data.title,
);
console.log(`Synced task title to GitHub issue #${issueNumber}`);
diff --git a/apps/api/src/plugins/github/services/apply-observed-task-value.ts b/apps/api/src/plugins/github/services/apply-observed-task-value.ts
new file mode 100644
index 000000000..b1e4be861
--- /dev/null
+++ b/apps/api/src/plugins/github/services/apply-observed-task-value.ts
@@ -0,0 +1,97 @@
+import { publishEvent } from "../../../events";
+import { taskTable } from "../../../database/schema";
+import { resolveTargetStatus as resolveGiteaStatus } from "../../gitea/utils/resolve-column";
+import { resolveTargetStatus as resolveGithubStatus } from "../utils/resolve-column";
+import {
+ hasNewerObservedEdit,
+ inboundStamp,
+ type SyncStamp,
+} from "../utils/sync-echo";
+import { parseLinkMetadata } from "../utils/parse-link-metadata";
+import { linkedTaskScope } from "./integration-task-scope";
+import { withIntegrationLink } from "./with-integration-link";
+import { updateExternalLink } from "./link-manager";
+import { updateTaskStatus } from "./task-service";
+
+// The observed matching value is durable even if the inbound HTTP request
+// times out waiting for our response. Apply it only after version correlation.
+export async function applyObservedTaskValue(
+ link: { id: string; taskId: string },
+ integration: { id: string; projectId: string; type: string },
+ field: "title" | "description" | "state",
+ value: string,
+ intentId: string,
+ updatedAt: string | undefined,
+) {
+ await withIntegrationLink(
+ link,
+ integration,
+ async (tx, afterCommit, locked) => {
+ const metadata = parseLinkMetadata<
+ Record<string, unknown> & { lastSync?: Record<string, SyncStamp> }
+ >(locked.metadata, {
+ externalLinkId: link.id,
+ source: "observed_provider_edit",
+ });
+ const stamp = metadata.lastSync?.[field];
+ if (
+ !hasNewerObservedEdit(
+ stamp?.outbound?.find((entry) => entry.intentId === intentId),
+ updatedAt,
+ )
+ )
+ return;
+ if (field === "state") {
+ const resolveStatus =
+ integration.type === "gitea"
+ ? resolveGiteaStatus
+ : resolveGithubStatus;
+ const status = await resolveStatus(
+ integration.projectId,
+ value === "closed" ? "issue_closed" : "issue_reopened",
+ value === "closed" ? "done" : "to-do",
+ tx,
+ );
+ const result = await updateTaskStatus(link.taskId, status, tx);
+ if (result.applied && result.before.status !== result.after.status)
+ afterCommit(() =>
+ publishEvent("task.status_changed", {
+ taskId: result.after.id,
+ projectId: result.after.projectId,
+ userId: null,
+ oldStatus: result.before.status,
+ newStatus: result.after.status,
+ title: result.after.title,
+ assigneeId: result.after.userId,
+ type: "status_changed",
+ }),
+ );
+ } else {
+ await tx
+ .update(taskTable)
+ .set({ [field]: value })
+ .where(linkedTaskScope(link.taskId, integration.projectId));
+ }
+ await updateExternalLink(
+ link.id,
+ {
+ metadata: {
+ ...metadata,
+ ...(field === "state" ? { state: value } : {}),
+ lastSync: {
+ ...metadata.lastSync,
+ [field]: inboundStamp(stamp, value, integration.type),
+ },
+ },
+ },
+ tx,
+ );
+ afterCommit(() =>
+ publishEvent("task.updated", {
+ taskId: link.taskId,
+ projectId: integration.projectId,
+ }),
+ );
+ },
+ );
+}
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.ts
index 576815e7b..9b3998148 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,7 +1,8 @@
import { randomUUID } from "node:crypto";
import db from "../../../database";
import { parseLinkMetadata } from "../utils/parse-link-metadata";
-import type { SyncStamp } from "../utils/sync-echo";
+import { hasNewerObservedEdit, type SyncStamp } from "../utils/sync-echo";
+import { applyObservedTaskValue } from "./apply-observed-task-value";
import { linkedTaskScope } from "./integration-task-scope";
import { findExternalLinksByTask, updateExternalLink } from "./link-manager";
@@ -14,6 +15,7 @@ export async function syncLatestTaskValue(
field: "title" | "description" | "state",
initialValue: string,
write: (value: string) => Promise<string | undefined>,
+ readCurrent?: () => Promise<string>,
) {
let value = initialValue;
for (;;) {
@@ -67,11 +69,25 @@ export async function syncLatestTaskValue(
});
const observed = metadata.lastSync?.[field]?.outbound?.find(
(entry) => entry.intentId === intentId,
- )?.observedUpdatedAt;
+ );
// The waiting inbound handler applies this newer provider edit after the
// exact response version is available; do not overwrite it with a repair.
- if (updatedAt && observed && Date.parse(observed) > Date.parse(updatedAt))
+ if (
+ hasNewerObservedEdit(observed, updatedAt) &&
+ currentLink.integration &&
+ readCurrent &&
+ (await readCurrent()) === value
+ ) {
+ await applyObservedTaskValue(
+ currentLink,
+ currentLink.integration,
+ field,
+ value,
+ intentId,
+ updatedAt,
+ );
return;
+ }
const task = await db.query.taskTable.findFirst({
where: linkedTaskScope(taskId, projectId),
columns: { title: true, description: true, status: true },
diff --git a/apps/api/src/plugins/github/utils/inbound-echo.ts b/apps/api/src/plugins/github/utils/inbound-echo.ts
index eed95f835..c21b78f5a 100644
--- a/apps/api/src/plugins/github/utils/inbound-echo.ts
+++ b/apps/api/src/plugins/github/utils/inbound-echo.ts
@@ -1,10 +1,12 @@
import { updateExternalLink } from "../services/link-manager";
import {
+ ambiguousOutboundEcho,
isOutboundEcho,
pendingOutboundIntent,
type SyncStamp,
} from "./sync-echo";
class ConfirmationRequired extends Error {}
+export class PendingResponseTimeout extends Error {}
export class PendingEcho extends Error {
recorded = false;
constructor(
@@ -28,7 +30,8 @@ export function inboundEcho(
const pending = pendingOutboundIntent(stamp, value);
if (pending) throw new PendingEcho(pending.intentId, updatedAt, context);
if (!isOutboundEcho(stamp, value, updatedAt)) return false;
- if (stamp?.value === value) return true;
+ if (stamp?.value === value && !ambiguousOutboundEcho(stamp, value, updatedAt))
+ return true;
if (providerValue === undefined) throw new ConfirmationRequired();
return providerValue !== value;
}
@@ -40,6 +43,8 @@ export async function withEchoConfirmation<Provider, Result>(
): Promise<Result> {
const recorded = new Set<string>();
let current: Provider | undefined;
+ let delay = 50;
+ const deadline = Date.now() + 5000;
for (;;) {
try {
const result = await apply(current);
@@ -61,7 +66,14 @@ export async function withEchoConfirmation<Provider, Result>(
});
recorded.add(key);
}
- await new Promise((resolve) => setTimeout(resolve, 50));
+ if (Date.now() >= deadline)
+ throw new PendingResponseTimeout(
+ "Outbound response is still pending; retry this webhook delivery",
+ );
+ await new Promise((resolve) =>
+ setTimeout(resolve, Math.min(delay, deadline - Date.now())),
+ );
+ delay = Math.min(delay * 2, 1000);
current = undefined;
} else if (
error instanceof ConfirmationRequired &&
diff --git a/apps/api/src/plugins/github/utils/sync-echo.ts b/apps/api/src/plugins/github/utils/sync-echo.ts
index 227596749..cbd57d416 100644
--- a/apps/api/src/plugins/github/utils/sync-echo.ts
+++ b/apps/api/src/plugins/github/utils/sync-echo.ts
@@ -6,6 +6,8 @@ export type OutboundIntent = {
cancelled?: boolean;
uncertain?: boolean;
observedUpdatedAt?: string;
+ startedAt?: string;
+ ambiguous?: boolean;
};
export type OutboundEntry = OutboundIntent & {
hash: string;
@@ -16,6 +18,8 @@ export type SyncStamp = {
timestamp?: string;
source?: string;
value?: string;
+ inboundAt?: string;
+ inboundValue?: string;
outbound?: OutboundEntry[];
};
@@ -51,12 +55,24 @@ export function outboundStamp(
timestamp,
updatedAt,
observedUpdatedAt: previousIntent?.observedUpdatedAt,
+ startedAt:
+ previousIntent?.startedAt ?? (intent.pending ? timestamp : undefined),
+ ambiguous:
+ previousIntent?.ambiguous ||
+ !!(
+ updatedAt &&
+ previousIntent?.observedUpdatedAt === updatedAt &&
+ previous?.inboundAt &&
+ previousIntent.startedAt &&
+ previous.inboundAt >= previousIntent.startedAt &&
+ previous.inboundValue !== value
+ ),
...intent,
});
const bounded = boundOutboundHistory(outbound);
if (intent.pending || intent.cancelled || intent.uncertain)
return { ...previous, outbound: bounded };
- return { timestamp, source: "kaneo", value, outbound: bounded };
+ return { ...previous, timestamp, source: "kaneo", value, outbound: bounded };
}
export function boundOutboundHistory(entries: OutboundEntry[]) {
@@ -130,3 +146,43 @@ export async function confirmedOutboundEcho(
if (stamp?.value === value) return true;
return (await readCurrent()) !== value;
}
+
+export function inboundStamp(
+ previous: SyncStamp | undefined,
+ value: string,
+ source: string,
+): SyncStamp {
+ const timestamp = new Date().toISOString();
+ return {
+ ...previous,
+ timestamp,
+ source,
+ value,
+ inboundAt: timestamp,
+ inboundValue: value,
+ };
+}
+export function ambiguousOutboundEcho(
+ stamp: SyncStamp | undefined,
+ value: string,
+ updatedAt?: string,
+) {
+ return (
+ stamp?.outbound?.some(
+ (entry) =>
+ entry.ambiguous &&
+ entry.hash === hash(value) &&
+ entry.updatedAt === updatedAt,
+ ) ?? false
+ );
+}
+export function hasNewerObservedEdit(
+ entry: OutboundEntry | undefined,
+ updatedAt: string | undefined,
+) {
+ if (!updatedAt || !entry?.observedUpdatedAt) return false;
+ return (
+ Date.parse(entry.observedUpdatedAt) > Date.parse(updatedAt) ||
+ (entry.observedUpdatedAt === updatedAt && !!entry.ambiguous)
+ );
+}
diff --git a/apps/api/src/plugins/github/webhooks/issue-closed.ts b/apps/api/src/plugins/github/webhooks/issue-closed.ts
index dca964402..771c50698 100644
--- a/apps/api/src/plugins/github/webhooks/issue-closed.ts
+++ b/apps/api/src/plugins/github/webhooks/issue-closed.ts
@@ -1,3 +1,7 @@
+import type { GitHubConfig } from "../config";
+import { getVerifiedInstallationOctokit } from "../utils/github-app";
+import { inboundEcho, withEchoConfirmation } from "../utils/inbound-echo";
+import { inboundStamp, type SyncStamp } from "../utils/sync-echo";
import { withIntegrationLink } from "../services/with-integration-link";
import { linkedTaskScope } from "../services/integration-task-scope";
import { and, eq } from "drizzle-orm";
@@ -19,6 +23,7 @@ type IssueClosedPayload = {
title: string;
html_url: string;
state: string;
+ updated_at?: string;
};
installation?: { id: number };
repository: {
@@ -47,64 +52,106 @@ export async function handleIssueClosed(payload: IssueClosedPayload) {
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) =>
+ withIntegrationLink(
+ externalLink,
+ integration,
+ async (db, afterCommit, externalLink) => {
+ const task = await db.query.taskTable.findFirst({
+ where: linkedTaskScope(externalLink.taskId, integration.projectId),
+ });
- if (!task) {
- return;
- }
+ if (!task) {
+ return;
+ }
- const existingMetadata = parseLinkMetadata(externalLink.metadata, {
- externalLinkId: externalLink.id,
- source: "issue_closed",
- });
+ const existingMetadata = parseLinkMetadata<
+ Record<string, unknown> & { lastSync?: { state?: SyncStamp } }
+ >(externalLink.metadata, {
+ externalLinkId: externalLink.id,
+ source: "issue_closed",
+ });
- if (existingMetadata.createdFrom === "kaneo") {
- return;
- }
+ if (existingMetadata.createdFrom === "kaneo") {
+ return;
+ }
- const targetStatus = await resolveTargetStatus(
- task.projectId,
- "issue_closed",
- "done",
- db,
- );
+ if (
+ inboundEcho(
+ existingMetadata.lastSync?.state,
+ "closed",
+ issue.updated_at,
+ current?.state,
+ { linkId: externalLink.id, field: "state" },
+ )
+ )
+ return;
- 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 targetStatus = await resolveTargetStatus(
+ task.projectId,
+ "issue_closed",
+ "done",
+ db,
);
- }
- await updateExternalLink(
- externalLink.id,
- {
- metadata: {
- ...existingMetadata,
- state: "closed",
+ 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",
+ lastSync: {
+ ...existingMetadata.lastSync,
+ state: inboundStamp(
+ existingMetadata.lastSync?.state,
+ "closed",
+ "github",
+ ),
+ },
+ },
},
- },
- db,
- );
- },
+ db,
+ );
+ },
+ ),
);
}
}
diff --git a/apps/api/src/plugins/github/webhooks/issue-edited.ts b/apps/api/src/plugins/github/webhooks/issue-edited.ts
index fcb261f0a..f6bd00252 100644
--- a/apps/api/src/plugins/github/webhooks/issue-edited.ts
+++ b/apps/api/src/plugins/github/webhooks/issue-edited.ts
@@ -1,3 +1,4 @@
+import { inboundStamp } from "../../github/utils/sync-echo";
import { publishEvent } from "../../../events";
import { withIntegrationLink } from "../services/with-integration-link";
import type { GitHubConfig } from "../config";
@@ -137,12 +138,11 @@ export async function handleIssueEdited(payload: IssueEditedPayload) {
if (shouldUpdateTitle) {
updateData.title = issue.title;
- updatedMetadata.lastSync.title = {
- outbound: metadata.lastSync?.title?.outbound,
- timestamp: new Date().toISOString(),
- source: "github",
- value: issue.title,
- };
+ updatedMetadata.lastSync.title = inboundStamp(
+ metadata.lastSync?.title,
+ issue.title,
+ "github",
+ );
console.log(
`Updating task title from GitHub: "${changes.title.from}" → "${issue.title}"`,
);
@@ -182,12 +182,11 @@ export async function handleIssueEdited(payload: IssueEditedPayload) {
if (shouldUpdateDescription) {
updateData.description = formattedDescription;
- updatedMetadata.lastSync.description = {
- outbound: metadata.lastSync?.description?.outbound,
- timestamp: new Date().toISOString(),
- source: "github",
- value: formattedDescription,
- };
+ updatedMetadata.lastSync.description = inboundStamp(
+ metadata.lastSync?.description,
+ formattedDescription,
+ "github",
+ );
console.log("Updating task description from GitHub");
}
}
diff --git a/apps/api/src/plugins/github/webhooks/issue-reopened.ts b/apps/api/src/plugins/github/webhooks/issue-reopened.ts
index ff22d069f..c128f1d4c 100644
--- a/apps/api/src/plugins/github/webhooks/issue-reopened.ts
+++ b/apps/api/src/plugins/github/webhooks/issue-reopened.ts
@@ -1,3 +1,7 @@
+import type { GitHubConfig } from "../config";
+import { getVerifiedInstallationOctokit } from "../utils/github-app";
+import { inboundEcho, withEchoConfirmation } from "../utils/inbound-echo";
+import { inboundStamp, type SyncStamp } from "../utils/sync-echo";
import { withIntegrationLink } from "../services/with-integration-link";
import { linkedTaskScope } from "../services/integration-task-scope";
import { and, eq } from "drizzle-orm";
@@ -19,6 +23,7 @@ type IssueReopenedPayload = {
title: string;
html_url: string;
state: string;
+ updated_at?: string;
};
installation?: { id: number };
repository: {
@@ -47,67 +52,109 @@ export async function handleIssueReopened(payload: IssueReopenedPayload) {
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) =>
+ withIntegrationLink(
+ externalLink,
+ integration,
+ async (db, afterCommit, externalLink) => {
+ const task = await db.query.taskTable.findFirst({
+ where: linkedTaskScope(externalLink.taskId, integration.projectId),
+ });
- if (!task) {
- return;
- }
+ if (!task) {
+ return;
+ }
- const existingMetadata = parseLinkMetadata(externalLink.metadata, {
- externalLinkId: externalLink.id,
- source: "issue_reopened",
- });
+ const existingMetadata = parseLinkMetadata<
+ Record<string, unknown> & { lastSync?: { state?: SyncStamp } }
+ >(externalLink.metadata, {
+ externalLinkId: externalLink.id,
+ source: "issue_reopened",
+ });
- if (
- existingMetadata.createdFrom === "kaneo" ||
- existingMetadata.state === "open"
- ) {
- return;
- }
+ if (
+ existingMetadata.createdFrom === "kaneo" ||
+ existingMetadata.state === "open"
+ ) {
+ return;
+ }
- const targetStatus = await resolveTargetStatus(
- task.projectId,
- "issue_reopened",
- "to-do",
- db,
- );
+ if (
+ inboundEcho(
+ existingMetadata.lastSync?.state,
+ "open",
+ issue.updated_at,
+ current?.state,
+ { linkId: externalLink.id, field: "state" },
+ )
+ )
+ return;
- 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 targetStatus = await resolveTargetStatus(
+ task.projectId,
+ "issue_reopened",
+ "to-do",
+ db,
);
- }
- await updateExternalLink(
- externalLink.id,
- {
- metadata: {
- ...existingMetadata,
- state: "open",
+ 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",
+ lastSync: {
+ ...existingMetadata.lastSync,
+ state: inboundStamp(
+ existingMetadata.lastSync?.state,
+ "open",
+ "github",
+ ),
+ },
+ },
},
- },
- db,
- );
- },
+ db,
+ );
+ },
+ ),
);
}
}
diff --git a/tests/api-integration/inbound-state-echo.test.ts b/tests/api-integration/inbound-state-echo.test.ts
new file mode 100644
index 000000000..b021417a7
--- /dev/null
+++ b/tests/api-integration/inbound-state-echo.test.ts
@@ -0,0 +1,137 @@
+import { eq } from "drizzle-orm";
+import { beforeEach, expect, it, vi } from "vite-plus/test";
+import db, { schema } from "../../apps/api/src/database";
+import { handleIssueClosed } from "../../apps/api/src/plugins/github/webhooks/issue-closed";
+import { handleIssueReopened } from "../../apps/api/src/plugins/github/webhooks/issue-reopened";
+import { handleGiteaIssueClosed } from "../../apps/api/src/plugins/gitea/webhooks/issue-closed";
+import { handleGiteaIssueReopened } from "../../apps/api/src/plugins/gitea/webhooks/issue-reopened";
+import { outboundStamp } from "../../apps/api/src/plugins/github/utils/sync-echo";
+import { resetTestDatabase } from "./helpers/database";
+import {
+ createWorkspaceMember,
+ createProjectFixture,
+} from "./helpers/fixtures";
+const m = vi.hoisted(() => ({ state: "open", integrations: [] as unknown[] }));
+vi.mock("../../apps/api/src/events", () => ({
+ publishEvent: vi.fn(async () => undefined),
+}));
+vi.mock(
+ "../../apps/api/src/plugins/github/services/task-service",
+ async (original) => ({
+ ...(await original<
+ typeof import("../../apps/api/src/plugins/github/services/task-service")
+ >()),
+ findAllIntegrationsByRepo: async () => m.integrations,
+ }),
+);
+vi.mock("../../apps/api/src/plugins/github/utils/github-app", () => ({
+ getVerifiedInstallationOctokit: async () => ({
+ rest: { issues: { get: async () => ({ data: { state: m.state } }) } },
+ }),
+}));
+vi.mock("../../apps/api/src/plugins/gitea/utils/gitea-api", () => ({
+ createGiteaClient: () => ({ getIssue: async () => ({ state: m.state }) }),
+}));
+beforeEach(resetTestDatabase);
+it.each(
+ ["github", "gitea"].flatMap((provider) =>
+ ["closed", "open"].map((delayed) => ({ provider, delayed })),
+ ),
+)(
+ "$provider ignores a delayed $delayed state echo and accepts a later genuine edit",
+ async ({ provider, delayed }) => {
+ const current = delayed === "closed" ? "open" : "closed";
+ const { workspace } = await createWorkspaceMember();
+ const { project } = await createProjectFixture({
+ workspaceId: workspace.id,
+ });
+ const [task] = await db
+ .insert(schema.taskTable)
+ .values({
+ projectId: project.id,
+ number: 1,
+ title: "card",
+ status: current === "closed" ? "done" : "to-do",
+ })
+ .returning();
+ const [integration] = await db
+ .insert(schema.integrationTable)
+ .values({
+ projectId: project.id,
+ type: provider,
+ config: JSON.stringify({
+ baseUrl: "https://git.example",
+ repositoryOwner: "owner",
+ repositoryName: "repo",
+ accessToken: "test-only",
+ }),
+ })
+ .returning();
+ m.integrations = [integration];
+ m.state = current;
+ const stamp = outboundStamp(
+ outboundStamp(undefined, delayed, "2026-09-30T00:00:01Z"),
+ current,
+ "2026-09-30T00:00:02Z",
+ );
+ await db.insert(schema.externalLinkTable).values({
+ taskId: task.id,
+ integrationId: integration.id,
+ resourceType: "issue",
+ externalId: "1",
+ url: "https://git.example/owner/repo/issues/1",
+ metadata: JSON.stringify({
+ createdFrom: provider,
+ state: current,
+ lastSync: { state: stamp },
+ }),
+ });
+ const payload = {
+ action: delayed === "closed" ? "closed" : "reopened",
+ issue: {
+ number: 1,
+ title: "card",
+ html_url: "https://git.example/owner/repo/issues/1",
+ state: delayed,
+ updated_at: "2026-09-30T00:00:01Z",
+ },
+ repository: {
+ id: 20,
+ name: "repo",
+ owner: { login: "owner" },
+ full_name: "owner/repo",
+ html_url: "https://git.example/owner/repo",
+ },
+ };
+ const apply = async () => {
+ if (provider === "github")
+ await (delayed === "closed" ? handleIssueClosed : handleIssueReopened)(
+ payload,
+ );
+ else
+ await (
+ delayed === "closed"
+ ? handleGiteaIssueClosed
+ : handleGiteaIssueReopened
+ )(payload, integration.id);
+ };
+ await apply();
+ expect(
+ (
+ await db.query.taskTable.findFirst({
+ where: eq(schema.taskTable.id, task.id),
+ })
+ )?.status,
+ ).toBe(current === "closed" ? "done" : "to-do");
+ m.state = delayed;
+ payload.issue.updated_at = "2026-09-30T00:00:03Z";
+ await apply();
+ expect(
+ (
+ await db.query.taskTable.findFirst({
+ where: eq(schema.taskTable.id, task.id),
+ })
+ )?.status,
+ ).toBe(delayed === "closed" ? "done" : "to-do");
+ },
+);
diff --git a/tests/api-integration/outbound-intent-correlation.test.ts b/tests/api-integration/outbound-intent-correlation.test.ts
index 6b2e8a06e..94a97b5a4 100644
--- a/tests/api-integration/outbound-intent-correlation.test.ts
+++ b/tests/api-integration/outbound-intent-correlation.test.ts
@@ -7,100 +7,138 @@ import {
inboundEcho,
withEchoConfirmation,
} from "../../apps/api/src/plugins/github/utils/inbound-echo";
-import type { SyncStamp } from "../../apps/api/src/plugins/github/utils/sync-echo";
+import { updateExternalLink } from "../../apps/api/src/plugins/github/services/link-manager";
+import {
+ inboundStamp,
+ type SyncStamp,
+} from "../../apps/api/src/plugins/github/utils/sync-echo";
import { resetTestDatabase } from "./helpers/database";
import {
createWorkspaceMember,
createProjectFixture,
} from "./helpers/fixtures";
+vi.mock("../../apps/api/src/events", () => ({
+ publishEvent: vi.fn(async () => undefined),
+}));
beforeEach(resetTestDatabase);
-it("commits the waiting provider version before an outbound completion can repair over it", async () => {
- const { workspace } = await createWorkspaceMember();
- const { project } = await createProjectFixture({ workspaceId: workspace.id });
- const [task] = await db
- .insert(schema.taskTable)
- .values({ projectId: project.id, number: 1, title: "B" })
- .returning();
- const [integration] = await db
- .insert(schema.integrationTable)
- .values({ projectId: project.id, type: "github", config: "{}" })
- .returning();
- const [link] = await db
- .insert(schema.externalLinkTable)
- .values({
- taskId: task.id,
- integrationId: integration.id,
- resourceType: "issue",
- externalId: "1",
- url: "https://provider.example/1",
- })
- .returning();
- let release!: () => void;
- const response = new Promise<void>((resolve) => {
- release = resolve;
- });
- let remote = "A";
- const outbound = syncLatestTaskValue(
- task.id,
- project.id,
- link,
- "title",
- "A",
- async (value) => {
- remote = value;
- await response;
- return "2026-09-30T00:00:01Z";
- },
- );
- await vi.waitFor(async () => {
- const current = await db.query.externalLinkTable.findFirst({
+it.each([
+ { colliding: false, legitimate: true, timeout: false },
+ { colliding: true, legitimate: true, timeout: false },
+ { colliding: true, legitimate: false, timeout: false },
+ { colliding: true, legitimate: true, timeout: true },
+])(
+ "correlates observed edits without losing intervening edits (collision=$colliding, legitimate=$legitimate, timeout=$timeout)",
+ async ({ colliding, legitimate, timeout }) => {
+ const { workspace } = await createWorkspaceMember();
+ const { project } = await createProjectFixture({
+ workspaceId: workspace.id,
+ });
+ const [task] = await db
+ .insert(schema.taskTable)
+ .values({ projectId: project.id, number: 1, title: "B" })
+ .returning();
+ const [integration] = await db
+ .insert(schema.integrationTable)
+ .values({ projectId: project.id, type: "github", config: "{}" })
+ .returning();
+ const [link] = await db
+ .insert(schema.externalLinkTable)
+ .values({
+ taskId: task.id,
+ integrationId: integration.id,
+ resourceType: "issue",
+ externalId: "1",
+ url: "https://provider.example/1",
+ })
+ .returning();
+ let release!: () => void;
+ const response = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ let remote = "A";
+ const outbound = syncLatestTaskValue(
+ task.id,
+ project.id,
+ link,
+ "title",
+ "A",
+ async (value) => {
+ remote = value;
+ await response;
+ return "2026-09-30T00:00:01Z";
+ },
+ async () => remote,
+ );
+ await vi.waitFor(async () => {
+ const current = await db.query.externalLinkTable.findFirst({
+ where: eq(schema.externalLinkTable.id, link.id),
+ });
+ expect(
+ JSON.parse(current?.metadata ?? "{}").lastSync?.title?.outbound?.[0]
+ .pending,
+ ).toBe(true);
+ });
+ const pendingLink = await db.query.externalLinkTable.findFirst({
where: eq(schema.externalLinkTable.id, link.id),
});
- expect(
- JSON.parse(current?.metadata ?? "{}").lastSync?.title?.outbound?.[0]
- .pending,
- ).toBe(true);
- });
- const inbound = withEchoConfirmation(
- async () => remote,
- (current) =>
- withIntegrationLink(
- link,
- integration,
- async (tx, _afterCommit, locked) => {
- const stamp = JSON.parse(locked.metadata ?? "{}").lastSync?.title as
- | SyncStamp
- | undefined;
- if (
- !inboundEcho(stamp, "A", "2026-09-30T00:00:03Z", current, {
- linkId: link.id,
- field: "title",
- })
- )
- await tx
- .update(schema.taskTable)
- .set({ title: "A" })
- .where(eq(schema.taskTable.id, task.id));
+ const pending = JSON.parse(pendingLink?.metadata ?? "{}");
+ await updateExternalLink(link.id, {
+ metadata: {
+ lastSync: {
+ title: inboundStamp(pending.lastSync.title, "B", "github"),
},
- ),
- );
- await vi.waitFor(async () => {
- const current = await db.query.externalLinkTable.findFirst({
- where: eq(schema.externalLinkTable.id, link.id),
+ },
});
+ remote = legitimate ? "A" : "B";
+ const observedVersion = colliding
+ ? "2026-09-30T00:00:01Z"
+ : "2026-09-30T00:00:03Z";
+ const inbound = withEchoConfirmation(
+ async () => remote,
+ (current) =>
+ withIntegrationLink(
+ link,
+ integration,
+ async (tx, _afterCommit, locked) => {
+ const stamp = JSON.parse(locked.metadata ?? "{}").lastSync
+ ?.title as SyncStamp | undefined;
+ if (
+ !inboundEcho(stamp, "A", observedVersion, current, {
+ linkId: link.id,
+ field: "title",
+ })
+ )
+ await tx
+ .update(schema.taskTable)
+ .set({ title: "A" })
+ .where(eq(schema.taskTable.id, task.id));
+ },
+ ),
+ );
+ const inboundResult = inbound.then(
+ () => null,
+ (error: unknown) => error,
+ );
+ await vi.waitFor(async () => {
+ const current = await db.query.externalLinkTable.findFirst({
+ where: eq(schema.externalLinkTable.id, link.id),
+ });
+ expect(
+ JSON.parse(current?.metadata ?? "{}").lastSync?.title?.outbound?.[0]
+ .observedUpdatedAt,
+ ).toBe(observedVersion);
+ });
+ if (timeout) expect(await inboundResult).toBeInstanceOf(Error);
+ release();
+ await Promise.all([outbound, inboundResult]);
expect(
- JSON.parse(current?.metadata ?? "{}").lastSync?.title?.outbound?.[0]
- .observedUpdatedAt,
- ).toBe("2026-09-30T00:00:03Z");
- });
- release();
- await Promise.all([outbound, inbound]);
- expect(
- (
- await db.query.taskTable.findFirst({
- where: eq(schema.taskTable.id, task.id),
- })
- )?.title,
- ).toBe("A");
- expect(remote).toBe("A");
-});
+ (
+ await db.query.taskTable.findFirst({
+ where: eq(schema.taskTable.id, task.id),
+ })
+ )?.title,
+ ).toBe(legitimate ? "A" : "B");
+ expect(remote).toBe(legitimate ? "A" : "B");
+ },
+ 15000,
+);
diff --git a/tests/api/plugins/github/issue-reopened.test.ts b/tests/api/plugins/github/issue-reopened.test.ts
index fde8fb304..443f6332f 100644
--- a/tests/api/plugins/github/issue-reopened.test.ts
+++ b/tests/api/plugins/github/issue-reopened.test.ts
@@ -71,14 +71,14 @@ it.each(["null", "[]", "42", '"text"', "invalid JSON"])(
expect(m.update).toHaveBeenCalledWith(
"first",
{
- metadata: { state: "open" },
+ metadata: expect.objectContaining({ state: "open" }),
},
expect.anything(),
);
expect(m.update).toHaveBeenCalledWith(
"second",
{
- metadata: { custom: "keep", state: "open" },
+ metadata: expect.objectContaining({ custom: "keep", state: "open" }),
},
expect.anything(),
);
diff --git a/tests/api/plugins/github/outbound-intent.test.ts b/tests/api/plugins/github/outbound-intent.test.ts
index c34947bbc..27eecb2a3 100644
--- a/tests/api/plugins/github/outbound-intent.test.ts
+++ b/tests/api/plugins/github/outbound-intent.test.ts
@@ -6,6 +6,7 @@ import {
} from "../../../../apps/api/src/plugins/github/utils/inbound-echo";
import { mergeSyncMetadata } from "../../../../apps/api/src/plugins/github/utils/merge-sync-metadata";
import {
+ inboundStamp,
isPendingOutboundEcho,
outboundStamp,
type OutboundIntent,
@@ -28,11 +29,32 @@ vi.mock(
integrationId: "integration",
resourceType: "issue",
metadata: JSON.stringify({ lastSync: m.stamps }),
+ integration: {
+ id: "integration",
+ projectId: "project",
+ type: "github",
+ },
},
],
updateExternalLink: m.save,
}),
);
+vi.mock(
+ "../../../../apps/api/src/plugins/github/services/apply-observed-task-value",
+ () => ({
+ applyObservedTaskValue: async (
+ _link: unknown,
+ _integration: unknown,
+ field: "title" | "description" | "state",
+ value: string,
+ ) => {
+ if (field === "state")
+ m.current.status = value === "closed" ? "done" : "to-do";
+ else m.current[field] = value;
+ m.stamps[field] = inboundStamp(m.stamps[field], value, "github");
+ },
+ }),
+);
const link = { id: "link", integrationId: "integration" };
beforeEach(() => {
m.stamps = {};
@@ -180,9 +202,13 @@ it("keeps an active intent while bounding completed rapid-write history", () =>
expect(isPendingOutboundEcho(stamp, "A")).toBe(true);
});
-it.each(["title", "description", "state"] as const)(
- "preserves a later provider %s edit back to an in-flight value",
- async (field) => {
+it.each(
+ (["title", "description", "state"] as const).flatMap((field) =>
+ [false, true].map((colliding) => ({ field, colliding })),
+ ),
+)(
+ "preserves a later provider $field edit back to an in-flight value (collision=$colliding)",
+ async ({ field, colliding }) => {
const a = field === "state" ? "closed" : "A";
const b = field === "state" ? "open" : "B";
m.current = { title: a, description: a, status: "done" };
@@ -190,7 +216,7 @@ it.each(["title", "description", "state"] as const)(
const release = deferred();
let remote = a;
const firstVersion = "2026-09-30T00:00:01Z";
- const laterVersion = "2026-09-30T00:00:03Z";
+ const laterVersion = colliding ? firstVersion : "2026-09-30T00:00:03Z";
const outbound = syncLatestTaskValue(
"task",
"project",
@@ -203,6 +229,7 @@ it.each(["title", "description", "state"] as const)(
await release.promise;
return firstVersion;
},
+ async () => remote,
);
await started.promise;
const apply = (value: string, version: string) =>
@@ -218,6 +245,7 @@ it.each(["title", "description", "state"] as const)(
if (field === "state")
m.current.status = value === "closed" ? "done" : "to-do";
else m.current[field] = value;
+ m.stamps[field] = inboundStamp(m.stamps[field], value, "github");
}
return Promise.resolve();
},
@@ -280,3 +308,24 @@ it.each([
);
},
);
+
+it("bounds abandoned intent polling and reports an unacknowledged delivery", async () => {
+ vi.useFakeTimers();
+ m.stamps.title = outboundStamp(undefined, "A", undefined, {
+ intentId: "abandoned",
+ pending: true,
+ });
+ let attempts = 0;
+ const run = withEchoConfirmation(
+ async () => "A",
+ async () => {
+ attempts++;
+ return inboundEcho(m.stamps.title, "A", "version");
+ },
+ );
+ const rejected = expect(run).rejects.toThrow("retry this webhook delivery");
+ await vi.advanceTimersByTimeAsync(5000);
+ await rejected;
+ expect(attempts).toBeLessThanOrEqual(11);
+ vi.useRealTimers();
+});