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.

feat(api): add Gitea plugin with webhooks and sync helpers

Tin77e7836fc230
diff --git a/apps/api/src/plugins/gitea/config.ts b/apps/api/src/plugins/gitea/config.ts
new file mode 100644
index 000000000..de3ac0192
--- /dev/null
+++ b/apps/api/src/plugins/gitea/config.ts
@@ -0,0 +1,75 @@
+import * as v from "valibot";
+import { branchPatterns } from "../github/config";
+
+export { branchPatterns };
+
+export const giteaConfigSchema = v.object({
+ baseUrl: v.string(),
+ accessToken: v.string(),
+ repositoryOwner: v.string(),
+ repositoryName: v.string(),
+ webhookSecret: v.optional(v.string()),
+ branchPattern: v.optional(v.string()),
+ customBranchRegex: v.optional(v.string()),
+ commentTaskLinkOnGiteaIssue: v.optional(v.boolean()),
+ statusTransitions: v.optional(
+ v.object({
+ onBranchPush: v.optional(v.string()),
+ onPROpen: v.optional(v.string()),
+ onPRMerge: v.optional(v.string()),
+ }),
+ ),
+});
+
+export type GiteaConfig = v.InferOutput<typeof giteaConfigSchema>;
+
+export async function validateGiteaConfig(
+ config: unknown,
+): Promise<{ valid: boolean; errors?: string[] }> {
+ try {
+ v.parse(giteaConfigSchema, config);
+ return { valid: true };
+ } catch (error) {
+ if (error instanceof v.ValiError) {
+ return {
+ valid: false,
+ errors: error.issues.map((issue) => issue.message),
+ };
+ }
+ return {
+ valid: false,
+ errors: [error instanceof Error ? error.message : "Invalid config"],
+ };
+ }
+}
+
+export const defaultGiteaConfig: Partial<GiteaConfig> = {
+ branchPattern: "{slug}-{number}",
+ commentTaskLinkOnGiteaIssue: true,
+ statusTransitions: {
+ onBranchPush: "in-progress",
+ onPROpen: "in-review",
+ onPRMerge: "done",
+ },
+};
+
+export function normalizeGiteaBaseUrl(url: string): string {
+ return url.trim().replace(/\/+$/, "");
+}
+
+export function getDefaultGiteaConfig(
+ baseUrl: string,
+ accessToken: string,
+ repositoryOwner: string,
+ repositoryName: string,
+ webhookSecret: string,
+): GiteaConfig {
+ return {
+ baseUrl: normalizeGiteaBaseUrl(baseUrl),
+ accessToken,
+ repositoryOwner,
+ repositoryName,
+ webhookSecret,
+ ...defaultGiteaConfig,
+ };
+}
diff --git a/apps/api/src/plugins/gitea/events/task-comment-created.ts b/apps/api/src/plugins/gitea/events/task-comment-created.ts
new file mode 100644
index 000000000..58c5edc8f
--- /dev/null
+++ b/apps/api/src/plugins/gitea/events/task-comment-created.ts
@@ -0,0 +1,40 @@
+import { findExternalLinkByTaskAndType } from "../../github/services/link-manager";
+import type { PluginContext, TaskCommentCreatedEvent } from "../../types";
+import type { GiteaConfig } from "../config";
+import { createGiteaClient } from "../utils/gitea-api";
+
+export async function handleTaskCommentCreated(
+ event: TaskCommentCreatedEvent,
+ context: PluginContext,
+): Promise<void> {
+ const config = context.config as GiteaConfig;
+ if (!config.baseUrl || !config.accessToken) {
+ return;
+ }
+
+ const { repositoryOwner, repositoryName } = config;
+
+ const existingLink = await findExternalLinkByTaskAndType(
+ event.taskId,
+ context.integrationId,
+ "issue",
+ );
+
+ if (!existingLink) {
+ return;
+ }
+
+ try {
+ const client = createGiteaClient(config);
+ const issueNumber = Number.parseInt(existingLink.externalId, 10);
+
+ await client.createIssueComment(
+ repositoryOwner,
+ repositoryName,
+ issueNumber,
+ event.comment,
+ );
+ } catch (error) {
+ console.error("Failed to create Gitea comment:", error);
+ }
+}
diff --git a/apps/api/src/plugins/gitea/events/task-created.ts b/apps/api/src/plugins/gitea/events/task-created.ts
new file mode 100644
index 000000000..32905548e
--- /dev/null
+++ b/apps/api/src/plugins/gitea/events/task-created.ts
@@ -0,0 +1,65 @@
+import {
+ createExternalLink,
+ findExternalLinkByTaskAndType,
+} from "../../github/services/link-manager";
+import {
+ formatIssueBody,
+ formatIssueTitle,
+ getLabelsForIssue,
+} from "../../github/utils/format";
+import type { PluginContext, TaskCreatedEvent } from "../../types";
+import type { GiteaConfig } from "../config";
+import { createGiteaClient } from "../utils/gitea-api";
+import { addLabelsToIssueGitea } from "../utils/labels";
+
+export async function handleTaskCreated(
+ event: TaskCreatedEvent,
+ context: PluginContext,
+): Promise<void> {
+ const config = context.config as GiteaConfig;
+ if (!config.baseUrl || !config.accessToken) {
+ return;
+ }
+
+ const { repositoryOwner, repositoryName } = config;
+
+ const existingLink = await findExternalLinkByTaskAndType(
+ event.taskId,
+ context.integrationId,
+ "issue",
+ );
+
+ if (existingLink) {
+ return;
+ }
+
+ try {
+ const client = createGiteaClient(config);
+ const createdIssue = await client.createIssue(
+ repositoryOwner,
+ repositoryName,
+ {
+ title: formatIssueTitle(event.title),
+ body: formatIssueBody(event.description, event.taskId),
+ },
+ );
+
+ const labels = getLabelsForIssue(event.priority, event.status);
+ await addLabelsToIssueGitea(config, createdIssue.number, labels);
+
+ await createExternalLink({
+ taskId: event.taskId,
+ integrationId: context.integrationId,
+ resourceType: "issue",
+ externalId: createdIssue.number.toString(),
+ url: createdIssue.html_url,
+ title: createdIssue.title,
+ metadata: {
+ state: createdIssue.state,
+ createdFrom: "kaneo",
+ },
+ });
+ } catch (error) {
+ console.error("Failed to create Gitea issue:", error);
+ }
+}
diff --git a/apps/api/src/plugins/gitea/events/task-description-changed.ts b/apps/api/src/plugins/gitea/events/task-description-changed.ts
new file mode 100644
index 000000000..b054506f4
--- /dev/null
+++ b/apps/api/src/plugins/gitea/events/task-description-changed.ts
@@ -0,0 +1,84 @@
+import {
+ findExternalLinksByTask,
+ updateExternalLink,
+} from "../../github/services/link-manager";
+import { formatIssueBody } from "../../github/utils/format";
+import type { PluginContext, TaskDescriptionChangedEvent } from "../../types";
+import type { GiteaConfig } from "../config";
+import { createGiteaClient } from "../utils/gitea-api";
+
+export async function handleTaskDescriptionChanged(
+ event: TaskDescriptionChangedEvent,
+ context: PluginContext,
+): Promise<void> {
+ const config = context.config as GiteaConfig;
+ if (!config.baseUrl || !config.accessToken) {
+ return;
+ }
+
+ const { repositoryOwner, repositoryName } = config;
+
+ try {
+ const links = await findExternalLinksByTask(event.taskId);
+ const issueLink = links.find(
+ (link) =>
+ link.integrationId === context.integrationId &&
+ link.resourceType === "issue",
+ );
+
+ if (!issueLink) {
+ return;
+ }
+
+ const metadata = issueLink.metadata ? JSON.parse(issueLink.metadata) : {};
+
+ const lastDescSync = metadata.lastSync?.description;
+ const newDescNormalized = event.newDescription || "";
+
+ if (lastDescSync) {
+ if (
+ lastDescSync.value === newDescNormalized &&
+ lastDescSync.source === "gitea"
+ ) {
+ console.log("Skipping description sync - already synced from Gitea");
+ return;
+ }
+
+ const timeSinceLastSync =
+ Date.now() - new Date(lastDescSync.timestamp).getTime();
+ if (timeSinceLastSync < 2000) {
+ console.log(
+ `Skipping description sync - recent sync detected (${timeSinceLastSync}ms ago)`,
+ );
+ return;
+ }
+ }
+
+ const client = createGiteaClient(config);
+ const issueNumber = Number.parseInt(issueLink.externalId, 10);
+
+ const formattedBody = formatIssueBody(event.newDescription, event.taskId);
+
+ await client.updateIssue(repositoryOwner, repositoryName, issueNumber, {
+ body: formattedBody,
+ });
+
+ await updateExternalLink(issueLink.id, {
+ metadata: {
+ ...metadata,
+ lastSync: {
+ ...metadata.lastSync,
+ description: {
+ timestamp: new Date().toISOString(),
+ source: "kaneo",
+ value: newDescNormalized,
+ },
+ },
+ },
+ });
+
+ console.log(`Synced task description to Gitea issue #${issueNumber}`);
+ } catch (error) {
+ console.error("Failed to update Gitea issue description:", error);
+ }
+}
diff --git a/apps/api/src/plugins/gitea/events/task-priority-changed.ts b/apps/api/src/plugins/gitea/events/task-priority-changed.ts
new file mode 100644
index 000000000..c18e0caaa
--- /dev/null
+++ b/apps/api/src/plugins/gitea/events/task-priority-changed.ts
@@ -0,0 +1,45 @@
+import { findExternalLinksByTask } from "../../github/services/link-manager";
+import type { PluginContext, TaskPriorityChangedEvent } from "../../types";
+import type { GiteaConfig } from "../config";
+import { addLabelsToIssueGitea, removeLabelGitea } from "../utils/labels";
+
+export async function handleTaskPriorityChanged(
+ event: TaskPriorityChangedEvent,
+ context: PluginContext,
+): Promise<void> {
+ const config = context.config as GiteaConfig;
+ if (!config.baseUrl || !config.accessToken) {
+ return;
+ }
+
+ try {
+ const links = await findExternalLinksByTask(event.taskId);
+ const issueLink = links.find(
+ (link) =>
+ link.integrationId === context.integrationId &&
+ link.resourceType === "issue",
+ );
+
+ if (!issueLink) {
+ return;
+ }
+
+ const issueNumber = Number.parseInt(issueLink.externalId, 10);
+
+ if (event.oldPriority && event.oldPriority !== "no-priority") {
+ await removeLabelGitea(
+ config,
+ issueNumber,
+ `priority:${event.oldPriority}`,
+ );
+ }
+
+ if (event.newPriority && event.newPriority !== "no-priority") {
+ await addLabelsToIssueGitea(config, issueNumber, [
+ `priority:${event.newPriority}`,
+ ]);
+ }
+ } catch (error) {
+ console.error("Failed to update Gitea issue priority:", error);
+ }
+}
diff --git a/apps/api/src/plugins/gitea/events/task-status-changed.ts b/apps/api/src/plugins/gitea/events/task-status-changed.ts
new file mode 100644
index 000000000..8ce07946c
--- /dev/null
+++ b/apps/api/src/plugins/gitea/events/task-status-changed.ts
@@ -0,0 +1,68 @@
+import {
+ findExternalLinksByTask,
+ updateExternalLink,
+} from "../../github/services/link-manager";
+import type { PluginContext, TaskStatusChangedEvent } from "../../types";
+import type { GiteaConfig } from "../config";
+import { createGiteaClient } from "../utils/gitea-api";
+import { addLabelsToIssueGitea, removeLabelGitea } from "../utils/labels";
+
+export async function handleTaskStatusChanged(
+ event: TaskStatusChangedEvent,
+ context: PluginContext,
+): Promise<void> {
+ const config = context.config as GiteaConfig;
+ if (!config.baseUrl || !config.accessToken) {
+ return;
+ }
+
+ const { repositoryOwner, repositoryName } = config;
+
+ try {
+ const links = await findExternalLinksByTask(event.taskId);
+ const issueLink = links.find(
+ (link) =>
+ link.integrationId === context.integrationId &&
+ link.resourceType === "issue",
+ );
+
+ if (!issueLink) {
+ return;
+ }
+
+ const client = createGiteaClient(config);
+ const issueNumber = Number.parseInt(issueLink.externalId, 10);
+
+ await removeLabelGitea(config, issueNumber, `status:${event.oldStatus}`);
+
+ await addLabelsToIssueGitea(config, issueNumber, [
+ `status:${event.newStatus}`,
+ ]);
+
+ if (event.newStatus === "done") {
+ await client.updateIssue(repositoryOwner, repositoryName, issueNumber, {
+ state: "closed",
+ });
+
+ await updateExternalLink(issueLink.id, {
+ metadata: {
+ ...(issueLink.metadata ? JSON.parse(issueLink.metadata) : {}),
+ state: "closed",
+ },
+ });
+ } else if (event.oldStatus === "done" && event.newStatus !== "done") {
+ await client.updateIssue(repositoryOwner, repositoryName, issueNumber, {
+ state: "open",
+ });
+
+ await updateExternalLink(issueLink.id, {
+ metadata: {
+ ...(issueLink.metadata ? JSON.parse(issueLink.metadata) : {}),
+ state: "open",
+ },
+ });
+ }
+ } catch (error) {
+ console.error("Failed to update Gitea issue status:", 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
new file mode 100644
index 000000000..60b4f8276
--- /dev/null
+++ b/apps/api/src/plugins/gitea/events/task-title-changed.ts
@@ -0,0 +1,80 @@
+import {
+ findExternalLinksByTask,
+ updateExternalLink,
+} from "../../github/services/link-manager";
+import type { PluginContext, TaskTitleChangedEvent } from "../../types";
+import type { GiteaConfig } from "../config";
+import { createGiteaClient } from "../utils/gitea-api";
+
+export async function handleTaskTitleChanged(
+ event: TaskTitleChangedEvent,
+ context: PluginContext,
+): Promise<void> {
+ const config = context.config as GiteaConfig;
+ if (!config.baseUrl || !config.accessToken) {
+ return;
+ }
+
+ const { repositoryOwner, repositoryName } = config;
+
+ try {
+ const links = await findExternalLinksByTask(event.taskId);
+ const issueLink = links.find(
+ (link) =>
+ link.integrationId === context.integrationId &&
+ link.resourceType === "issue",
+ );
+
+ if (!issueLink) {
+ return;
+ }
+
+ const metadata = issueLink.metadata ? JSON.parse(issueLink.metadata) : {};
+
+ const lastTitleSync = metadata.lastSync?.title;
+ if (lastTitleSync) {
+ if (
+ lastTitleSync.value === event.newTitle &&
+ lastTitleSync.source === "gitea"
+ ) {
+ console.log("Skipping title sync - already synced from Gitea");
+ return;
+ }
+
+ const timeSinceLastSync =
+ Date.now() - new Date(lastTitleSync.timestamp).getTime();
+ if (timeSinceLastSync < 2000) {
+ console.log(
+ `Skipping title sync - recent sync detected (${timeSinceLastSync}ms ago)`,
+ );
+ return;
+ }
+ }
+
+ const client = createGiteaClient(config);
+ const issueNumber = Number.parseInt(issueLink.externalId, 10);
+
+ await client.updateIssue(repositoryOwner, repositoryName, issueNumber, {
+ title: event.newTitle,
+ });
+
+ await updateExternalLink(issueLink.id, {
+ title: event.newTitle,
+ metadata: {
+ ...metadata,
+ lastSync: {
+ ...metadata.lastSync,
+ title: {
+ timestamp: new Date().toISOString(),
+ source: "kaneo",
+ value: event.newTitle,
+ },
+ },
+ },
+ });
+
+ console.log(`Synced task title to Gitea issue #${issueNumber}`);
+ } catch (error) {
+ console.error("Failed to update Gitea issue title:", error);
+ }
+}
diff --git a/apps/api/src/plugins/gitea/index.ts b/apps/api/src/plugins/gitea/index.ts
new file mode 100644
index 000000000..9df754c34
--- /dev/null
+++ b/apps/api/src/plugins/gitea/index.ts
@@ -0,0 +1,20 @@
+import type { IntegrationPlugin } from "../types";
+import { validateGiteaConfig } from "./config";
+import { handleTaskCommentCreated } from "./events/task-comment-created";
+import { handleTaskCreated } from "./events/task-created";
+import { handleTaskDescriptionChanged } from "./events/task-description-changed";
+import { handleTaskPriorityChanged } from "./events/task-priority-changed";
+import { handleTaskStatusChanged } from "./events/task-status-changed";
+import { handleTaskTitleChanged } from "./events/task-title-changed";
+
+export const giteaPlugin: IntegrationPlugin = {
+ type: "gitea",
+ name: "Gitea",
+ onTaskCreated: handleTaskCreated,
+ onTaskStatusChanged: handleTaskStatusChanged,
+ onTaskPriorityChanged: handleTaskPriorityChanged,
+ onTaskTitleChanged: handleTaskTitleChanged,
+ onTaskDescriptionChanged: handleTaskDescriptionChanged,
+ onTaskCommentCreated: handleTaskCommentCreated,
+ validateConfig: validateGiteaConfig,
+};
diff --git a/apps/api/src/plugins/gitea/services/integration-lookup.ts b/apps/api/src/plugins/gitea/services/integration-lookup.ts
new file mode 100644
index 000000000..122abb2eb
--- /dev/null
+++ b/apps/api/src/plugins/gitea/services/integration-lookup.ts
@@ -0,0 +1,41 @@
+import { and, eq } from "drizzle-orm";
+import db from "../../../database";
+import { integrationTable } from "../../../database/schema";
+import type { GiteaConfig } from "../config";
+import { normalizeGiteaBaseUrl } from "../config";
+
+export async function findAllIntegrationsByGiteaRepo(
+ baseUrl: string,
+ owner: string,
+ repo: string,
+) {
+ const normalized = normalizeGiteaBaseUrl(baseUrl);
+ const integrations = await db.query.integrationTable.findMany({
+ where: and(
+ eq(integrationTable.type, "gitea"),
+ eq(integrationTable.isActive, true),
+ ),
+ with: {
+ project: true,
+ },
+ });
+
+ return integrations.filter((integration) => {
+ try {
+ const config = JSON.parse(integration.config) as GiteaConfig;
+ return (
+ normalizeGiteaBaseUrl(config.baseUrl) === normalized &&
+ config.repositoryOwner === owner &&
+ config.repositoryName === repo
+ );
+ } catch {
+ return false;
+ }
+ });
+}
+
+export function repoOwnerLogin(repo: {
+ owner?: { login?: string; username?: string };
+}): string {
+ return repo.owner?.login ?? repo.owner?.username ?? "";
+}
diff --git a/apps/api/src/plugins/gitea/utils/branch-matcher.ts b/apps/api/src/plugins/gitea/utils/branch-matcher.ts
new file mode 100644
index 000000000..55529d115
--- /dev/null
+++ b/apps/api/src/plugins/gitea/utils/branch-matcher.ts
@@ -0,0 +1,47 @@
+import type { GitHubConfig } from "../../github/config";
+import {
+ extractTaskNumber,
+ extractTaskNumberFromBranch,
+ extractTaskNumberFromPRBody,
+ extractTaskNumberFromPRTitle,
+ generateBranchName,
+} from "../../github/utils/branch-matcher";
+import type { GiteaConfig } from "../config";
+
+function asBranchConfig(config: GiteaConfig): GitHubConfig {
+ return config as unknown as GitHubConfig;
+}
+
+export {
+ extractTaskNumberFromPRBody,
+ extractTaskNumberFromPRTitle,
+ generateBranchName,
+};
+
+export function extractTaskNumberFromBranchGitea(
+ branchName: string,
+ config: GiteaConfig,
+ projectSlug: string,
+): number | null {
+ return extractTaskNumberFromBranch(
+ branchName,
+ asBranchConfig(config),
+ projectSlug,
+ );
+}
+
+export function extractTaskNumberGitea(
+ branchName: string,
+ prTitle: string | undefined,
+ prBody: string | undefined,
+ config: GiteaConfig,
+ projectSlug: string,
+): number | null {
+ return extractTaskNumber(
+ branchName,
+ prTitle,
+ prBody,
+ asBranchConfig(config),
+ projectSlug,
+ );
+}
diff --git a/apps/api/src/plugins/gitea/utils/gitea-api.ts b/apps/api/src/plugins/gitea/utils/gitea-api.ts
new file mode 100644
index 000000000..346a8994b
--- /dev/null
+++ b/apps/api/src/plugins/gitea/utils/gitea-api.ts
@@ -0,0 +1,311 @@
+import type { GiteaConfig } from "../config";
+import { normalizeGiteaBaseUrl } from "../config";
+
+export type GiteaLabel = {
+ id: number;
+ name: string;
+ color?: string;
+};
+
+export type GiteaIssue = {
+ id: number;
+ number: number;
+ title: string;
+ body: string | null;
+ html_url: string;
+ state: string;
+ labels?: GiteaLabel[];
+ user?: { login?: string; username?: string; avatar_url?: string } | null;
+ pull_request?: unknown;
+};
+
+export type GiteaComment = {
+ id: number;
+ body: string;
+ html_url: string;
+ user?: { login?: string; username?: string; avatar_url?: string } | null;
+ created_at: string;
+};
+
+export type GiteaPullRequest = {
+ number: number;
+ title: string;
+ body: string | null;
+ html_url: string;
+ state: string;
+ head?: { ref?: string };
+ user?: { login?: string; username?: string; avatar_url?: string } | null;
+ merged?: boolean;
+ merged_at?: string | null;
+};
+
+export class GiteaApiError extends Error {
+ constructor(
+ message: string,
+ public status: number,
+ public body?: string,
+ ) {
+ super(message);
+ this.name = "GiteaApiError";
+ }
+}
+
+function authHeaders(token: string): HeadersInit {
+ return {
+ Authorization: `token ${token}`,
+ "Content-Type": "application/json",
+ };
+}
+
+export async function giteaFetch<T>(
+ baseUrl: string,
+ token: string,
+ path: string,
+ init?: RequestInit,
+): Promise<T> {
+ const root = normalizeGiteaBaseUrl(baseUrl);
+ const url = `${root}/api/v1${path.startsWith("/") ? path : `/${path}`}`;
+ const res = await fetch(url, {
+ ...init,
+ headers: {
+ ...authHeaders(token),
+ ...init?.headers,
+ },
+ });
+
+ 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 as T;
+ }
+
+ try {
+ return JSON.parse(text) as T;
+ } catch {
+ return undefined as T;
+ }
+}
+
+export function createGiteaClient(
+ config: Pick<GiteaConfig, "baseUrl" | "accessToken">,
+) {
+ const { baseUrl, accessToken } = config;
+ const owner = (o: string, r: string) =>
+ `/repos/${encodeURIComponent(o)}/${encodeURIComponent(r)}`;
+
+ return {
+ async getRepo(repositoryOwner: string, repositoryName: string) {
+ return giteaFetch<{
+ name: string;
+ owner: { login?: string; username?: string };
+ html_url: string;
+ private: boolean;
+ permissions?: { admin?: boolean; push?: boolean; pull?: boolean };
+ }>(baseUrl, accessToken, owner(repositoryOwner, repositoryName));
+ },
+
+ async listUserRepos(page = 1, limit = 50) {
+ return giteaFetch<
+ Array<{
+ id: number;
+ name: string;
+ full_name: string;
+ owner: { login?: string; username?: string };
+ private: boolean;
+ html_url: string;
+ }>
+ >(baseUrl, accessToken, `/user/repos?page=${page}&limit=${limit}`);
+ },
+
+ async createIssue(
+ repositoryOwner: string,
+ repositoryName: string,
+ body: { title: string; body?: string | null; closed?: boolean },
+ ) {
+ return giteaFetch<GiteaIssue>(
+ baseUrl,
+ accessToken,
+ `${owner(repositoryOwner, repositoryName)}/issues`,
+ {
+ method: "POST",
+ body: JSON.stringify(body),
+ },
+ );
+ },
+
+ async updateIssue(
+ repositoryOwner: string,
+ repositoryName: string,
+ index: number,
+ body: Record<string, unknown>,
+ ) {
+ return giteaFetch<GiteaIssue>(
+ baseUrl,
+ accessToken,
+ `${owner(repositoryOwner, repositoryName)}/issues/${index}`,
+ {
+ method: "PATCH",
+ body: JSON.stringify(body),
+ },
+ );
+ },
+
+ async listIssueComments(
+ repositoryOwner: string,
+ repositoryName: string,
+ index: number,
+ page: number,
+ limit: number,
+ ) {
+ return giteaFetch<GiteaComment[]>(
+ baseUrl,
+ accessToken,
+ `${owner(repositoryOwner, repositoryName)}/issues/${index}/comments?page=${page}&limit=${limit}`,
+ );
+ },
+
+ async createIssueComment(
+ repositoryOwner: string,
+ repositoryName: string,
+ index: number,
+ body: string,
+ ) {
+ return giteaFetch<GiteaComment>(
+ baseUrl,
+ accessToken,
+ `${owner(repositoryOwner, repositoryName)}/issues/${index}/comments`,
+ {
+ method: "POST",
+ body: JSON.stringify({ body }),
+ },
+ );
+ },
+
+ async listLabels(repositoryOwner: string, repositoryName: string) {
+ return giteaFetch<GiteaLabel[]>(
+ baseUrl,
+ accessToken,
+ `${owner(repositoryOwner, repositoryName)}/labels`,
+ );
+ },
+
+ async createLabel(
+ repositoryOwner: string,
+ repositoryName: string,
+ name: string,
+ color: string,
+ ) {
+ return giteaFetch<GiteaLabel>(
+ baseUrl,
+ accessToken,
+ `${owner(repositoryOwner, repositoryName)}/labels`,
+ {
+ method: "POST",
+ body: JSON.stringify({
+ name,
+ color: color.replace(/^#/, ""),
+ }),
+ },
+ );
+ },
+
+ async addLabelsToIssue(
+ repositoryOwner: string,
+ repositoryName: string,
+ index: number,
+ labelIds: number[],
+ ) {
+ if (labelIds.length === 0) return;
+ await giteaFetch<unknown>(
+ baseUrl,
+ accessToken,
+ `${owner(repositoryOwner, repositoryName)}/issues/${index}/labels`,
+ {
+ method: "POST",
+ body: JSON.stringify(labelIds),
+ },
+ );
+ },
+
+ async replaceIssueLabels(
+ repositoryOwner: string,
+ repositoryName: string,
+ index: number,
+ labelIds: number[],
+ ) {
+ await giteaFetch<unknown>(
+ baseUrl,
+ accessToken,
+ `${owner(repositoryOwner, repositoryName)}/issues/${index}/labels`,
+ {
+ method: "PUT",
+ body: JSON.stringify(labelIds),
+ },
+ );
+ },
+
+ async removeLabelFromIssue(
+ repositoryOwner: string,
+ repositoryName: string,
+ index: number,
+ labelId: number,
+ ) {
+ await giteaFetch<unknown>(
+ baseUrl,
+ accessToken,
+ `${owner(repositoryOwner, repositoryName)}/issues/${index}/labels/${labelId}`,
+ {
+ method: "DELETE",
+ },
+ );
+ },
+
+ async getIssue(
+ repositoryOwner: string,
+ repositoryName: string,
+ index: number,
+ ) {
+ return giteaFetch<GiteaIssue>(
+ baseUrl,
+ accessToken,
+ `${owner(repositoryOwner, repositoryName)}/issues/${index}`,
+ );
+ },
+
+ async listIssues(
+ repositoryOwner: string,
+ repositoryName: string,
+ page: number,
+ state: "open" | "closed" | "all",
+ ) {
+ return giteaFetch<GiteaIssue[]>(
+ baseUrl,
+ accessToken,
+ `${owner(repositoryOwner, repositoryName)}/issues?state=${state}&page=${page}&limit=100`,
+ );
+ },
+
+ async listPulls(
+ repositoryOwner: string,
+ repositoryName: string,
+ page: number,
+ ) {
+ return giteaFetch<GiteaPullRequest[]>(
+ baseUrl,
+ accessToken,
+ `${owner(repositoryOwner, repositoryName)}/pulls?state=open&page=${page}&limit=100`,
+ );
+ },
+ };
+}
+
+export async function verifyGiteaToken(baseUrl: string, token: string) {
+ return giteaFetch<{ id: number; login: string }>(
+ normalizeGiteaBaseUrl(baseUrl),
+ token,
+ "/user",
+ );
+}
diff --git a/apps/api/src/plugins/gitea/utils/labels.ts b/apps/api/src/plugins/gitea/utils/labels.ts
new file mode 100644
index 000000000..779a985ec
--- /dev/null
+++ b/apps/api/src/plugins/gitea/utils/labels.ts
@@ -0,0 +1,125 @@
+import type { GiteaConfig } from "../config";
+import { createGiteaClient, type GiteaLabel } from "./gitea-api";
+
+const labelColors: Record<string, string> = {
+ "priority:low": "0EA5E9",
+ "priority:medium": "EAB308",
+ "priority:high": "F97316",
+ "priority:urgent": "EF4444",
+ "status:to-do": "6B7280",
+ "status:in-progress": "3B82F6",
+ "status:in-review": "8B5CF6",
+ "status:done": "10B981",
+ "status:planned": "8B5CF6",
+ "status:archived": "6B7280",
+};
+
+function getLabelColor(labelName: string): string {
+ return labelColors[labelName] || "6B7280";
+}
+
+async function getOrCreateLabelId(
+ client: ReturnType<typeof createGiteaClient>,
+ config: Pick<GiteaConfig, "repositoryOwner" | "repositoryName">,
+ name: string,
+): Promise<number> {
+ const { repositoryOwner, repositoryName } = config;
+ let labels: GiteaLabel[];
+ try {
+ labels = await client.listLabels(repositoryOwner, repositoryName);
+ } catch {
+ labels = [];
+ }
+
+ const found = labels.find((l) => l.name === name);
+ if (found) {
+ return found.id;
+ }
+
+ const color = getLabelColor(name);
+ const created = await client.createLabel(
+ repositoryOwner,
+ repositoryName,
+ name,
+ color,
+ );
+ return created.id;
+}
+
+export async function ensureLabelsExistGitea(
+ config: GiteaConfig,
+ labels: string[],
+): Promise<Map<string, number>> {
+ const client = createGiteaClient(config);
+ const map = new Map<string, number>();
+ for (const name of labels) {
+ try {
+ const id = await getOrCreateLabelId(client, config, name);
+ map.set(name, id);
+ } catch (error) {
+ console.error(`Failed to ensure Gitea label "${name}":`, error);
+ }
+ }
+ return map;
+}
+
+export async function addLabelsToIssueGitea(
+ config: GiteaConfig,
+ issueIndex: number,
+ labelNames: string[],
+) {
+ if (labelNames.length === 0) return;
+
+ const client = createGiteaClient(config);
+ const ids: number[] = [];
+ for (const name of labelNames) {
+ try {
+ const id = await getOrCreateLabelId(client, config, name);
+ ids.push(id);
+ } catch (error) {
+ console.error(`Failed to add Gitea label "${name}":`, error);
+ }
+ }
+
+ if (ids.length === 0) return;
+
+ try {
+ await client.addLabelsToIssue(
+ config.repositoryOwner,
+ config.repositoryName,
+ issueIndex,
+ ids,
+ );
+ } catch (error) {
+ console.error("Failed to add labels to Gitea issue:", error);
+ }
+}
+
+export async function removeLabelGitea(
+ config: GiteaConfig,
+ issueIndex: number,
+ labelName: string,
+) {
+ const client = createGiteaClient(config);
+ let labels: GiteaLabel[];
+ try {
+ labels = await client.listLabels(
+ config.repositoryOwner,
+ config.repositoryName,
+ );
+ } catch {
+ return;
+ }
+
+ const label = labels.find((l) => l.name === labelName);
+ if (!label) return;
+
+ try {
+ await client.removeLabelFromIssue(
+ config.repositoryOwner,
+ config.repositoryName,
+ issueIndex,
+ label.id,
+ );
+ } catch {}
+}
diff --git a/apps/api/src/plugins/gitea/utils/resolve-column.ts b/apps/api/src/plugins/gitea/utils/resolve-column.ts
new file mode 100644
index 000000000..12928a3da
--- /dev/null
+++ b/apps/api/src/plugins/gitea/utils/resolve-column.ts
@@ -0,0 +1,48 @@
+import { and, asc, eq } from "drizzle-orm";
+import db from "../../../database";
+import { columnTable, workflowRuleTable } from "../../../database/schema";
+
+export async function resolveTargetStatus(
+ projectId: string,
+ eventType: string,
+ fallbackStatus: string,
+): Promise<string> {
+ const projectColumns = await db
+ .select({
+ id: columnTable.id,
+ slug: columnTable.slug,
+ })
+ .from(columnTable)
+ .where(eq(columnTable.projectId, projectId))
+ .orderBy(asc(columnTable.position));
+
+ if (projectColumns.length === 0) {
+ return fallbackStatus;
+ }
+
+ const rule = await db.query.workflowRuleTable.findFirst({
+ where: and(
+ eq(workflowRuleTable.projectId, projectId),
+ eq(workflowRuleTable.integrationType, "gitea"),
+ eq(workflowRuleTable.eventType, eventType),
+ ),
+ });
+
+ if (rule) {
+ const mappedColumn = projectColumns.find(
+ (column) => column.id === rule.columnId,
+ );
+ if (mappedColumn) {
+ return mappedColumn.slug;
+ }
+ }
+
+ const fallbackColumn = projectColumns.find(
+ (column) => column.slug === fallbackStatus,
+ );
+ if (fallbackColumn) {
+ return fallbackColumn.slug;
+ }
+
+ return projectColumns[0]?.slug ?? fallbackStatus;
+}
diff --git a/apps/api/src/plugins/gitea/utils/sync-label-to-gitea.ts b/apps/api/src/plugins/gitea/utils/sync-label-to-gitea.ts
new file mode 100644
index 000000000..585d8d583
--- /dev/null
+++ b/apps/api/src/plugins/gitea/utils/sync-label-to-gitea.ts
@@ -0,0 +1,163 @@
+import { eq } from "drizzle-orm";
+import db from "../../../database";
+import { externalLinkTable } from "../../../database/schema";
+import type { GiteaConfig } from "../config";
+import { createGiteaClient } from "./gitea-api";
+
+const namedColorToHex: Record<string, string> = {
+ red: "EF4444",
+ orange: "F97316",
+ amber: "F59E0B",
+ yellow: "EAB308",
+ lime: "84CC16",
+ green: "22C55E",
+ emerald: "10B981",
+ teal: "14B8A6",
+ cyan: "06B6D4",
+ sky: "0EA5E9",
+ blue: "3B82F6",
+ indigo: "6366F1",
+ violet: "8B5CF6",
+ purple: "A855F7",
+ fuchsia: "D946EF",
+ pink: "EC4899",
+ rose: "F43F5E",
+ gray: "6B7280",
+ slate: "64748B",
+ zinc: "71717A",
+ neutral: "737373",
+ stone: "78716C",
+};
+
+function toHexColor(color: string): string {
+ const lower = color.toLowerCase().replace(/^#/, "");
+ if (namedColorToHex[lower]) {
+ return namedColorToHex[lower];
+ }
+ if (/^[0-9a-f]{6}$/i.test(lower)) {
+ return lower;
+ }
+ if (/^[0-9a-f]{3}$/i.test(lower)) {
+ const [r, g, b] = lower.split("");
+ return `${r}${r}${g}${g}${b}${b}`;
+ }
+ return "6B7280";
+}
+
+async function getGiteaIssueContext(taskId: string) {
+ const externalLink = await db.query.externalLinkTable.findFirst({
+ where: eq(externalLinkTable.taskId, taskId),
+ with: {
+ integration: true,
+ },
+ });
+
+ if (!externalLink || externalLink.resourceType !== "issue") {
+ return null;
+ }
+
+ const integration = externalLink.integration;
+ if (!integration || integration.type !== "gitea") {
+ return null;
+ }
+
+ let config: GiteaConfig;
+ try {
+ config = JSON.parse(integration.config) as GiteaConfig;
+ } catch {
+ return null;
+ }
+
+ if (!config.accessToken || !config.baseUrl) {
+ return null;
+ }
+
+ const client = createGiteaClient(config);
+ const issueNumber = Number.parseInt(externalLink.externalId, 10);
+
+ return {
+ client,
+ config,
+ issueNumber,
+ };
+}
+
+export async function syncLabelToGitea(
+ taskId: string,
+ labelName: string,
+ labelColor: string,
+) {
+ const ctx = await getGiteaIssueContext(taskId);
+ if (!ctx) return;
+
+ const { client, config, issueNumber } = ctx;
+ const color = toHexColor(labelColor);
+
+ const labels = await client.listLabels(
+ config.repositoryOwner,
+ config.repositoryName,
+ );
+ let label = labels.find((l) => l.name === labelName);
+
+ if (!label) {
+ try {
+ label = await client.createLabel(
+ config.repositoryOwner,
+ config.repositoryName,
+ labelName,
+ color,
+ );
+ } catch (error) {
+ console.error(`Failed to create label "${labelName}" in Gitea:`, error);
+ return;
+ }
+ }
+
+ try {
+ const issue = await client.getIssue(
+ config.repositoryOwner,
+ config.repositoryName,
+ issueNumber,
+ );
+ const existingIds = (issue.labels ?? []).map((l) => l.id);
+ if (existingIds.includes(label.id)) {
+ return;
+ }
+ await client.addLabelsToIssue(
+ config.repositoryOwner,
+ config.repositoryName,
+ issueNumber,
+ [label.id],
+ );
+ } catch (error) {
+ console.error(`Failed to add label "${labelName}" to Gitea issue:`, error);
+ }
+}
+
+export async function removeLabelFromGitea(taskId: string, labelName: string) {
+ const ctx = await getGiteaIssueContext(taskId);
+ if (!ctx) return;
+
+ const { client, config, issueNumber } = ctx;
+
+ const labels = await client.listLabels(
+ config.repositoryOwner,
+ config.repositoryName,
+ );
+ const label = labels.find((l) => l.name === labelName);
+ if (!label) return;
+
+ try {
+ await client.removeLabelFromIssue(
+ config.repositoryOwner,
+ config.repositoryName,
+ issueNumber,
+ label.id,
+ );
+ } catch (error) {
+ console.error(
+ `Failed to remove label "${labelName}" from Gitea issue:`,
+ error,
+ );
+ }
+}
diff --git a/apps/api/src/plugins/gitea/utils/verify-signature.ts b/apps/api/src/plugins/gitea/utils/verify-signature.ts
new file mode 100644
index 000000000..aafecf106
--- /dev/null
+++ b/apps/api/src/plugins/gitea/utils/verify-signature.ts
@@ -0,0 +1,29 @@
+import { createHmac, timingSafeEqual } from "node:crypto";
+
+export function verifyGiteaSignature(
+ payload: string,
+ secret: string,
+ signatureHeader: string | undefined,
+): boolean {
+ if (!signatureHeader || !secret) {
+ return false;
+ }
+
+ let provided = signatureHeader.trim();
+ if (provided.toLowerCase().startsWith("sha256=")) {
+ provided = provided.slice(7);
+ }
+
+ const expected = createHmac("sha256", secret).update(payload).digest("hex");
+
+ try {
+ const a = Buffer.from(provided, "hex");
+ const b = Buffer.from(expected, "hex");
+ if (a.length !== b.length) {
+ return false;
+ }
+ return timingSafeEqual(a, b);
+ } catch {
+ return provided === expected;
+ }
+}
diff --git a/apps/api/src/plugins/gitea/utils/webhook-repo.ts b/apps/api/src/plugins/gitea/utils/webhook-repo.ts
new file mode 100644
index 000000000..971496b73
--- /dev/null
+++ b/apps/api/src/plugins/gitea/utils/webhook-repo.ts
@@ -0,0 +1,10 @@
+import { normalizeGiteaBaseUrl } from "../config";
+
+export function baseUrlFromRepositoryHtmlUrl(htmlUrl: string): string {
+ try {
+ const u = new URL(htmlUrl);
+ return normalizeGiteaBaseUrl(`${u.protocol}//${u.host}`);
+ } catch {
+ return "";
+ }
+}
diff --git a/apps/api/src/plugins/gitea/webhook-handler.ts b/apps/api/src/plugins/gitea/webhook-handler.ts
new file mode 100644
index 000000000..bae7fd149
--- /dev/null
+++ b/apps/api/src/plugins/gitea/webhook-handler.ts
@@ -0,0 +1,129 @@
+import { eq } from "drizzle-orm";
+import db from "../../database";
+import { integrationTable } from "../../database/schema";
+import type { GiteaConfig } from "./config";
+import { verifyGiteaSignature } from "./utils/verify-signature";
+import { handleGiteaIssueClosed } from "./webhooks/issue-closed";
+import { handleGiteaIssueCommentCreated } from "./webhooks/issue-comment-created";
+import { handleGiteaIssueEdited } from "./webhooks/issue-edited";
+import { handleGiteaIssueLabeled } from "./webhooks/issue-labeled";
+import { handleGiteaIssueOpened } from "./webhooks/issue-opened";
+import { handleGiteaLabelCreated } from "./webhooks/label-created";
+import { handleGiteaPullRequestClosed } from "./webhooks/pull-request-closed";
+import { handleGiteaPullRequestOpened } from "./webhooks/pull-request-opened";
+import { handleGiteaPush } from "./webhooks/push";
+
+export async function handleGiteaWebhookRequest(
+ integrationId: string,
+ rawBody: string,
+ signatureHeader: string | undefined,
+ eventHeader: string | undefined,
+): Promise<{ success: boolean; error?: string }> {
+ const integration = await db.query.integrationTable.findFirst({
+ where: eq(integrationTable.id, integrationId),
+ });
+
+ if (!integration || integration.type !== "gitea") {
+ return { success: false, error: "Gitea integration not found" };
+ }
+
+ let config: GiteaConfig;
+ try {
+ config = JSON.parse(integration.config) as GiteaConfig;
+ } catch {
+ return { success: false, error: "Invalid integration config" };
+ }
+
+ const secret = config.webhookSecret;
+ if (!secret) {
+ return { success: false, error: "Webhook secret not configured" };
+ }
+
+ if (!verifyGiteaSignature(rawBody, secret, signatureHeader)) {
+ return { success: false, error: "Invalid webhook signature" };
+ }
+
+ const event = eventHeader || undefined;
+
+ if (!event) {
+ return { success: false, error: "Missing event name" };
+ }
+
+ let payload: Record<string, unknown>;
+ try {
+ payload = JSON.parse(rawBody) as Record<string, unknown>;
+ } catch {
+ return { success: false, error: "Invalid JSON payload" };
+ }
+
+ try {
+ await dispatchGiteaEvent(event, payload);
+ return { success: true };
+ } catch (error) {
+ console.error("[Gitea Webhook] Handler error:", error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : "Webhook handler failed",
+ };
+ }
+}
+
+async function dispatchGiteaEvent(
+ event: string,
+ payload: Record<string, unknown>,
+) {
+ console.log(`[Gitea Webhook] Event: ${event}`);
+
+ switch (event) {
+ case "push":
+ await handleGiteaPush(payload as never);
+ return;
+ case "pull_request": {
+ const action = payload.action as string | undefined;
+ if (
+ action === "opened" ||
+ action === "reopened" ||
+ action === "ready_for_review"
+ ) {
+ await handleGiteaPullRequestOpened(payload as never);
+ } else if (action === "closed") {
+ await handleGiteaPullRequestClosed(payload as never);
+ }
+ return;
+ }
+ case "issues": {
+ const action = payload.action as string | undefined;
+ // Gitea uses "created" for new issues; GitHub-style is "opened"
+ if (action === "opened" || action === "created") {
+ await handleGiteaIssueOpened(payload as never);
+ } else if (action === "closed") {
+ await handleGiteaIssueClosed(payload as never);
+ } else if (action === "edited") {
+ await handleGiteaIssueEdited(payload as never);
+ } else if (
+ action === "labeled" ||
+ action === "unlabeled" ||
+ action === "label_updated"
+ ) {
+ await handleGiteaIssueLabeled({
+ ...payload,
+ action: action ?? "",
+ } as never);
+ }
+ return;
+ }
+ case "issue_comment": {
+ const action = payload.action as string | undefined;
+ if (action === "created") {
+ await handleGiteaIssueCommentCreated(payload as never);
+ }
+ return;
+ }
+ case "create": {
+ await handleGiteaLabelCreated(payload as never);
+ return;
+ }
+ default:
+ console.log(`[Gitea Webhook] Ignored event: ${event}`);
+ }
+}
diff --git a/apps/api/src/plugins/gitea/webhooks/issue-closed.ts b/apps/api/src/plugins/gitea/webhooks/issue-closed.ts
new file mode 100644
index 000000000..d692728aa
--- /dev/null
+++ b/apps/api/src/plugins/gitea/webhooks/issue-closed.ts
@@ -0,0 +1,87 @@
+import { and, eq } from "drizzle-orm";
+import db from "../../../database";
+import { externalLinkTable, taskTable } from "../../../database/schema";
+import { updateExternalLink } from "../../github/services/link-manager";
+import { updateTaskStatus } from "../../github/services/task-service";
+import {
+ findAllIntegrationsByGiteaRepo,
+ repoOwnerLogin,
+} from "../services/integration-lookup";
+import { resolveTargetStatus } from "../utils/resolve-column";
+import { baseUrlFromRepositoryHtmlUrl } from "../utils/webhook-repo";
+
+type IssueClosedPayload = {
+ action: string;
+ issue: {
+ number: number;
+ title: string;
+ html_url: string;
+ state: string;
+ };
+ repository: {
+ owner: { login?: string; username?: string };
+ name: string;
+ html_url: string;
+ };
+};
+
+export async function handleGiteaIssueClosed(payload: IssueClosedPayload) {
+ const { issue, repository } = payload;
+
+ const baseUrl = baseUrlFromRepositoryHtmlUrl(repository.html_url);
+ if (!baseUrl) return;
+
+ const owner = repoOwnerLogin(repository);
+ const integrations = await findAllIntegrationsByGiteaRepo(
+ baseUrl,
+ owner,
+ repository.name,
+ );
+
+ for (const integration of integrations) {
+ const externalLink = await db.query.externalLinkTable.findFirst({
+ where: and(
+ eq(externalLinkTable.integrationId, integration.id),
+ eq(externalLinkTable.resourceType, "issue"),
+ eq(externalLinkTable.externalId, issue.number.toString()),
+ ),
+ });
+
+ if (!externalLink) {
+ continue;
+ }
+
+ const task = await db.query.taskTable.findFirst({
+ where: eq(taskTable.id, externalLink.taskId),
+ });
+
+ if (!task) {
+ continue;
+ }
+
+ const existingMetadata = externalLink.metadata
+ ? JSON.parse(externalLink.metadata)
+ : {};
+
+ if (existingMetadata.createdFrom === "kaneo") {
+ continue;
+ }
+
+ const targetStatus = await resolveTargetStatus(
+ task.projectId,
+ "issue_closed",
+ "done",
+ );
+
+ await updateTaskStatus(task.id, targetStatus);
+
+ await updateExternalLink(externalLink.id, {
+ metadata: {
+ ...existingMetadata,
+ state: "closed",
+ },
+ });
+
+ return;
+ }
+}
diff --git a/apps/api/src/plugins/gitea/webhooks/issue-comment-created.ts b/apps/api/src/plugins/gitea/webhooks/issue-comment-created.ts
new file mode 100644
index 000000000..de1ba63bf
--- /dev/null
+++ b/apps/api/src/plugins/gitea/webhooks/issue-comment-created.ts
@@ -0,0 +1,80 @@
+import db from "../../../database";
+import { activityTable } from "../../../database/schema";
+import { findExternalLink } from "../../github/services/link-manager";
+import {
+ findAllIntegrationsByGiteaRepo,
+ repoOwnerLogin,
+} from "../services/integration-lookup";
+import { baseUrlFromRepositoryHtmlUrl } from "../utils/webhook-repo";
+
+type IssueCommentCreatedPayload = {
+ action: string;
+ issue: {
+ number: number;
+ };
+ comment: {
+ id: number;
+ body: string;
+ html_url: string;
+ user: {
+ login?: string;
+ username?: string;
+ avatar_url: string;
+ } | null;
+ created_at: string;
+ };
+ repository: {
+ owner: { login?: string; username?: string };
+ name: string;
+ html_url: string;
+ };
+};
+
+export async function handleGiteaIssueCommentCreated(
+ payload: IssueCommentCreatedPayload,
+) {
+ const { issue, comment, repository } = payload;
+
+ if (payload.action !== "created") {
+ return;
+ }
+
+ const username = comment.user?.login ?? comment.user?.username ?? "";
+ if (username.endsWith("[bot]")) {
+ return;
+ }
+
+ const baseUrl = baseUrlFromRepositoryHtmlUrl(repository.html_url);
+ if (!baseUrl) return;
+
+ const owner = repoOwnerLogin(repository);
+ const integrations = await findAllIntegrationsByGiteaRepo(
+ baseUrl,
+ owner,
+ repository.name,
+ );
+
+ for (const integration of integrations) {
+ const existingLink = await findExternalLink(
+ integration.id,
+ "issue",
+ issue.number.toString(),
+ );
+
+ if (!existingLink) {
+ continue;
+ }
+
+ await db.insert(activityTable).values({
+ taskId: existingLink.taskId,
+ type: "comment",
+ content: comment.body,
+ externalUserName: username || "Unknown",
+ externalUserAvatar: comment.user?.avatar_url ?? null,
+ externalSource: "gitea",
+ externalUrl: comment.html_url,
+ });
+
+ return;
+ }
+}
diff --git a/apps/api/src/plugins/gitea/webhooks/issue-edited.ts b/apps/api/src/plugins/gitea/webhooks/issue-edited.ts
new file mode 100644
index 000000000..69999f837
--- /dev/null
+++ b/apps/api/src/plugins/gitea/webhooks/issue-edited.ts
@@ -0,0 +1,156 @@
+import { eq } from "drizzle-orm";
+import db from "../../../database";
+import { taskTable } from "../../../database/schema";
+import {
+ findExternalLink,
+ updateExternalLink,
+} from "../../github/services/link-manager";
+import { formatTaskDescriptionFromIssue } from "../../github/utils/format";
+import {
+ findAllIntegrationsByGiteaRepo,
+ repoOwnerLogin,
+} from "../services/integration-lookup";
+import { baseUrlFromRepositoryHtmlUrl } from "../utils/webhook-repo";
+
+type IssueEditedPayload = {
+ action: string;
+ issue: {
+ number: number;
+ title: string;
+ body: string | null;
+ html_url: string;
+ };
+ changes?: {
+ title?: { from: string };
+ body?: { from: string };
+ };
+ repository: {
+ owner: { login?: string; username?: string };
+ name: string;
+ html_url: string;
+ };
+};
+
+export async function handleGiteaIssueEdited(payload: IssueEditedPayload) {
+ const { issue, repository, changes } = payload;
+
+ if (!changes?.title && !changes?.body) {
+ return;
+ }
+
+ const baseUrl = baseUrlFromRepositoryHtmlUrl(repository.html_url);
+ if (!baseUrl) return;
+
+ const owner = repoOwnerLogin(repository);
+ const integrations = await findAllIntegrationsByGiteaRepo(
+ baseUrl,
+ owner,
+ repository.name,
+ );
+
+ for (const integration of integrations) {
+ const externalLink = await findExternalLink(
+ integration.id,
+ "issue",
+ issue.number.toString(),
+ );
+
+ if (!externalLink) {
+ continue;
+ }
+
+ const task = await db.query.taskTable.findFirst({
+ where: eq(taskTable.id, externalLink.taskId),
+ });
+
+ if (!task) {
+ continue;
+ }
+
+ const metadata = externalLink.metadata
+ ? JSON.parse(externalLink.metadata)
+ : {};
+
+ const updateData: Record<string, unknown> = {};
+ const updatedMetadata = { ...metadata };
+
+ if (!updatedMetadata.lastSync) {
+ updatedMetadata.lastSync = {};
+ }
+
+ if (changes.title) {
+ const lastTitleSync = metadata.lastSync?.title;
+
+ let shouldUpdateTitle = true;
+
+ if (lastTitleSync) {
+ if (
+ lastTitleSync.value === issue.title &&
+ lastTitleSync.source === "kaneo"
+ ) {
+ shouldUpdateTitle = false;
+ }
+
+ const timeSinceLastSync =
+ Date.now() - new Date(lastTitleSync.timestamp).getTime();
+ if (timeSinceLastSync < 2000 && shouldUpdateTitle) {
+ shouldUpdateTitle = false;
+ }
+ }
+
+ if (shouldUpdateTitle) {
+ updateData.title = issue.title;
+ updatedMetadata.lastSync.title = {
+ timestamp: new Date().toISOString(),
+ source: "gitea",
+ value: issue.title,
+ };
+ }
+ }
+
+ if (changes.body) {
+ const lastDescSync = metadata.lastSync?.description;
+ const formattedDescription = formatTaskDescriptionFromIssue(issue.body);
+
+ let shouldUpdateDescription = true;
+
+ if (lastDescSync) {
+ if (
+ lastDescSync.value === formattedDescription &&
+ lastDescSync.source === "kaneo"
+ ) {
+ shouldUpdateDescription = false;
+ }
+
+ const timeSinceLastSync =
+ Date.now() - new Date(lastDescSync.timestamp).getTime();
+ if (timeSinceLastSync < 2000 && shouldUpdateDescription) {
+ shouldUpdateDescription = false;
+ }
+ }
+
+ if (shouldUpdateDescription) {
+ updateData.description = formattedDescription;
+ updatedMetadata.lastSync.description = {
+ timestamp: new Date().toISOString(),
+ source: "gitea",
+ value: formattedDescription,
+ };
+ }
+ }
+
+ if (Object.keys(updateData).length > 0) {
+ await db
+ .update(taskTable)
+ .set(updateData)
+ .where(eq(taskTable.id, task.id));
+
+ await updateExternalLink(externalLink.id, {
+ title: issue.title,
+ metadata: updatedMetadata,
+ });
+ }
+
+ return;
+ }
+}
diff --git a/apps/api/src/plugins/gitea/webhooks/issue-labeled.ts b/apps/api/src/plugins/gitea/webhooks/issue-labeled.ts
new file mode 100644
index 000000000..e1dcc3ffb
--- /dev/null
+++ b/apps/api/src/plugins/gitea/webhooks/issue-labeled.ts
@@ -0,0 +1,196 @@
+import { eq } from "drizzle-orm";
+import db from "../../../database";
+import { labelTable, taskTable } from "../../../database/schema";
+import { findExternalLink } from "../../github/services/link-manager";
+import { updateTaskStatus } from "../../github/services/task-service";
+import {
+ extractIssuePriority,
+ extractIssueStatus,
+} from "../../github/utils/extract-priority";
+import {
+ findAllIntegrationsByGiteaRepo,
+ repoOwnerLogin,
+} from "../services/integration-lookup";
+import { baseUrlFromRepositoryHtmlUrl } from "../utils/webhook-repo";
+
+type IssueLabeledPayload = {
+ action: string;
+ issue: {
+ number: number;
+ labels?: Array<string | { name?: string; color?: string }>;
+ };
+ label?: {
+ name: string;
+ color: string;
+ };
+ repository: {
+ owner: { login?: string; username?: string };
+ name: string;
+ html_url: string;
+ };
+};
+
+function isSystemLabelName(name: string) {
+ return name.startsWith("priority:") || name.startsWith("status:");
+}
+
+/** Non-system labels from a Gitea issue (used when action is label_updated). */
+function giteaLabelsForSync(
+ labels: IssueLabeledPayload["issue"]["labels"],
+): Array<{ name: string; color?: string }> {
+ if (!labels) return [];
+ const out: Array<{ name: string; color?: string }> = [];
+ for (const raw of labels) {
+ const name = typeof raw === "string" ? raw : raw.name;
+ if (!name || isSystemLabelName(name)) continue;
+ const color =
+ typeof raw === "object" && raw && "color" in raw ? raw.color : undefined;
+ out.push({ name, color });
+ }
+ return out;
+}
+
+async function syncGiteaLabelsToTask(
+ taskId: string,
+ workspaceId: string,
+ giteaLabels: Array<{ name: string; color?: string }>,
+) {
+ const desiredNames = new Set(giteaLabels.map((l) => l.name));
+ const existingRows = await db.query.labelTable.findMany({
+ where: eq(labelTable.taskId, taskId),
+ });
+
+ for (const g of giteaLabels) {
+ const already = existingRows.some((row) => row.name === g.name);
+ if (!already) {
+ const color = g.color ? `#${g.color.replace(/^#/, "")}` : "#6B7280";
+ await db.insert(labelTable).values({
+ name: g.name,
+ color,
+ taskId,
+ workspaceId,
+ });
+ }
+ }
+
+ for (const row of existingRows) {
+ if (!desiredNames.has(row.name) && !isSystemLabelName(row.name)) {
+ await db.delete(labelTable).where(eq(labelTable.id, row.id));
+ }
+ }
+}
+
+export async function handleGiteaIssueLabeled(payload: IssueLabeledPayload) {
+ const { issue, repository, label: addedLabel } = payload;
+
+ const baseUrl = baseUrlFromRepositoryHtmlUrl(repository.html_url);
+ if (!baseUrl) return;
+
+ const owner = repoOwnerLogin(repository);
+ const integrations = await findAllIntegrationsByGiteaRepo(
+ baseUrl,
+ owner,
+ repository.name,
+ );
+
+ for (const integration of integrations) {
+ const existingLink = await findExternalLink(
+ integration.id,
+ "issue",
+ issue.number.toString(),
+ );
+
+ if (!existingLink) {
+ continue;
+ }
+
+ const priority = extractIssuePriority(issue.labels);
+ const status = extractIssueStatus(issue.labels);
+
+ if (priority) {
+ await db
+ .update(taskTable)
+ .set({ priority })
+ .where(eq(taskTable.id, existingLink.taskId));
+ }
+
+ if (status) {
+ await updateTaskStatus(existingLink.taskId, status);
+ }
+
+ if (payload.action === "label_updated") {
+ 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 (!addedLabel) {
+ continue;
+ }
+
+ const isSystemLabel =
+ addedLabel.name.startsWith("priority:") ||
+ addedLabel.name.startsWith("status:");
+
+ if (isSystemLabel) {
+ 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({
+ 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,
+ });
+ }
+ }
+ }
+
+ 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),
+ ),
+ });
+
+ 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-opened.ts b/apps/api/src/plugins/gitea/webhooks/issue-opened.ts
new file mode 100644
index 000000000..933ca3c1e
--- /dev/null
+++ b/apps/api/src/plugins/gitea/webhooks/issue-opened.ts
@@ -0,0 +1,175 @@
+import { and, eq } from "drizzle-orm";
+import db from "../../../database";
+import { columnTable, projectTable, taskTable } from "../../../database/schema";
+import getNextTaskNumber from "../../../task/controllers/get-next-task-number";
+import {
+ createExternalLink,
+ findExternalLink,
+} from "../../github/services/link-manager";
+import {
+ extractIssuePriority,
+ extractIssueStatus,
+} from "../../github/utils/extract-priority";
+import { formatTaskDescriptionFromIssue } from "../../github/utils/format";
+import type { GiteaConfig } from "../config";
+import {
+ findAllIntegrationsByGiteaRepo,
+ repoOwnerLogin,
+} from "../services/integration-lookup";
+import { createGiteaClient } from "../utils/gitea-api";
+import { addLabelsToIssueGitea } from "../utils/labels";
+import { resolveTargetStatus } from "../utils/resolve-column";
+import { baseUrlFromRepositoryHtmlUrl } from "../utils/webhook-repo";
+
+type IssueOpenedPayload = {
+ action: string;
+ issue: {
+ number: number;
+ title: string;
+ body: string | null;
+ html_url: string;
+ labels?: Array<string | { name?: string }>;
+ user: { login?: string; username?: string } | null;
+ };
+ repository: {
+ owner: { login?: string; username?: string };
+ name: string;
+ html_url: string;
+ };
+};
+
+export async function handleGiteaIssueOpened(payload: IssueOpenedPayload) {
+ const { issue, repository } = payload;
+
+ const baseUrl = baseUrlFromRepositoryHtmlUrl(repository.html_url);
+ if (!baseUrl) {
+ return;
+ }
+
+ const owner = repoOwnerLogin(repository);
+ const integrations = await findAllIntegrationsByGiteaRepo(
+ baseUrl,
+ owner,
+ repository.name,
+ );
+
+ if (integrations.length === 0) {
+ return;
+ }
+
+ for (const integration of integrations) {
+ const config = JSON.parse(integration.config) as GiteaConfig;
+ const projectId = integration.projectId;
+
+ const priority = extractIssuePriority(issue.labels);
+ const status = extractIssueStatus(issue.labels);
+
+ const existingLink = await findExternalLink(
+ integration.id,
+ "issue",
+ issue.number.toString(),
+ );
+
+ if (existingLink) {
+ continue;
+ }
+
+ const nextTaskNumber = await getNextTaskNumber(projectId);
+
+ const resolvedStatus = await resolveTargetStatus(
+ projectId,
+ "issue_opened",
+ status || "to-do",
+ );
+
+ const targetColumn = await db.query.columnTable.findFirst({
+ where: and(
+ eq(columnTable.projectId, projectId),
+ eq(columnTable.slug, resolvedStatus),
+ ),
+ });
+
+ const taskValues: typeof taskTable.$inferInsert = {
+ projectId,
+ userId: null,
+ title: issue.title,
+ description: formatTaskDescriptionFromIssue(issue.body),
+ status: resolvedStatus,
+ columnId: targetColumn?.id ?? null,
+ priority: null,
+ number: nextTaskNumber + 1,
+ };
+
+ if (priority) taskValues.priority = priority;
+
+ const [createdTask] = await db
+ .insert(taskTable)
+ .values(taskValues)
+ .returning();
+
+ if (!createdTask) {
+ console.error("Failed to create task from Gitea issue");
+ continue;
+ }
+
+ await createExternalLink({
+ taskId: createdTask.id,
+ integrationId: integration.id,
+ resourceType: "issue",
+ externalId: issue.number.toString(),
+ url: issue.html_url,
+ title: issue.title,
+ metadata: {
+ state: "open",
+ createdFrom: "gitea",
+ author: issue.user?.login ?? issue.user?.username,
+ },
+ });
+
+ const project = await db.query.projectTable.findFirst({
+ where: eq(projectTable.id, projectId),
+ });
+
+ if (!project) {
+ continue;
+ }
+
+ const clientUrl = process.env.KANEO_CLIENT_URL || "http://localhost:5173";
+ const taskUrl = `${clientUrl}/dashboard/workspace/${project.workspaceId}/project/${projectId}/task/${createdTask.id}`;
+ const taskIdentifier = `${project.slug.toUpperCase()}-${createdTask.number}`;
+
+ try {
+ const client = createGiteaClient(config);
+
+ const existingLabels =
+ issue.labels
+ ?.map((label) => (typeof label === "string" ? label : label.name))
+ .filter(Boolean) || [];
+
+ const labelsToAdd: string[] = [];
+
+ if (priority && !existingLabels.includes(`priority:${priority}`)) {
+ labelsToAdd.push(`priority:${priority}`);
+ }
+
+ if (status && !existingLabels.includes(`status:${status}`)) {
+ labelsToAdd.push(`status:${status}`);
+ }
+
+ if (labelsToAdd.length > 0) {
+ await addLabelsToIssueGitea(config, issue.number, labelsToAdd);
+ }
+
+ if (config.commentTaskLinkOnGiteaIssue !== false) {
+ await client.createIssueComment(
+ config.repositoryOwner,
+ config.repositoryName,
+ issue.number,
+ `[${taskIdentifier}](${taskUrl})`,
+ );
+ }
+ } catch (error) {
+ console.error("Failed to process Gitea issue:", error);
+ }
+ }
+}
diff --git a/apps/api/src/plugins/gitea/webhooks/label-created.ts b/apps/api/src/plugins/gitea/webhooks/label-created.ts
new file mode 100644
index 000000000..2e846ed7f
--- /dev/null
+++ b/apps/api/src/plugins/gitea/webhooks/label-created.ts
@@ -0,0 +1,76 @@
+import { eq } from "drizzle-orm";
+import db from "../../../database";
+import { labelTable, projectTable } from "../../../database/schema";
+import {
+ findAllIntegrationsByGiteaRepo,
+ repoOwnerLogin,
+} from "../services/integration-lookup";
+import { baseUrlFromRepositoryHtmlUrl } from "../utils/webhook-repo";
+
+/** Gitea sends `create` events with ref_type `label` for new labels */
+type LabelCreatePayload = {
+ ref?: string;
+ ref_type?: string;
+ label?: {
+ name: string;
+ color: string;
+ description?: string | null;
+ };
+ repository: {
+ owner: { login?: string; username?: string };
+ name: string;
+ html_url: string;
+ };
+};
+
+export async function handleGiteaLabelCreated(payload: LabelCreatePayload) {
+ if (payload.ref_type !== "label" || !payload.label) {
+ return;
+ }
+
+ const { repository, label } = payload;
+
+ const baseUrl = baseUrlFromRepositoryHtmlUrl(repository.html_url);
+ if (!baseUrl) return;
+
+ const owner = repoOwnerLogin(repository);
+ const integrations = await findAllIntegrationsByGiteaRepo(
+ baseUrl,
+ owner,
+ repository.name,
+ );
+
+ for (const integration of integrations) {
+ if (!integration.project) {
+ continue;
+ }
+
+ const project = await db.query.projectTable.findFirst({
+ where: eq(projectTable.id, integration.project.id),
+ });
+
+ if (!project?.workspaceId) {
+ continue;
+ }
+
+ const labelExists = await db.query.labelTable.findFirst({
+ where: (table, { and, eq: e }) =>
+ and(
+ e(table.workspaceId, project.workspaceId),
+ e(table.name, label.name),
+ ),
+ });
+
+ if (labelExists) {
+ continue;
+ }
+
+ const color = label.color ? `#${label.color.replace(/^#/, "")}` : "#6B7280";
+
+ await db.insert(labelTable).values({
+ name: label.name,
+ color,
+ workspaceId: project.workspaceId,
+ });
+ }
+}
diff --git a/apps/api/src/plugins/gitea/webhooks/pull-request-closed.ts b/apps/api/src/plugins/gitea/webhooks/pull-request-closed.ts
new file mode 100644
index 000000000..f76652ff4
--- /dev/null
+++ b/apps/api/src/plugins/gitea/webhooks/pull-request-closed.ts
@@ -0,0 +1,110 @@
+import { and, eq } from "drizzle-orm";
+import db from "../../../database";
+import { externalLinkTable } from "../../../database/schema";
+import { updateExternalLink } from "../../github/services/link-manager";
+import {
+ findTaskById,
+ updateTaskStatus,
+} from "../../github/services/task-service";
+import type { GiteaConfig } from "../config";
+import {
+ findAllIntegrationsByGiteaRepo,
+ repoOwnerLogin,
+} from "../services/integration-lookup";
+import { resolveTargetStatus } from "../utils/resolve-column";
+import { baseUrlFromRepositoryHtmlUrl } from "../utils/webhook-repo";
+
+type PRClosedPayload = {
+ action: string;
+ pull_request: {
+ number: number;
+ title: string;
+ html_url: string;
+ state: string;
+ merged: boolean;
+ merged_at: string | null;
+ head: {
+ ref: string;
+ };
+ };
+ repository: {
+ owner: { login?: string; username?: string };
+ name: string;
+ html_url: string;
+ };
+};
+
+export async function handleGiteaPullRequestClosed(payload: PRClosedPayload) {
+ const { pull_request, repository } = payload;
+
+ const baseUrl = baseUrlFromRepositoryHtmlUrl(repository.html_url);
+ if (!baseUrl) return;
+
+ const owner = repoOwnerLogin(repository);
+ const integrations = await findAllIntegrationsByGiteaRepo(
+ baseUrl,
+ owner,
+ repository.name,
+ );
+
+ for (const integration of integrations) {
+ const config = JSON.parse(integration.config) as GiteaConfig;
+
+ const externalLink = await db.query.externalLinkTable.findFirst({
+ where: and(
+ eq(externalLinkTable.integrationId, integration.id),
+ eq(externalLinkTable.resourceType, "pull_request"),
+ eq(externalLinkTable.externalId, pull_request.number.toString()),
+ ),
+ });
+
+ if (!externalLink) {
+ continue;
+ }
+
+ const task = await findTaskById(externalLink.taskId);
+
+ if (!task) {
+ continue;
+ }
+
+ const existingMetadata = externalLink.metadata
+ ? JSON.parse(externalLink.metadata)
+ : {};
+
+ await updateExternalLink(externalLink.id, {
+ metadata: {
+ ...existingMetadata,
+ state: "closed",
+ merged: pull_request.merged,
+ mergedAt: pull_request.merged_at,
+ },
+ });
+
+ if (pull_request.merged) {
+ const allTaskPRs = await db.query.externalLinkTable.findMany({
+ where: and(
+ eq(externalLinkTable.taskId, task.id),
+ eq(externalLinkTable.resourceType, "pull_request"),
+ ),
+ });
+
+ const hasOpenPRs = allTaskPRs.some((pr) => {
+ if (pr.id === externalLink.id) return false;
+ const metadata = pr.metadata ? JSON.parse(pr.metadata) : {};
+ return metadata.state === "open";
+ });
+
+ if (!hasOpenPRs) {
+ const targetStatus = await resolveTargetStatus(
+ integration.projectId,
+ "pr_merged",
+ config.statusTransitions?.onPRMerge || "done",
+ );
+ await updateTaskStatus(task.id, targetStatus);
+ }
+ }
+
+ return;
+ }
+}
diff --git a/apps/api/src/plugins/gitea/webhooks/pull-request-opened.ts b/apps/api/src/plugins/gitea/webhooks/pull-request-opened.ts
new file mode 100644
index 000000000..cb1c557bc
--- /dev/null
+++ b/apps/api/src/plugins/gitea/webhooks/pull-request-opened.ts
@@ -0,0 +1,121 @@
+import {
+ createExternalLink,
+ findExternalLink,
+} from "../../github/services/link-manager";
+import {
+ findTaskByNumber,
+ isTaskInFinalState,
+ updateTaskStatus,
+} from "../../github/services/task-service";
+import type { GiteaConfig } from "../config";
+import {
+ findAllIntegrationsByGiteaRepo,
+ repoOwnerLogin,
+} from "../services/integration-lookup";
+import { extractTaskNumberGitea } from "../utils/branch-matcher";
+import { resolveTargetStatus } from "../utils/resolve-column";
+import { baseUrlFromRepositoryHtmlUrl } from "../utils/webhook-repo";
+
+type PROpenedPayload = {
+ action: string;
+ pull_request: {
+ number: number;
+ title: string;
+ body: string | null;
+ html_url: string;
+ state: string;
+ draft?: boolean;
+ merged?: boolean;
+ head: {
+ ref: string;
+ };
+ user: { login?: string; username?: string } | null;
+ };
+ repository: {
+ owner: { login?: string; username?: string };
+ name: string;
+ html_url: string;
+ };
+};
+
+export async function handleGiteaPullRequestOpened(payload: PROpenedPayload) {
+ const { pull_request, repository } = payload;
+
+ const baseUrl = baseUrlFromRepositoryHtmlUrl(repository.html_url);
+ if (!baseUrl) return;
+
+ const owner = repoOwnerLogin(repository);
+ const integrations = await findAllIntegrationsByGiteaRepo(
+ baseUrl,
+ owner,
+ repository.name,
+ );
+
+ for (const integration of integrations) {
+ if (!integration.project) {
+ continue;
+ }
+
+ const config = JSON.parse(integration.config) as GiteaConfig;
+ const projectSlug = integration.project.slug;
+ const branchName = pull_request.head.ref;
+
+ const taskNumber = extractTaskNumberGitea(
+ branchName,
+ pull_request.title,
+ pull_request.body ?? undefined,
+ config,
+ projectSlug,
+ );
+
+ if (!taskNumber) {
+ continue;
+ }
+
+ const task = await findTaskByNumber(integration.projectId, taskNumber);
+
+ if (!task) {
+ continue;
+ }
+
+ const existingLink = await findExternalLink(
+ integration.id,
+ "pull_request",
+ pull_request.number.toString(),
+ );
+
+ if (existingLink) {
+ continue;
+ }
+
+ await createExternalLink({
+ taskId: task.id,
+ integrationId: integration.id,
+ resourceType: "pull_request",
+ externalId: pull_request.number.toString(),
+ url: pull_request.html_url,
+ title: pull_request.title,
+ metadata: {
+ state: pull_request.state,
+ draft: pull_request.draft,
+ merged: pull_request.merged,
+ branch: branchName,
+ author: pull_request.user?.login ?? pull_request.user?.username,
+ },
+ });
+
+ const targetStatus = await resolveTargetStatus(
+ integration.projectId,
+ "pr_opened",
+ config.statusTransitions?.onPROpen || "in-review",
+ );
+
+ const isTaskFinal = await isTaskInFinalState(task);
+
+ if (task.status !== targetStatus && !isTaskFinal) {
+ await updateTaskStatus(task.id, targetStatus);
+ }
+
+ return;
+ }
+}
diff --git a/apps/api/src/plugins/gitea/webhooks/push.ts b/apps/api/src/plugins/gitea/webhooks/push.ts
new file mode 100644
index 000000000..eda61e38f
--- /dev/null
+++ b/apps/api/src/plugins/gitea/webhooks/push.ts
@@ -0,0 +1,131 @@
+import { createOrUpdateExternalLink } from "../../github/services/link-manager";
+import {
+ findTaskByNumber,
+ isTaskInFinalState,
+ updateTaskStatus,
+} from "../../github/services/task-service";
+import type { GiteaConfig } from "../config";
+import {
+ findAllIntegrationsByGiteaRepo,
+ repoOwnerLogin,
+} from "../services/integration-lookup";
+import { extractTaskNumberFromBranchGitea } from "../utils/branch-matcher";
+import { resolveTargetStatus } from "../utils/resolve-column";
+
+type PushPayload = {
+ ref: string;
+ head_commit?: {
+ id: string;
+ message: string;
+ author?: { name: string };
+ timestamp: string;
+ };
+ commits?: Array<{
+ id: string;
+ message: string;
+ author?: { name: string; username?: string };
+ timestamp?: string;
+ }>;
+ repository: {
+ owner: { login?: string; username?: string };
+ name: string;
+ html_url: string;
+ };
+};
+
+const PROTECTED_BRANCHES = [
+ "main",
+ "master",
+ "develop",
+ "staging",
+ "production",
+];
+
+export async function handleGiteaPush(payload: PushPayload) {
+ const { ref, repository } = payload;
+
+ const branchName = ref.replace("refs/heads/", "");
+ console.log(`[Gitea Push] Processing branch: ${branchName}`);
+
+ if (PROTECTED_BRANCHES.includes(branchName)) {
+ console.log(`[Gitea Push] Skipping protected branch: ${branchName}`);
+ return;
+ }
+
+ const baseUrl = new URL(repository.html_url);
+ const origin = `${baseUrl.protocol}//${baseUrl.host}`;
+ const owner = repoOwnerLogin(repository);
+ const integrations = await findAllIntegrationsByGiteaRepo(
+ origin,
+ owner,
+ repository.name,
+ );
+
+ if (integrations.length === 0) {
+ return;
+ }
+
+ const headCommit =
+ payload.head_commit ?? payload.commits?.[payload.commits.length - 1];
+
+ for (const integration of integrations) {
+ if (!integration.project) {
+ continue;
+ }
+
+ const config = JSON.parse(integration.config) as GiteaConfig;
+ const projectSlug = integration.project.slug;
+
+ const taskNumber = extractTaskNumberFromBranchGitea(
+ branchName,
+ config,
+ projectSlug,
+ );
+
+ if (!taskNumber) {
+ continue;
+ }
+
+ const task = await findTaskByNumber(integration.projectId, taskNumber);
+
+ if (!task) {
+ continue;
+ }
+
+ const treeUrl = `${repository.html_url}/src/branch/${branchName}`;
+
+ await createOrUpdateExternalLink({
+ taskId: task.id,
+ integrationId: integration.id,
+ resourceType: "branch",
+ externalId: branchName,
+ url: treeUrl,
+ title: branchName,
+ metadata: {
+ lastCommit: headCommit
+ ? {
+ sha: headCommit.id,
+ message: headCommit.message,
+ author: headCommit.author?.name,
+ timestamp:
+ "timestamp" in headCommit ? headCommit.timestamp : undefined,
+ }
+ : null,
+ },
+ });
+
+ const targetStatus = await resolveTargetStatus(
+ integration.projectId,
+ "branch_push",
+ config.statusTransitions?.onBranchPush || "in-progress",
+ );
+
+ const isTaskFinal = await isTaskInFinalState(task);
+
+ if (task.status !== targetStatus && !isTaskFinal) {
+ await updateTaskStatus(task.id, targetStatus);
+ }
+
+ return;
+ }
+}
diff --git a/apps/api/src/plugins/index.ts b/apps/api/src/plugins/index.ts
index 195b94ddf..f91b156b9 100644
--- a/apps/api/src/plugins/index.ts
+++ b/apps/api/src/plugins/index.ts
@@ -1,5 +1,6 @@
import { discordPlugin } from "./discord";
import { genericWebhookPlugin } from "./generic-webhook";
+import { giteaPlugin } from "./gitea";
import { githubPlugin, initializeGitHubPlugin } from "./github";
import { initializeEventSubscriptions, registerPlugin } from "./registry";
import { slackPlugin } from "./slack";
@@ -8,6 +9,7 @@ export function initializePlugins() {
console.log("Initializing plugins...");
registerPlugin(githubPlugin);
+ registerPlugin(giteaPlugin);
registerPlugin(slackPlugin);
registerPlugin(discordPlugin);
registerPlugin(genericWebhookPlugin);