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 webhook versions and final workflow states

Tin0f47144c712e
diff --git a/apps/api/src/plugins/gitea/webhooks/issue-closed.ts b/apps/api/src/plugins/gitea/webhooks/issue-closed.ts
index 442326ee1..a661dc75a 100644
--- a/apps/api/src/plugins/gitea/webhooks/issue-closed.ts
+++ b/apps/api/src/plugins/gitea/webhooks/issue-closed.ts
@@ -16,7 +16,10 @@ import db from "../../../database";
import { externalLinkTable } from "../../../database/schema";
import { publishEvent } from "../../../events";
import { updateExternalLink } from "../../github/services/link-manager";
-import { updateTaskStatus } from "../../github/services/task-service";
+import {
+ isTaskInFinalState,
+ updateTaskStatus,
+} from "../../github/services/task-service";
import {
findAllIntegrationsByGiteaRepo,
repoOwnerLogin,
@@ -119,7 +122,9 @@ export async function handleGiteaIssueClosed(
{
linkId: externalLink.id,
field: "state",
- localValue: task.status === "done" ? "closed" : "open",
+ localValue: (await isTaskInFinalState(task, db))
+ ? "closed"
+ : "open",
confirmation,
},
)
diff --git a/apps/api/src/plugins/gitea/webhooks/issue-edited.ts b/apps/api/src/plugins/gitea/webhooks/issue-edited.ts
index 52d6b1f11..730e22500 100644
--- a/apps/api/src/plugins/gitea/webhooks/issue-edited.ts
+++ b/apps/api/src/plugins/gitea/webhooks/issue-edited.ts
@@ -140,7 +140,7 @@ export async function handleGiteaIssueEdited(
metadata.lastSync?.title,
issue.title,
"gitea",
- current?.updated_at ?? issue.updated_at,
+ issue.updated_at,
);
}
}
@@ -184,7 +184,7 @@ export async function handleGiteaIssueEdited(
metadata.lastSync?.description,
formattedDescription,
"gitea",
- current?.updated_at ?? issue.updated_at,
+ issue.updated_at,
);
}
}
diff --git a/apps/api/src/plugins/gitea/webhooks/issue-reopened.ts b/apps/api/src/plugins/gitea/webhooks/issue-reopened.ts
index d1f002485..04f79c07b 100644
--- a/apps/api/src/plugins/gitea/webhooks/issue-reopened.ts
+++ b/apps/api/src/plugins/gitea/webhooks/issue-reopened.ts
@@ -17,7 +17,10 @@ import db from "../../../database";
import { externalLinkTable } from "../../../database/schema";
import { publishEvent } from "../../../events";
import { updateExternalLink } from "../../github/services/link-manager";
-import { updateTaskStatus } from "../../github/services/task-service";
+import {
+ isTaskInFinalState,
+ updateTaskStatus,
+} from "../../github/services/task-service";
import {
findAllIntegrationsByGiteaRepo,
repoOwnerLogin,
@@ -120,7 +123,9 @@ export async function handleGiteaIssueReopened(
{
linkId: externalLink.id,
field: "state",
- localValue: task.status === "done" ? "closed" : "open",
+ localValue: (await isTaskInFinalState(task, db))
+ ? "closed"
+ : "open",
confirmation,
},
)
diff --git a/apps/api/src/plugins/github/services/deferred-issue-edits.ts b/apps/api/src/plugins/github/services/deferred-issue-edits.ts
index 82a2268ef..034017c16 100644
--- a/apps/api/src/plugins/github/services/deferred-issue-edits.ts
+++ b/apps/api/src/plugins/github/services/deferred-issue-edits.ts
@@ -27,6 +27,7 @@ import {
import { writeInboundTaskField } from "./apply-observed-task-value";
import { updateExternalLink } from "./link-manager";
import { syncLatestTaskValue } from "./sync-latest-task-value";
+import { isTaskInFinalState } from "./task-service";
import {
linkedTaskScope,
integrationTaskRevision,
@@ -236,9 +237,18 @@ async function replayClaimedIssueEdits() {
return;
const task = await tx.query.taskTable.findFirst({
where: linkedTaskScope(link.taskId, integration.projectId),
- columns: { title: true, description: true, status: true },
+ columns: {
+ title: true,
+ description: true,
+ status: true,
+ columnId: true,
+ projectId: true,
+ },
});
if (!task) return;
+ const taskIsClosed = fields.includes("state")
+ ? await isTaskInFinalState(task, tx)
+ : false;
for (const field of fields) {
const stamp = current.lastSync?.[field];
const uncertain = uncertainOutboundIntents(stamp, values[field]);
@@ -247,7 +257,7 @@ async function replayClaimedIssueEdits() {
);
const local =
field === "state"
- ? task.status === "done"
+ ? taskIsClosed
? "closed"
: "open"
: field === "description"
@@ -303,7 +313,7 @@ async function replayClaimedIssueEdits() {
field,
localValue:
field === "state"
- ? task.status === "done"
+ ? taskIsClosed
? "closed"
: "open"
: field === "description"
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 a156927e2..1ce89a6f7 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
@@ -13,6 +13,7 @@ import {
integrationTaskRevision,
} from "./integration-task-scope";
import { findExternalLinksByTask, updateExternalLink } from "./link-manager";
+import { isTaskInFinalState } from "./task-service";
// Provider requests may complete out of order across API instances. Every late
// completion repairs the provider using the current, still-linked task value.
@@ -158,12 +159,18 @@ export async function syncLatestTaskValue(
}
const task = await db.query.taskTable.findFirst({
where: linkedTaskScope(taskId, projectId),
- columns: { title: true, description: true, status: true },
+ columns: {
+ title: true,
+ description: true,
+ status: true,
+ columnId: true,
+ projectId: true,
+ },
});
if (!task) return;
const current =
field === "state"
- ? task.status === "done"
+ ? (await isTaskInFinalState(task))
? "closed"
: "open"
: field === "title"
diff --git a/apps/api/src/plugins/github/webhooks/issue-closed.ts b/apps/api/src/plugins/github/webhooks/issue-closed.ts
index a3875b39d..22fcee820 100644
--- a/apps/api/src/plugins/github/webhooks/issue-closed.ts
+++ b/apps/api/src/plugins/github/webhooks/issue-closed.ts
@@ -13,6 +13,7 @@ import { publishEvent } from "../../../events";
import { updateExternalLink } from "../services/link-manager";
import {
findAllIntegrationsByRepo,
+ isTaskInFinalState,
updateTaskStatus,
} from "../services/task-service";
import { parseLinkMetadata } from "../utils/parse-link-metadata";
@@ -103,7 +104,9 @@ export async function handleIssueClosed(payload: IssueClosedPayload) {
{
linkId: externalLink.id,
field: "state",
- localValue: task.status === "done" ? "closed" : "open",
+ localValue: (await isTaskInFinalState(task, db))
+ ? "closed"
+ : "open",
confirmation,
},
)
diff --git a/apps/api/src/plugins/github/webhooks/issue-edited.ts b/apps/api/src/plugins/github/webhooks/issue-edited.ts
index 45e12912c..610b69050 100644
--- a/apps/api/src/plugins/github/webhooks/issue-edited.ts
+++ b/apps/api/src/plugins/github/webhooks/issue-edited.ts
@@ -150,7 +150,7 @@ export async function handleIssueEdited(payload: IssueEditedPayload) {
metadata.lastSync?.title,
issue.title,
"github",
- current?.updated_at ?? issue.updated_at,
+ issue.updated_at,
);
console.log(
`Updating task title from GitHub: "${changes.title.from}" → "${issue.title}"`,
@@ -200,7 +200,7 @@ export async function handleIssueEdited(payload: IssueEditedPayload) {
metadata.lastSync?.description,
formattedDescription,
"github",
- current?.updated_at ?? issue.updated_at,
+ issue.updated_at,
);
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 b7518e337..fe4aa2beb 100644
--- a/apps/api/src/plugins/github/webhooks/issue-reopened.ts
+++ b/apps/api/src/plugins/github/webhooks/issue-reopened.ts
@@ -13,6 +13,7 @@ import { publishEvent } from "../../../events";
import { updateExternalLink } from "../services/link-manager";
import {
findAllIntegrationsByRepo,
+ isTaskInFinalState,
updateTaskStatus,
} from "../services/task-service";
import { parseLinkMetadata } from "../utils/parse-link-metadata";
@@ -106,7 +107,9 @@ export async function handleIssueReopened(payload: IssueReopenedPayload) {
{
linkId: externalLink.id,
field: "state",
- localValue: task.status === "done" ? "closed" : "open",
+ localValue: (await isTaskInFinalState(task, db))
+ ? "closed"
+ : "open",
confirmation,
},
)
diff --git a/tests/api-integration/deferred-issue-edits.test.ts b/tests/api-integration/deferred-issue-edits.test.ts
index 57b506c27..1716965b5 100644
--- a/tests/api-integration/deferred-issue-edits.test.ts
+++ b/tests/api-integration/deferred-issue-edits.test.ts
@@ -1930,3 +1930,186 @@ it.each(
expect(m.write).not.toHaveBeenCalled();
},
);
+
+it.each(
+ (["github", "gitea"] as const).flatMap((provider) =>
+ (["title", "description"] as const).map((field) => ({ provider, field })),
+ ),
+)(
+ "keeps the $provider $field webhook version when only the other field is confirmed",
+ async ({ provider, field }) => {
+ const { task, integration, link } = await seed(provider);
+ const confirmedField = field === "title" ? "description" : "title";
+ const before = { title: "title-0", description: "body-0" };
+ const first = { title: "title-1", description: "body-1" };
+ const latest = { title: "title-2", description: "body-2" };
+ const t0 = "2026-09-30T00:00:00Z";
+ const t1 = "2026-09-30T00:00:01Z";
+ const t2 = "2026-09-30T00:00:02Z";
+ const t3 = "2026-09-30T00:00:03Z";
+ await db
+ .update(schema.taskTable)
+ .set(before)
+ .where(eq(schema.taskTable.id, task.id));
+ await db
+ .update(schema.externalLinkTable)
+ .set({
+ metadata: JSON.stringify({
+ lastSync: {
+ [confirmedField]: inboundStamp(
+ undefined,
+ before[confirmedField],
+ provider,
+ t1,
+ ),
+ [field]: inboundStamp(undefined, before[field], provider, t0),
+ },
+ }),
+ })
+ .where(eq(schema.externalLinkTable.id, link.id));
+ // Confirmation reads the whole issue, including a newer edit to the other
+ // field. Its timestamp must not be assigned to that field's older payload.
+ m.read.mockResolvedValue({
+ title: field === "title" ? latest.title : first.title,
+ body: field === "description" ? latest.description : first.description,
+ state: "open",
+ updated_at: t3,
+ });
+ const payload = {
+ action: "edited",
+ issue: {
+ number: 1,
+ title: first.title,
+ body: first.description,
+ updated_at: t1,
+ html_url: link.url,
+ },
+ changes: {
+ title: { from: before.title },
+ body: { from: before.description },
+ },
+ repository: {
+ id: 20,
+ name: "repo",
+ full_name: "owner/repo",
+ owner: { login: "owner" },
+ html_url: "https://git.example/owner/repo",
+ },
+ };
+ if (provider === "github") await handleIssueEdited(payload);
+ else await handleGiteaIssueEdited(payload, integration.id);
+ expect(m.read).toHaveBeenCalled();
+ expect((await current(task.id))?.[field]).toBe(first[field]);
+ expect((await metadata(link.id)).lastSync[field].inboundUpdatedAt).toBe(t1);
+ await deliverField(provider, field, latest[field], t2, integration.id);
+ expect((await current(task.id))?.[field]).toBe(latest[field]);
+ },
+);
+
+it.each(["github", "gitea"])(
+ "keeps %s issues closed when orphaned replay finds a custom final workflow task",
+ async (provider) => {
+ const { task, integration, link } = await seed(provider);
+ const [finalColumn] = await db
+ .insert(schema.columnTable)
+ .values({
+ projectId: task.projectId,
+ name: "Released",
+ slug: "released",
+ position: 10,
+ isFinal: true,
+ })
+ .returning();
+ await db.insert(schema.workflowRuleTable).values({
+ projectId: task.projectId,
+ integrationType: provider,
+ eventType: "issue_closed",
+ columnId: finalColumn.id,
+ });
+ await db
+ .update(schema.taskTable)
+ .set({ status: "released", columnId: finalColumn.id })
+ .where(eq(schema.taskTable.id, task.id));
+ // A genuine remote close has already been applied through the workflow.
+ // An older writer was orphaned; its stale delivery still needs replay.
+ const stamp = inboundStamp(
+ outboundStamp(undefined, "closed", undefined, {
+ intentId: "old-close",
+ pending: true,
+ }),
+ "closed",
+ provider,
+ "2026-09-30T00:00:03Z",
+ );
+ const orphan = stamp.outbound?.find(
+ (entry) => entry.intentId === "old-close",
+ );
+ if (!orphan) throw new Error("Missing orphaned close intent");
+ orphan.timestamp = new Date(Date.now() - 300_001).toISOString();
+ orphan.startedAt = orphan.timestamp;
+ await db
+ .update(schema.externalLinkTable)
+ .set({ metadata: JSON.stringify({ lastSync: { state: stamp } }) })
+ .where(eq(schema.externalLinkTable.id, link.id));
+ m.read.mockResolvedValue({
+ title: "B",
+ body: "old body",
+ state: "closed",
+ updated_at: "2026-09-30T00:00:03Z",
+ });
+ await deferIssueEdit(link, integration, ["state"]);
+ await replayDeferredIssueEdits();
+ expect((await current(task.id))?.status).toBe("released");
+ expect(m.write).not.toHaveBeenCalledWith(
+ expect.objectContaining({ state: "open" }),
+ );
+ },
+);
+
+it.each(
+ (["github", "gitea"] as const).flatMap((provider) =>
+ [true, false].map((isFinal) => ({ provider, isFinal })),
+ ),
+)(
+ "repairs a late $provider close using the custom column's final flag ($isFinal)",
+ async ({ provider, isFinal }) => {
+ const { task, integration, link } = await seed(provider);
+ const [column] = await db
+ .insert(schema.columnTable)
+ .values({
+ projectId: task.projectId,
+ name: "Custom",
+ slug: "custom",
+ position: 10,
+ isFinal,
+ })
+ .returning();
+ await db
+ .update(schema.externalLinkTable)
+ .set({ metadata: "{}" })
+ .where(eq(schema.externalLinkTable.id, link.id));
+ const write = vi.fn(async (_state: string) => {
+ if (write.mock.calls.length === 1) {
+ await db
+ .update(schema.taskTable)
+ .set({ status: column.slug, columnId: column.id })
+ .where(eq(schema.taskTable.id, task.id));
+ }
+ return "2026-09-30T00:00:04Z";
+ });
+ await syncLatestTaskValue(
+ task.id,
+ task.projectId,
+ link,
+ "state",
+ "closed",
+ write,
+ undefined,
+ integration,
+ );
+ expect(write.mock.calls.map(([state]) => state)).toEqual(
+ isFinal ? ["closed"] : ["closed", "open"],
+ );
+ expect((await metadata(link.id)).state).toBe(isFinal ? "closed" : "open");
+ },
+);
diff --git a/tests/api/plugins/gitea/rapid-text-sync.test.ts b/tests/api/plugins/gitea/rapid-text-sync.test.ts
index d4c5ba0b3..159f56bcd 100644
--- a/tests/api/plugins/gitea/rapid-text-sync.test.ts
+++ b/tests/api/plugins/gitea/rapid-text-sync.test.ts
@@ -12,6 +12,7 @@ const m = vi.hoisted(() => ({
vi.mock("../../../../apps/api/src/database", () => ({
default: {
query: {
+ columnTable: { findFirst: async () => undefined },
externalLinkTable: {
findFirst: async () => ({
id: "link",
@@ -205,7 +206,12 @@ it("allows a new remote edit back to an older outbound value", async () => {
vi.mock(
"../../../../apps/api/src/plugins/github/services/task-service",
- () => ({ updateTaskStatus: m.status }),
+ async (original) => ({
+ ...(await original<
+ typeof import("../../../../apps/api/src/plugins/github/services/task-service")
+ >()),
+ updateTaskStatus: m.status,
+ }),
);
vi.mock("../../../../apps/api/src/plugins/gitea/utils/resolve-column", () => ({
resolveTargetStatus: async (
diff --git a/tests/api/plugins/github/issue-reopened.test.ts b/tests/api/plugins/github/issue-reopened.test.ts
index 443f6332f..ec2aa8901 100644
--- a/tests/api/plugins/github/issue-reopened.test.ts
+++ b/tests/api/plugins/github/issue-reopened.test.ts
@@ -14,13 +14,17 @@ vi.mock("../../../../apps/api/src/database", () => ({
query: {
externalLinkTable: { findFirst: m.links },
taskTable: { findFirst: m.tasks },
+ columnTable: { findFirst: async () => undefined },
},
},
}));
vi.mock("../../../../apps/api/src/events", () => ({ publishEvent: m.publish }));
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: m.find,
updateTaskStatus: m.status,
}),
diff --git a/tests/api/plugins/github/outbound-intent.test.ts b/tests/api/plugins/github/outbound-intent.test.ts
index d9ef0b981..ae8b0e263 100644
--- a/tests/api/plugins/github/outbound-intent.test.ts
+++ b/tests/api/plugins/github/outbound-intent.test.ts
@@ -19,7 +19,12 @@ const m = vi.hoisted(() => ({
save: vi.fn(),
}));
vi.mock("../../../../apps/api/src/database", () => ({
- default: { query: { taskTable: { findFirst: async () => m.current } } },
+ default: {
+ query: {
+ taskTable: { findFirst: async () => m.current },
+ columnTable: { findFirst: async () => undefined },
+ },
+ },
}));
vi.mock(
"../../../../apps/api/src/plugins/github/services/link-manager",
diff --git a/tests/api/plugins/github/rapid-state-sync.test.ts b/tests/api/plugins/github/rapid-state-sync.test.ts
index 4936bb620..5beb0f54b 100644
--- a/tests/api/plugins/github/rapid-state-sync.test.ts
+++ b/tests/api/plugins/github/rapid-state-sync.test.ts
@@ -4,7 +4,10 @@ import { handleTaskStatusChanged as gitea } from "../../../../apps/api/src/plugi
const m = vi.hoisted(() => ({ status: "", write: vi.fn(), save: vi.fn() }));
vi.mock("../../../../apps/api/src/database", () => ({
default: {
- query: { taskTable: { findFirst: async () => ({ status: m.status }) } },
+ query: {
+ taskTable: { findFirst: async () => ({ status: m.status }) },
+ columnTable: { findFirst: async () => undefined },
+ },
},
}));
vi.mock(