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(gitea): align fetch timeout, label api bodies, and webhook events

Cursor Agentc2ff123358c4
diff --git a/apps/api/src/plugins/gitea/utils/gitea-api.ts b/apps/api/src/plugins/gitea/utils/gitea-api.ts
index 5fd443ed9..a38f72280 100644
--- a/apps/api/src/plugins/gitea/utils/gitea-api.ts
+++ b/apps/api/src/plugins/gitea/utils/gitea-api.ts
@@ -84,9 +84,8 @@ export async function giteaFetch<T>(
}
}
- let res: Response;
try {
- res = await fetch(url, {
+ const res = await fetch(url, {
...init,
signal: controller.signal,
headers: {
@@ -94,7 +93,36 @@ export async function giteaFetch<T>(
...init?.headers,
},
});
+
+ const text = await res.text();
+ clearTimeout(timeoutId);
+
+ if (!res.ok) {
+ throw new GiteaApiError(
+ `Gitea API error ${res.status}`,
+ res.status,
+ text,
+ );
+ }
+
+ if (res.status === 204 || text === "") {
+ return undefined;
+ }
+
+ try {
+ return JSON.parse(text) as T;
+ } catch {
+ throw new GiteaApiError(
+ "Gitea API returned invalid JSON",
+ res.status,
+ text,
+ );
+ }
} catch (error) {
+ clearTimeout(timeoutId);
+ if (error instanceof GiteaApiError) {
+ throw error;
+ }
if (error instanceof Error && error.name === "AbortError") {
if (timedOut) {
throw new GiteaApiError(
@@ -105,27 +133,6 @@ export async function giteaFetch<T>(
throw error;
}
throw error;
- } finally {
- clearTimeout(timeoutId);
- }
-
- const text = await res.text();
- if (!res.ok) {
- throw new GiteaApiError(`Gitea API error ${res.status}`, res.status, text);
- }
-
- if (res.status === 204 || text === "") {
- return undefined;
- }
-
- try {
- return JSON.parse(text) as T;
- } catch {
- throw new GiteaApiError(
- "Gitea API returned invalid JSON",
- res.status,
- text,
- );
}
}
@@ -321,7 +328,7 @@ export function createGiteaClient(
const chunk = labelIds.slice(i, i + MAX_LABELS_PER_REQUEST);
await giteaFetch<unknown>(baseUrl, accessToken, path, {
method: "POST",
- body: JSON.stringify(chunk),
+ body: JSON.stringify({ labels: chunk }),
});
}
},
@@ -338,7 +345,7 @@ export function createGiteaClient(
`${owner(repositoryOwner, repositoryName)}/issues/${index}/labels`,
{
method: "PUT",
- body: JSON.stringify(labelIds),
+ body: JSON.stringify({ labels: labelIds }),
},
);
},
diff --git a/apps/api/src/plugins/gitea/utils/outbound-echo.ts b/apps/api/src/plugins/gitea/utils/outbound-echo.ts
new file mode 100644
index 000000000..c52d9136b
--- /dev/null
+++ b/apps/api/src/plugins/gitea/utils/outbound-echo.ts
@@ -0,0 +1,11 @@
+/** Skip webhook sync when it likely echoes our own outbound API update. */
+export const OUTBOUND_STATE_ECHO_WINDOW_MS = 5000;
+
+export function parseIssueUpdatedAtMs(issue: {
+ updated_at?: string;
+}): number | null {
+ const raw = issue.updated_at;
+ if (!raw || typeof raw !== "string") return null;
+ const t = Date.parse(raw);
+ return Number.isNaN(t) ? null : t;
+}
diff --git a/apps/api/src/plugins/gitea/webhooks/issue-closed.ts b/apps/api/src/plugins/gitea/webhooks/issue-closed.ts
index 4c0e6557d..3fe2f9f2f 100644
--- a/apps/api/src/plugins/gitea/webhooks/issue-closed.ts
+++ b/apps/api/src/plugins/gitea/webhooks/issue-closed.ts
@@ -1,12 +1,17 @@
import { and, eq } from "drizzle-orm";
import db from "../../../database";
import { externalLinkTable, taskTable } from "../../../database/schema";
+import { publishEvent } from "../../../events";
import { updateExternalLink } from "../../github/services/link-manager";
import { updateTaskStatus } from "../../github/services/task-service";
import {
findAllIntegrationsByGiteaRepo,
repoOwnerLogin,
} from "../services/integration-lookup";
+import {
+ OUTBOUND_STATE_ECHO_WINDOW_MS,
+ parseIssueUpdatedAtMs,
+} from "../utils/outbound-echo";
import { resolveTargetStatus } from "../utils/resolve-column";
import { baseUrlFromRepositoryHtmlUrl } from "../utils/webhook-repo";
@@ -17,6 +22,7 @@ type IssueClosedPayload = {
title: string;
html_url: string;
state: string;
+ updated_at?: string;
};
repository: {
owner: { login?: string; username?: string };
@@ -79,8 +85,15 @@ export async function handleGiteaIssueClosed(payload: IssueClosedPayload) {
}
}
- if (existingMetadata.createdFrom === "kaneo") {
- continue;
+ const lastOutbound = existingMetadata.lastOutboundStateSyncAt;
+ if (typeof lastOutbound === "number" && Number.isFinite(lastOutbound)) {
+ const eventMs = parseIssueUpdatedAtMs(issue);
+ if (
+ eventMs !== null &&
+ Math.abs(eventMs - lastOutbound) <= OUTBOUND_STATE_ECHO_WINDOW_MS
+ ) {
+ continue;
+ }
}
const targetStatus = await resolveTargetStatus(
@@ -89,7 +102,22 @@ export async function handleGiteaIssueClosed(payload: IssueClosedPayload) {
"done",
);
- await updateTaskStatus(task.id, targetStatus);
+ const statusResult = await updateTaskStatus(task.id, targetStatus);
+ if (
+ statusResult.applied &&
+ statusResult.before.status !== statusResult.after.status
+ ) {
+ await 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: {
diff --git a/apps/api/src/plugins/gitea/webhooks/issue-labeled.ts b/apps/api/src/plugins/gitea/webhooks/issue-labeled.ts
index e508a7e86..d08ca7cac 100644
--- a/apps/api/src/plugins/gitea/webhooks/issue-labeled.ts
+++ b/apps/api/src/plugins/gitea/webhooks/issue-labeled.ts
@@ -1,6 +1,7 @@
import { eq, inArray } from "drizzle-orm";
import db from "../../../database";
import { labelTable, taskTable } from "../../../database/schema";
+import { publishEvent } from "../../../events";
import { findExternalLink } from "../../github/services/link-manager";
import { updateTaskStatus } from "../../github/services/task-service";
import {
@@ -125,108 +126,135 @@ export async function handleGiteaIssueLabeled(payload: IssueLabeledPayload) {
);
for (const integration of integrations) {
- const existingLink = await findExternalLink(
- integration.id,
- "issue",
- issue.number.toString(),
- );
-
- if (!existingLink) {
- continue;
- }
+ try {
+ const existingLink = await findExternalLink(
+ integration.id,
+ "issue",
+ issue.number.toString(),
+ );
- const priority = extractIssuePriority(issue.labels);
- const status = extractIssueStatus(issue.labels);
+ if (!existingLink) {
+ continue;
+ }
- if (priority) {
- await db
- .update(taskTable)
- .set({ priority })
- .where(eq(taskTable.id, existingLink.taskId));
- }
+ const priority = extractIssuePriority(issue.labels);
+ const status = extractIssueStatus(issue.labels);
- if (status) {
- await updateTaskStatus(existingLink.taskId, status);
- }
-
- if (payload.action === "label_updated") {
- if (issue.labels === undefined) {
- continue;
+ if (priority) {
+ await db
+ .update(taskTable)
+ .set({ priority })
+ .where(eq(taskTable.id, existingLink.taskId));
}
- const task = await db.query.taskTable.findFirst({
- where: eq(taskTable.id, existingLink.taskId),
- with: {
- project: true,
- },
- });
- if (task?.project?.workspaceId) {
- await syncGiteaLabelsToTask(
+ if (status) {
+ const statusResult = await updateTaskStatus(
existingLink.taskId,
- task.project.workspaceId,
- giteaLabelsForSync(issue.labels),
+ status,
);
+ if (
+ statusResult.applied &&
+ statusResult.before.status !== statusResult.after.status
+ ) {
+ await 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",
+ });
+ }
}
- continue;
- }
- if (!addedLabel) {
- continue;
- }
+ if (payload.action === "label_updated") {
+ if (issue.labels === undefined) {
+ continue;
+ }
- if (isSystemLabelName(addedLabel.name)) {
- continue;
- }
+ const task = await db.query.taskTable.findFirst({
+ where: eq(taskTable.id, existingLink.taskId),
+ with: {
+ project: true,
+ },
+ });
+ if (task?.project?.workspaceId) {
+ await syncGiteaLabelsToTask(
+ existingLink.taskId,
+ task.project.workspaceId,
+ giteaLabelsForSync(issue.labels),
+ );
+ }
+ continue;
+ }
- if (payload.action === "labeled") {
- const task = await db.query.taskTable.findFirst({
- where: eq(taskTable.id, existingLink.taskId),
- with: {
- project: true,
- },
- });
+ if (!addedLabel) {
+ continue;
+ }
+
+ if (isSystemLabelName(addedLabel.name)) {
+ continue;
+ }
+
+ if (payload.action === "labeled") {
+ const task = await db.query.taskTable.findFirst({
+ where: eq(taskTable.id, existingLink.taskId),
+ with: {
+ project: true,
+ },
+ });
- if (task?.project?.workspaceId) {
- const existingLabel = await db.query.labelTable.findFirst({
+ if (task?.project?.workspaceId) {
+ const existingLabel = await db.query.labelTable.findFirst({
+ where: (table, { and, eq: e }) =>
+ and(
+ e(table.workspaceId, task.project.workspaceId),
+ e(table.name, addedLabel.name),
+ e(table.taskId, task.id),
+ ),
+ });
+
+ if (!existingLabel) {
+ const color = addedLabel.color
+ ? `#${addedLabel.color.replace(/^#/, "")}`
+ : "#6B7280";
+ await db
+ .insert(labelTable)
+ .values({
+ name: addedLabel.name,
+ color,
+ taskId: task.id,
+ workspaceId: task.project.workspaceId,
+ })
+ .onConflictDoNothing({
+ target: [labelTable.taskId, labelTable.name],
+ });
+ }
+ }
+ }
+
+ if (payload.action === "unlabeled") {
+ const labelsToDelete = await db.query.labelTable.findMany({
where: (table, { and, eq: e }) =>
and(
- e(table.workspaceId, task.project.workspaceId),
+ e(table.taskId, existingLink.taskId),
e(table.name, addedLabel.name),
- e(table.taskId, task.id),
),
});
- if (!existingLabel) {
- const color = addedLabel.color
- ? `#${addedLabel.color.replace(/^#/, "")}`
- : "#6B7280";
- await db
- .insert(labelTable)
- .values({
- name: addedLabel.name,
- color,
- taskId: task.id,
- workspaceId: task.project.workspaceId,
- })
- .onConflictDoNothing({
- target: [labelTable.taskId, labelTable.name],
- });
+ for (const label of labelsToDelete) {
+ await db.delete(labelTable).where(eq(labelTable.id, label.id));
}
}
- }
-
- if (payload.action === "unlabeled") {
- const labelsToDelete = await db.query.labelTable.findMany({
- where: (table, { and, eq: e }) =>
- and(
- e(table.taskId, existingLink.taskId),
- e(table.name, addedLabel.name),
- ),
+ } catch (error) {
+ console.error("Gitea issue_labeled handler failed for integration", {
+ integrationId: integration.id,
+ issueNumber: issue.number,
+ repository: `${owner}/${repository.name}`,
+ error,
});
-
- for (const label of labelsToDelete) {
- await db.delete(labelTable).where(eq(labelTable.id, label.id));
- }
}
}
}
diff --git a/apps/api/src/plugins/gitea/webhooks/issue-reopened.ts b/apps/api/src/plugins/gitea/webhooks/issue-reopened.ts
index 4c49c4b81..d1adaff4d 100644
--- a/apps/api/src/plugins/gitea/webhooks/issue-reopened.ts
+++ b/apps/api/src/plugins/gitea/webhooks/issue-reopened.ts
@@ -1,25 +1,20 @@
import { and, eq } from "drizzle-orm";
import db from "../../../database";
import { externalLinkTable, taskTable } from "../../../database/schema";
+import { publishEvent } from "../../../events";
import { updateExternalLink } from "../../github/services/link-manager";
import { updateTaskStatus } from "../../github/services/task-service";
import {
findAllIntegrationsByGiteaRepo,
repoOwnerLogin,
} from "../services/integration-lookup";
+import {
+ OUTBOUND_STATE_ECHO_WINDOW_MS,
+ parseIssueUpdatedAtMs,
+} from "../utils/outbound-echo";
import { resolveTargetStatus } from "../utils/resolve-column";
import { baseUrlFromRepositoryHtmlUrl } from "../utils/webhook-repo";
-/** Skip reopen sync when it likely echoes our own outbound state update (webhook vs API). */
-const OUTBOUND_STATE_ECHO_WINDOW_MS = 5000;
-
-function parseIssueUpdatedAtMs(issue: { updated_at?: string }): number | null {
- const raw = issue.updated_at;
- if (!raw || typeof raw !== "string") return null;
- const t = Date.parse(raw);
- return Number.isNaN(t) ? null : t;
-}
-
type IssueReopenedPayload = {
action: string;
issue: {
@@ -108,7 +103,22 @@ export async function handleGiteaIssueReopened(payload: IssueReopenedPayload) {
"to-do",
);
- await updateTaskStatus(task.id, targetStatus);
+ const statusResult = await updateTaskStatus(task.id, targetStatus);
+ if (
+ statusResult.applied &&
+ statusResult.before.status !== statusResult.after.status
+ ) {
+ await 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: {
@@ -119,6 +129,8 @@ export async function handleGiteaIssueReopened(payload: IssueReopenedPayload) {
} catch (error) {
console.error("Gitea issue_reopened handler failed for integration", {
integrationId: integration.id,
+ issueNumber: issue.number,
+ repository: `${owner}/${repository.name}`,
error,
});
}
diff --git a/apps/api/src/plugins/github/services/task-service.ts b/apps/api/src/plugins/github/services/task-service.ts
index 996ed9b54..603ca9f95 100644
--- a/apps/api/src/plugins/github/services/task-service.ts
+++ b/apps/api/src/plugins/github/services/task-service.ts
@@ -1,3 +1,4 @@
+import type { InferSelectModel } from "drizzle-orm";
import { and, eq } from "drizzle-orm";
import db from "../../../database";
import {
@@ -6,6 +7,12 @@ import {
taskTable,
} from "../../../database/schema";
+export type TaskRow = InferSelectModel<typeof taskTable>;
+
+export type UpdateTaskStatusResult =
+ | { applied: false }
+ | { applied: true; before: TaskRow; after: TaskRow };
+
const NON_COLUMN_STATUSES = new Set(["planned", "archived"]);
export async function findTaskByNumber(projectId: string, taskNumber: number) {
@@ -23,13 +30,16 @@ export async function findTaskById(taskId: string) {
});
}
-export async function updateTaskStatus(taskId: string, newStatus: string) {
+export async function updateTaskStatus(
+ taskId: string,
+ newStatus: string,
+): Promise<UpdateTaskStatusResult> {
const task = await db.query.taskTable.findFirst({
where: eq(taskTable.id, taskId),
});
if (!task) {
- return;
+ return { applied: false };
}
let columnId: string | null = null;
@@ -47,13 +57,23 @@ export async function updateTaskStatus(taskId: string, newStatus: string) {
console.warn(
`[GitHub] Skipping status update for task ${taskId}: column "${newStatus}" not found in project ${task.projectId}`,
);
- return;
+ return { applied: false };
}
await db
.update(taskTable)
.set({ status: newStatus, columnId })
.where(eq(taskTable.id, taskId));
+
+ const after = await db.query.taskTable.findFirst({
+ where: eq(taskTable.id, taskId),
+ });
+
+ if (!after) {
+ return { applied: false };
+ }
+
+ return { applied: true, before: task, after };
}
export async function isTaskInFinalState(task: {