⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
fix(integrations): correlate pending echoes with provider versions
Tin198b17ce43d1
diff --git a/apps/api/src/plugins/gitea/webhooks/issue-closed.ts b/apps/api/src/plugins/gitea/webhooks/issue-closed.tsindex d02e395dc..33e6c4941 100644--- a/apps/api/src/plugins/gitea/webhooks/issue-closed.ts+++ b/apps/api/src/plugins/gitea/webhooks/issue-closed.ts@@ -112,6 +112,7 @@ export async function handleGiteaIssueClosed("closed",issue.updated_at,current ? (current.state ?? issue.state) : undefined,+ { linkId: externalLink.id, field: "state" },))return;diff --git a/apps/api/src/plugins/gitea/webhooks/issue-edited.ts b/apps/api/src/plugins/gitea/webhooks/issue-edited.tsindex 5b9037c23..46597714d 100644--- a/apps/api/src/plugins/gitea/webhooks/issue-edited.ts+++ b/apps/api/src/plugins/gitea/webhooks/issue-edited.ts@@ -118,6 +118,7 @@ export async function handleGiteaIssueEdited(issue.title,issue.updated_at,current?.title,+ { linkId: externalLink.id, field: "title" },)) {shouldUpdateTitle = false;@@ -156,6 +157,7 @@ export async function handleGiteaIssueEdited(task.id,): undefined,+ { linkId: externalLink.id, field: "description" },)) {shouldUpdateDescription = false;diff --git a/apps/api/src/plugins/gitea/webhooks/issue-reopened.ts b/apps/api/src/plugins/gitea/webhooks/issue-reopened.tsindex ddadc28eb..76188cff5 100644--- a/apps/api/src/plugins/gitea/webhooks/issue-reopened.ts+++ b/apps/api/src/plugins/gitea/webhooks/issue-reopened.ts@@ -115,6 +115,7 @@ export async function handleGiteaIssueReopened("open",issue.updated_at,current ? (current.state ?? issue.state) : undefined,+ { linkId: externalLink.id, field: "state" },))return;diff --git a/apps/api/src/plugins/github/services/link-manager.ts b/apps/api/src/plugins/github/services/link-manager.tsindex ba33474ba..1be24c424 100644--- a/apps/api/src/plugins/github/services/link-manager.ts+++ b/apps/api/src/plugins/github/services/link-manager.ts@@ -31,6 +31,12 @@ export type UpdateExternalLinkParams = {intentId?: string;pending?: boolean;cancelled?: boolean;+ uncertain?: boolean;+ };+ observedOutbound?: {+ field: "title" | "description" | "state";+ intentId: string;+ updatedAt: string;};title?: string | null;url?: string;@@ -127,7 +133,7 @@ export async function updateExternalLink(params: UpdateExternalLinkParams,database: DbOrTx = db,) {- if (params.outbound || params.metadata) {+ if (params.outbound || params.metadata || params.observedOutbound) {await database.transaction(async (tx) => {const link = await lockExternalLink(id, tx);if (!link) return;@@ -135,6 +141,23 @@ export async function updateExternalLink(Record<string, unknown> & { lastSync?: Record<string, SyncStamp> }>(link.metadata, { externalLinkId: id, source: "sync_update" });const merged = mergeSyncMetadata(metadata, params.metadata ?? {});+ if (params.observedOutbound) {+ const { field, intentId, updatedAt } = params.observedOutbound;+ const stamp = merged.lastSync?.[field];+ if (stamp)+ stamp.outbound = stamp.outbound?.map((entry) =>+ entry.intentId === intentId+ ? {+ ...entry,+ observedUpdatedAt:+ !entry.observedUpdatedAt ||+ updatedAt > entry.observedUpdatedAt+ ? updatedAt+ : entry.observedUpdatedAt,+ }+ : entry,+ );+ }if (params.outbound) {const { field, value, updatedAt, ...intent } = params.outbound;merged.lastSync = {diff --git a/apps/api/src/plugins/github/services/sync-latest-task-value.ts b/apps/api/src/plugins/github/services/sync-latest-task-value.tsindex 54b85e971..576815e7b 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,5 +1,7 @@import { randomUUID } from "node:crypto";import db from "../../../database";+import { parseLinkMetadata } from "../utils/parse-link-metadata";+import type { SyncStamp } from "../utils/sync-echo";import { linkedTaskScope } from "./integration-task-scope";import { findExternalLinksByTask, updateExternalLink } from "./link-manager";@@ -24,8 +26,21 @@ export async function syncLatestTaskValue(try {updatedAt = await write(value);} catch (error) {+ const status =+ typeof error === "object" && error && "status" in error+ ? Number(error.status)+ : undefined;+ const rejected =+ status !== undefined && status >= 400 && status < 500 && status !== 408;await updateExternalLink(link.id, {- outbound: { field, value, intentId, pending: false, cancelled: true },+ outbound: {+ field,+ value,+ intentId,+ pending: false,+ cancelled: rejected,+ uncertain: !rejected,+ },}).catch(() => {});throw error;}@@ -36,6 +51,27 @@ export async function syncLatestTaskValue(? { metadata: { state: value, lastOutboundStateSyncAt: Date.now() } }: {}),});+ const currentLinks = await findExternalLinksByTask(taskId);+ const currentLink = currentLinks.find(+ (candidate) =>+ candidate.id === link.id &&+ candidate.integrationId === link.integrationId &&+ candidate.resourceType === "issue",+ );+ if (!currentLink) return;+ const metadata = parseLinkMetadata<{+ lastSync?: Record<string, SyncStamp>;+ }>(currentLink.metadata, {+ externalLinkId: link.id,+ source: "outbound_completion",+ });+ 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))+ return;const task = await db.query.taskTable.findFirst({where: linkedTaskScope(taskId, projectId),columns: { title: true, description: true, status: true },@@ -50,7 +86,7 @@ export async function syncLatestTaskValue(? task.title: task.description || "";if (current === value) return;- const stillLinked = (await findExternalLinksByTask(taskId)).some(+ const stillLinked = currentLinks.some((currentLink) =>currentLink.id === link.id &¤tLink.integrationId === link.integrationId &&diff --git a/apps/api/src/plugins/github/services/with-integration-link.ts b/apps/api/src/plugins/github/services/with-integration-link.tsindex bc65a3513..cb52494c1 100644--- a/apps/api/src/plugins/github/services/with-integration-link.ts+++ b/apps/api/src/plugins/github/services/with-integration-link.ts@@ -1,4 +1,6 @@import { and, eq } from "drizzle-orm";+import { PendingEcho } from "../utils/inbound-echo";+import { updateExternalLink } from "./link-manager";import { externalLinkTable } from "../../../database/schema";import {withIntegrationTask,@@ -30,7 +32,26 @@ export function withIntegrationLink<T>().for("update");if (!lockedLink) return;- return apply(database, afterCommit, lockedLink);+ try {+ return await apply(database, afterCommit, lockedLink);+ } catch (error) {+ if (!(error instanceof PendingEcho)) throw error;+ if (error.context && error.intentId && error.updatedAt) {+ await updateExternalLink(+ lockedLink.id,+ {+ observedOutbound: {+ field: error.context.field,+ intentId: error.intentId,+ updatedAt: error.updatedAt,+ },+ },+ database,+ );+ error.recorded = true;+ }+ return error;+ }},);}diff --git a/apps/api/src/plugins/github/utils/inbound-echo.ts b/apps/api/src/plugins/github/utils/inbound-echo.tsindex 1c4a8f1aa..eed95f835 100644--- a/apps/api/src/plugins/github/utils/inbound-echo.ts+++ b/apps/api/src/plugins/github/utils/inbound-echo.ts@@ -1,32 +1,76 @@+import { updateExternalLink } from "../services/link-manager";import {isOutboundEcho,- isPendingOutboundEcho,+ pendingOutboundIntent,type SyncStamp,} from "./sync-echo";class ConfirmationRequired extends Error {}-+export class PendingEcho extends Error {+ recorded = false;+ constructor(+ public intentId: string | undefined,+ public updatedAt: string | undefined,+ public context?: {+ linkId: string;+ field: "title" | "description" | "state";+ },+ ) {+ super("Outbound response is pending");+ }+}export function inboundEcho(stamp: SyncStamp | undefined,value: string,updatedAt?: string,providerValue?: string,+ context?: { linkId: string; field: "title" | "description" | "state" },) {- if (isPendingOutboundEcho(stamp, value)) return true;+ 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 (providerValue === undefined) throw new ConfirmationRequired();return providerValue !== value;}--// Release the guarded transaction before an ambiguous echo needs provider I/O.+// Every retry releases the transaction first. Persist observed provider versions+// so an outbound completion cannot repair over a newer edit waiting for it.export async function withEchoConfirmation<Provider, Result>(read: () => Promise<Provider>,apply: (current?: Provider) => Promise<Result>,): Promise<Result> {- try {- return await apply();- } catch (error) {- if (!(error instanceof ConfirmationRequired)) throw error;- return apply(await read());+ const recorded = new Set<string>();+ let current: Provider | undefined;+ for (;;) {+ try {+ const result = await apply(current);+ if (result instanceof PendingEcho) throw result;+ return result;+ } catch (error) {+ if (error instanceof PendingEcho) {+ const { context, intentId, updatedAt } = error;+ const key = `${intentId}:${updatedAt}`;+ if (+ !error.recorded &&+ context &&+ intentId &&+ updatedAt &&+ !recorded.has(key)+ ) {+ await updateExternalLink(context.linkId, {+ observedOutbound: { field: context.field, intentId, updatedAt },+ });+ recorded.add(key);+ }+ await new Promise((resolve) => setTimeout(resolve, 50));+ current = undefined;+ } else if (+ error instanceof ConfirmationRequired &&+ current === undefined+ ) {+ current = await read();+ } else {+ throw error;+ }+ }}}diff --git a/apps/api/src/plugins/github/utils/sync-echo.ts b/apps/api/src/plugins/github/utils/sync-echo.tsindex 5f54b0a3e..227596749 100644--- a/apps/api/src/plugins/github/utils/sync-echo.ts+++ b/apps/api/src/plugins/github/utils/sync-echo.ts@@ -4,6 +4,8 @@ export type OutboundIntent = {intentId?: string;pending?: boolean;cancelled?: boolean;+ uncertain?: boolean;+ observedUpdatedAt?: string;};export type OutboundEntry = OutboundIntent & {hash: string;@@ -41,9 +43,18 @@ export function outboundStamp(hash: hash(previous.value),timestamp: previous.timestamp,});- outbound.push({ hash: hash(value), timestamp, updatedAt, ...intent });+ const previousIntent = previous?.outbound?.find(+ (entry) => intent.intentId && entry.intentId === intent.intentId,+ );+ outbound.push({+ hash: hash(value),+ timestamp,+ updatedAt,+ observedUpdatedAt: previousIntent?.observedUpdatedAt,+ ...intent,+ });const bounded = boundOutboundHistory(outbound);- if (intent.pending || intent.cancelled)+ if (intent.pending || intent.cancelled || intent.uncertain)return { ...previous, outbound: bounded };return { timestamp, source: "kaneo", value, outbound: bounded };}@@ -62,11 +73,11 @@ export function boundOutboundHistory(entries: OutboundEntry[]) {);}-export function isPendingOutboundEcho(+export function pendingOutboundIntent(stamp: SyncStamp | undefined,value: string,) {- return (stamp?.outbound ?? []).some(+ return (stamp?.outbound ?? []).find((entry) =>entry.pending &&!entry.cancelled &&@@ -75,6 +86,13 @@ export function isPendingOutboundEcho();}+export function isPendingOutboundEcho(+ stamp: SyncStamp | undefined,+ value: string,+) {+ return !!pendingOutboundIntent(stamp, value);+}+export function isOutboundEcho(stamp: SyncStamp | undefined,value: string,diff --git a/apps/api/src/plugins/github/webhooks/issue-edited.ts b/apps/api/src/plugins/github/webhooks/issue-edited.tsindex 0a1de9869..fcb261f0a 100644--- a/apps/api/src/plugins/github/webhooks/issue-edited.ts+++ b/apps/api/src/plugins/github/webhooks/issue-edited.ts@@ -125,6 +125,7 @@ export async function handleIssueEdited(payload: IssueEditedPayload) {issue.title,issue.updated_at,current?.title,+ { linkId: externalLink.id, field: "title" },)) {console.log(@@ -169,6 +170,7 @@ export async function handleIssueEdited(payload: IssueEditedPayload) {task.id,): undefined,+ { linkId: externalLink.id, field: "description" },)) {console.log(diff --git a/tests/api-integration/outbound-intent-correlation.test.ts b/tests/api-integration/outbound-intent-correlation.test.tsnew file mode 100644index 000000000..6b2e8a06e--- /dev/null+++ b/tests/api-integration/outbound-intent-correlation.test.ts@@ -0,0 +1,106 @@+import { eq } from "drizzle-orm";+import { beforeEach, expect, it, vi } from "vite-plus/test";+import db, { schema } from "../../apps/api/src/database";+import { syncLatestTaskValue } from "../../apps/api/src/plugins/github/services/sync-latest-task-value";+import { withIntegrationLink } from "../../apps/api/src/plugins/github/services/with-integration-link";+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 { resetTestDatabase } from "./helpers/database";+import {+ createWorkspaceMember,+ createProjectFixture,+} from "./helpers/fixtures";+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({+ 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));+ },+ ),+ );+ 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("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");+});diff --git a/tests/api/plugins/github/outbound-intent.test.ts b/tests/api/plugins/github/outbound-intent.test.tsindex 73c754818..c34947bbc 100644--- a/tests/api/plugins/github/outbound-intent.test.ts+++ b/tests/api/plugins/github/outbound-intent.test.ts@@ -1,6 +1,9 @@import { beforeEach, expect, it, vi } from "vite-plus/test";import { syncLatestTaskValue } from "../../../../apps/api/src/plugins/github/services/sync-latest-task-value";-import { inboundEcho } from "../../../../apps/api/src/plugins/github/utils/inbound-echo";+import {+ inboundEcho,+ withEchoConfirmation,+} from "../../../../apps/api/src/plugins/github/utils/inbound-echo";import { mergeSyncMetadata } from "../../../../apps/api/src/plugins/github/utils/merge-sync-metadata";import {isPendingOutboundEcho,@@ -20,7 +23,12 @@ vi.mock("../../../../apps/api/src/plugins/github/services/link-manager",() => ({findExternalLinksByTask: async () => [- { id: "link", integrationId: "integration", resourceType: "issue" },+ {+ id: "link",+ integrationId: "integration",+ resourceType: "issue",+ metadata: JSON.stringify({ lastSync: m.stamps }),+ },],updateExternalLink: m.save,}),@@ -33,14 +41,32 @@ beforeEach(() => {_id: string,{outbound,+ observedOutbound,}: {- outbound: OutboundIntent & {+ observedOutbound?: {+ field: string;+ intentId: string;+ updatedAt: string;+ };+ outbound?: OutboundIntent & {field: string;value: string;updatedAt?: string;};},) => {+ if (observedOutbound) {+ const entry = m.stamps[observedOutbound.field]?.outbound?.find(+ (entry) => entry.intentId === observedOutbound.intentId,+ );+ if (+ entry &&+ (!entry.observedUpdatedAt ||+ observedOutbound.updatedAt > entry.observedUpdatedAt)+ )+ entry.observedUpdatedAt = observedOutbound.updatedAt;+ }+ if (!outbound) return;m.stamps[outbound.field] = outboundStamp(m.stamps[outbound.field],outbound.value,@@ -67,6 +93,7 @@ it.each(["title", "description", "state"] as const)(const release = deferred();let first = true;let remote = a;+ const webhooks: Promise<unknown>[] = [];const write = async (value: string) => {if (first) {first = false;@@ -74,13 +101,25 @@ it.each(["title", "description", "state"] as const)(await release.promise;}remote = value;- // Exercise the same predicate used by the guarded inbound handlers while- // the provider has applied the write and has not returned its response.- if (!inboundEcho(m.stamps[field], value, `${value}-stamp`, remote)) {- if (field === "state")- m.current.status = value === "closed" ? "done" : "to-do";- else m.current[field] = value;- }+ // The provider does not wait for webhook processing before responding.+ webhooks.push(+ withEchoConfirmation(+ async () => remote,+ (current) => {+ if (+ !inboundEcho(m.stamps[field], value, `${value}-stamp`, current, {+ linkId: "link",+ field,+ })+ ) {+ if (field === "state")+ m.current.status = value === "closed" ? "done" : "to-do";+ else m.current[field] = value;+ }+ return Promise.resolve();+ },+ ),+ );return `${value}-stamp`;};const older = syncLatestTaskValue("task", "project", link, field, a, write);@@ -89,6 +128,7 @@ it.each(["title", "description", "state"] as const)(await syncLatestTaskValue("task", "project", link, field, b, write);release.resolve();await older;+ await Promise.all(webhooks);expect(remote).toBe(b);expect(field === "state" ? m.current.status : m.current[field]).toBe(field === "state" ? "to-do" : b,@@ -104,7 +144,7 @@ it.each(["title", "description", "state"] as const)(it("clears failed intents so a later legitimate provider edit is accepted", async () => {await expect(syncLatestTaskValue("task", "project", link, "title", "A", async () => {- throw new Error("provider failed");+ throw Object.assign(new Error("provider failed"), { status: 422 });}),).rejects.toThrow("provider failed");expect(isPendingOutboundEcho(m.stamps.title, "A")).toBe(false);@@ -139,3 +179,104 @@ it("keeps an active intent while bounding completed rapid-write history", () =>expect(stamp.outbound?.filter((entry) => !entry.pending)).toHaveLength(32);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) => {+ const a = field === "state" ? "closed" : "A";+ const b = field === "state" ? "open" : "B";+ m.current = { title: a, description: a, status: "done" };+ const started = deferred();+ const release = deferred();+ let remote = a;+ const firstVersion = "2026-09-30T00:00:01Z";+ const laterVersion = "2026-09-30T00:00:03Z";+ const outbound = syncLatestTaskValue(+ "task",+ "project",+ link,+ field,+ a,+ async (value) => {+ remote = value;+ started.resolve();+ await release.promise;+ return firstVersion;+ },+ );+ await started.promise;+ const apply = (value: string, version: string) =>+ withEchoConfirmation(+ async () => remote,+ (current) => {+ if (+ !inboundEcho(m.stamps[field], value, version, current, {+ linkId: "link",+ field,+ })+ ) {+ if (field === "state")+ m.current.status = value === "closed" ? "done" : "to-do";+ else m.current[field] = value;+ }+ return Promise.resolve();+ },+ );+ const original = apply(a, firstVersion);+ remote = b;+ await apply(b, "2026-09-30T00:00:02Z");+ remote = a;+ const legitimate = apply(a, laterVersion);+ await vi.waitFor(() =>+ expect(m.stamps[field].outbound?.[0].observedUpdatedAt).toBe(+ laterVersion,+ ),+ );+ release.resolve();+ await Promise.all([outbound, original, legitimate]);+ expect(remote).toBe(a);+ expect(field === "state" ? m.current.status : m.current[field]).toBe(+ field === "state" ? "done" : a,+ );+ },+);+it.each([+ new Error("lost response"),+ Object.assign(new Error("timeout"), { status: 408 }),+ Object.assign(new Error("gateway failure"), { status: 502 }),+])(+ "recognizes a potentially applied failed write after a newer local edit (%s)",+ async (error) => {+ m.current = { title: "A", description: "", status: "to-do" };+ let remote = "A";+ await expect(+ syncLatestTaskValue("task", "project", link, "title", "A", async () => {+ throw error;+ }),+ ).rejects.toThrow(error.message);+ m.current.title = "B";+ await syncLatestTaskValue(+ "task",+ "project",+ link,+ "title",+ "B",+ async (value) => {+ remote = value;+ return "2026-09-30T00:00:02Z";+ },+ );+ const echo = await withEchoConfirmation(+ async () => remote,+ (current) =>+ Promise.resolve(+ inboundEcho(m.stamps.title, "A", "2026-09-30T00:00:01Z", current),+ ),+ );+ expect(echo).toBe(true);+ expect(m.current.title).toBe("B");+ expect(inboundEcho(m.stamps.title, "A", "2026-09-30T00:00:03Z", "A")).toBe(+ false,+ );+ },+);