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): map upstream errors, tighten sync, and fix bulk labels

Cursor Agent3fb52f44289a
diff --git a/apps/api/src/gitea-integration/controllers/create-gitea-integration.ts b/apps/api/src/gitea-integration/controllers/create-gitea-integration.ts
index 5a4dac43c..f83394ac6 100644
--- a/apps/api/src/gitea-integration/controllers/create-gitea-integration.ts
+++ b/apps/api/src/gitea-integration/controllers/create-gitea-integration.ts
@@ -11,6 +11,7 @@ import {
} from "../../plugins/gitea/config";
import {
createGiteaClient,
+ GiteaApiError,
verifyGiteaToken,
} from "../../plugins/gitea/utils/gitea-api";
@@ -63,13 +64,20 @@ async function createGiteaIntegration({
});
}
- await verifyGiteaToken(normalizedBase, resolvedToken);
+ try {
+ await verifyGiteaToken(normalizedBase, resolvedToken);
- const client = createGiteaClient({
- baseUrl: normalizedBase,
- accessToken: resolvedToken,
- });
- await client.getRepo(repositoryOwner, repositoryName);
+ const client = createGiteaClient({
+ baseUrl: normalizedBase,
+ accessToken: resolvedToken,
+ });
+ await client.getRepo(repositoryOwner, repositoryName);
+ } catch (error) {
+ if (error instanceof GiteaApiError) {
+ throw new HTTPException(error.status || 400, { message: error.message });
+ }
+ throw error;
+ }
const allGitea = await db.query.integrationTable.findMany({
where: eq(integrationTable.type, "gitea"),
@@ -79,6 +87,9 @@ async function createGiteaIntegration({
if (integration.projectId === projectId) {
continue;
}
+ if (!integration.isActive) {
+ continue;
+ }
try {
const cfg = JSON.parse(integration.config) as {
baseUrl?: string;
diff --git a/apps/api/src/plugins/gitea/events/task-created.ts b/apps/api/src/plugins/gitea/events/task-created.ts
index d703f42e1..007901f55 100644
--- a/apps/api/src/plugins/gitea/events/task-created.ts
+++ b/apps/api/src/plugins/gitea/events/task-created.ts
@@ -54,6 +54,7 @@ export async function handleTaskCreated(
metadata: {
state: createdIssue.state,
createdFrom: "kaneo",
+ lastOutboundStateSyncAt: Date.now(),
},
});
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 8ce07946c..957092960 100644
--- a/apps/api/src/plugins/gitea/events/task-status-changed.ts
+++ b/apps/api/src/plugins/gitea/events/task-status-changed.ts
@@ -48,6 +48,7 @@ export async function handleTaskStatusChanged(
metadata: {
...(issueLink.metadata ? JSON.parse(issueLink.metadata) : {}),
state: "closed",
+ lastOutboundStateSyncAt: Date.now(),
},
});
} else if (event.oldStatus === "done" && event.newStatus !== "done") {
@@ -59,6 +60,7 @@ export async function handleTaskStatusChanged(
metadata: {
...(issueLink.metadata ? JSON.parse(issueLink.metadata) : {}),
state: "open",
+ lastOutboundStateSyncAt: Date.now(),
},
});
}
diff --git a/apps/api/src/plugins/gitea/utils/gitea-api.ts b/apps/api/src/plugins/gitea/utils/gitea-api.ts
index 9441fd7f9..5fd443ed9 100644
--- a/apps/api/src/plugins/gitea/utils/gitea-api.ts
+++ b/apps/api/src/plugins/gitea/utils/gitea-api.ts
@@ -69,10 +69,11 @@ export async function giteaFetch<T>(
const url = `${root}/api/v1${path.startsWith("/") ? path : `/${path}`}`;
const controller = new AbortController();
- const timeoutId = setTimeout(
- () => controller.abort(),
- GITEA_FETCH_TIMEOUT_MS,
- );
+ let timedOut = false;
+ const timeoutId = setTimeout(() => {
+ timedOut = true;
+ controller.abort();
+ }, GITEA_FETCH_TIMEOUT_MS);
if (init?.signal) {
if (init.signal.aborted) {
controller.abort();
@@ -95,10 +96,13 @@ export async function giteaFetch<T>(
});
} catch (error) {
if (error instanceof Error && error.name === "AbortError") {
- throw new GiteaApiError(
- `Gitea request timed out after ${GITEA_FETCH_TIMEOUT_MS}ms`,
- 408,
- );
+ if (timedOut) {
+ throw new GiteaApiError(
+ `Gitea request timed out after ${GITEA_FETCH_TIMEOUT_MS}ms`,
+ 408,
+ );
+ }
+ throw error;
}
throw error;
} finally {
diff --git a/apps/api/src/plugins/gitea/utils/labels.ts b/apps/api/src/plugins/gitea/utils/labels.ts
index d369fed86..fdf60e119 100644
--- a/apps/api/src/plugins/gitea/utils/labels.ts
+++ b/apps/api/src/plugins/gitea/utils/labels.ts
@@ -82,6 +82,8 @@ export async function addLabelsToIssueGitea(
if (ids.length === 0) return;
+ const client = createGiteaClient(config);
+
try {
await client.addLabelsToIssue(
config.repositoryOwner,
diff --git a/apps/api/src/plugins/gitea/webhooks/issue-labeled.ts b/apps/api/src/plugins/gitea/webhooks/issue-labeled.ts
index b75ab7c7b..e508a7e86 100644
--- a/apps/api/src/plugins/gitea/webhooks/issue-labeled.ts
+++ b/apps/api/src/plugins/gitea/webhooks/issue-labeled.ts
@@ -47,6 +47,10 @@ function giteaLabelsForSync(
return out;
}
+function normalizedGiteaLabelColor(g: { color?: string }): string {
+ return g.color ? `#${g.color.replace(/^#/, "")}` : "#6B7280";
+}
+
async function syncGiteaLabelsToTask(
taskId: string,
workspaceId: string,
@@ -61,11 +65,32 @@ async function syncGiteaLabelsToTask(
.filter((g) => !existingRows.some((row) => row.name === g.name))
.map((g) => ({
name: g.name,
- color: g.color ? `#${g.color.replace(/^#/, "")}` : "#6B7280",
+ color: normalizedGiteaLabelColor(g),
taskId,
workspaceId,
}));
+ const colorToIds = new Map<string, string[]>();
+ for (const g of giteaLabels) {
+ if (isSystemLabelName(g.name)) continue;
+ const row = existingRows.find((r) => r.name === g.name);
+ if (!row) continue;
+ const want = normalizedGiteaLabelColor(g);
+ const have = row.color ? `#${row.color.replace(/^#/, "")}` : "#6B7280";
+ if (have === want) continue;
+ const list = colorToIds.get(want) ?? [];
+ list.push(row.id);
+ colorToIds.set(want, list);
+ }
+
+ for (const [color, ids] of colorToIds) {
+ if (ids.length === 0) continue;
+ await db
+ .update(labelTable)
+ .set({ color })
+ .where(inArray(labelTable.id, ids));
+ }
+
if (labelsToInsert.length > 0) {
await db
.insert(labelTable)
diff --git a/apps/api/src/plugins/gitea/webhooks/issue-reopened.ts b/apps/api/src/plugins/gitea/webhooks/issue-reopened.ts
index d00f67f32..4c49c4b81 100644
--- a/apps/api/src/plugins/gitea/webhooks/issue-reopened.ts
+++ b/apps/api/src/plugins/gitea/webhooks/issue-reopened.ts
@@ -10,6 +10,16 @@ import {
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: {
@@ -17,6 +27,7 @@ type IssueReopenedPayload = {
title: string;
html_url: string;
state: string;
+ updated_at?: string;
};
repository: {
owner: { login?: string; username?: string };
@@ -80,8 +91,15 @@ export async function handleGiteaIssueReopened(payload: IssueReopenedPayload) {
}
}
- 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(
diff --git a/apps/api/src/task/controllers/bulk-update-tasks.ts b/apps/api/src/task/controllers/bulk-update-tasks.ts
index 236ed886f..baaa696c5 100644
--- a/apps/api/src/task/controllers/bulk-update-tasks.ts
+++ b/apps/api/src/task/controllers/bulk-update-tasks.ts
@@ -167,7 +167,6 @@ async function bulkUpdateTasks({
const existingAssignment = await db.query.labelTable.findFirst({
where: and(
eq(labelTable.name, label.name),
- eq(labelTable.color, label.color),
eq(labelTable.taskId, task.id),
),
});