⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
fix(gitea): prevent outbound comment echoes (#1834)
Tin Sever61c317559618
diff --git a/apps/api/src/gitea-integration/controllers/import-gitea-issues.ts b/apps/api/src/gitea-integration/controllers/import-gitea-issues.tsindex 68da790ef..e055011a9 100644--- a/apps/api/src/gitea-integration/controllers/import-gitea-issues.ts+++ b/apps/api/src/gitea-integration/controllers/import-gitea-issues.ts@@ -10,6 +10,7 @@ import {} from "../../database/schema";import { publishEvent } from "../../events";import type { GiteaConfig } from "../../plugins/gitea/config";+import { isKaneoComment } from "../../plugins/gitea/utils/comment-origin";import {createGiteaClient,type GiteaIssue,@@ -402,7 +403,7 @@ async function importCommentsForTask(for (const comment of allComments) {const username = comment.user?.login ?? comment.user?.username ?? "";- if (username.endsWith("[bot]")) {+ if (username.endsWith("[bot]") || isKaneoComment(comment.body)) {continue;}diff --git a/apps/api/src/plugins/gitea/events/task-comment-created.ts b/apps/api/src/plugins/gitea/events/task-comment-created.tsindex 01dde456f..b5cf42f82 100644--- a/apps/api/src/plugins/gitea/events/task-comment-created.ts+++ b/apps/api/src/plugins/gitea/events/task-comment-created.ts@@ -1,6 +1,7 @@import { findExternalLinkByTaskAndType } from "../../github/services/link-manager";import type { PluginContext, TaskCommentCreatedEvent } from "../../types";import type { GiteaConfig } from "../config";+import { markKaneoComment } from "../utils/comment-origin";import { createGiteaClient } from "../utils/gitea-api";export async function handleTaskCommentCreated(@@ -52,7 +53,7 @@ export async function handleTaskCommentCreated(repositoryOwner,repositoryName,issueNumber,- event.comment,+ markKaneoComment(event.comment),);} catch (error) {console.error("Failed to create Gitea comment:", error);diff --git a/apps/api/src/plugins/gitea/utils/comment-origin.ts b/apps/api/src/plugins/gitea/utils/comment-origin.tsnew file mode 100644index 000000000..e7131cb81--- /dev/null+++ b/apps/api/src/plugins/gitea/utils/comment-origin.ts@@ -0,0 +1,11 @@+// Persist the origin in Gitea so delayed webhooks and later imports also skip echoes.+const KANEO_COMMENT_PREFIX = "<!-- kaneo:comment -->\n\n";++export function markKaneoComment(body: string): string {+ // Keep the marker outside user-controlled Markdown, including unclosed code fences.+ return `${KANEO_COMMENT_PREFIX}${body}`;+}++export function isKaneoComment(body: string): boolean {+ return body.startsWith(KANEO_COMMENT_PREFIX);+}diff --git a/apps/api/src/plugins/gitea/webhooks/issue-comment-created.ts b/apps/api/src/plugins/gitea/webhooks/issue-comment-created.tsindex b52a041e9..b6fd060e5 100644--- a/apps/api/src/plugins/gitea/webhooks/issue-comment-created.ts+++ b/apps/api/src/plugins/gitea/webhooks/issue-comment-created.ts@@ -5,6 +5,7 @@ import {findAllIntegrationsByGiteaRepo,repoOwnerLogin,} from "../services/integration-lookup";+import { isKaneoComment } from "../utils/comment-origin";import { baseUrlFromRepositoryHtmlUrl } from "../utils/webhook-repo";type IssueCommentCreatedPayload = {@@ -36,7 +37,7 @@ export async function handleGiteaIssueCommentCreated() {const { issue, comment, repository } = payload;- if (payload.action !== "created") {+ if (payload.action !== "created" || isKaneoComment(comment.body)) {return;}diff --git a/apps/api/src/plugins/gitea/webhooks/issue-opened.ts b/apps/api/src/plugins/gitea/webhooks/issue-opened.tsindex dd1c04b73..f6774c26e 100644--- a/apps/api/src/plugins/gitea/webhooks/issue-opened.ts+++ b/apps/api/src/plugins/gitea/webhooks/issue-opened.ts@@ -17,6 +17,7 @@ import {findAllIntegrationsByGiteaRepo,repoOwnerLogin,} from "../services/integration-lookup";+import { markKaneoComment } from "../utils/comment-origin";import { createGiteaClient } from "../utils/gitea-api";import { addLabelsToIssueGitea } from "../utils/labels";import { resolveTargetStatus } from "../utils/resolve-column";@@ -190,7 +191,7 @@ export async function handleGiteaIssueOpened(config.repositoryOwner,config.repositoryName,issue.number,- `[${taskIdentifier}](${taskUrl})`,+ markKaneoComment(`[${taskIdentifier}](${taskUrl})`),);}} catch (error) {diff --git a/tests/api/plugins/gitea/comment-sync.test.ts b/tests/api/plugins/gitea/comment-sync.test.tsnew file mode 100644index 000000000..d20475fb1--- /dev/null+++ b/tests/api/plugins/gitea/comment-sync.test.ts@@ -0,0 +1,167 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { importGiteaIssues } from "../../../../apps/api/src/gitea-integration/controllers/import-gitea-issues";+import { handleTaskCommentCreated } from "../../../../apps/api/src/plugins/gitea/events/task-comment-created";+import { handleGiteaIssueCommentCreated } from "../../../../apps/api/src/plugins/gitea/webhooks/issue-comment-created";++const mocks = vi.hoisted(() => ({+ values: vi.fn(() => ({ onConflictDoNothing: vi.fn() })),+ createIssueComment: vi.fn(),+ listIssueComments: vi.fn(),+}));+const config = {+ baseUrl: "https://gitea.example.com",+ accessToken: "test-token",+ repositoryOwner: "owner",+ repositoryName: "repo",+};++vi.mock("../../../../apps/api/src/database", () => ({+ default: {+ insert: () => ({ values: mocks.values }),+ update: () => ({ set: () => ({ where: vi.fn() }) }),+ delete: () => ({ where: vi.fn() }),+ query: {+ projectTable: { findFirst: async () => ({ workspaceId: "workspace-1" }) },+ integrationTable: {+ findFirst: async () => ({+ id: "integration-1",+ isActive: true,+ config: JSON.stringify(config),+ }),+ },+ labelTable: { findMany: async () => [] },+ },+ },+}));+vi.mock("../../../../apps/api/src/events", () => ({ publishEvent: vi.fn() }));+vi.mock(+ "../../../../apps/api/src/plugins/github/services/link-manager",+ () => ({+ findExternalLinkByTaskAndType: async () => ({ externalId: "42" }),+ findExternalLink: async () => ({ taskId: "task-1" }),+ createExternalLink: vi.fn(),+ }),+);+vi.mock(+ "../../../../apps/api/src/plugins/gitea/services/integration-lookup",+ () => ({+ findAllIntegrationsByGiteaRepo: async () => [{ id: "integration-1" }],+ repoOwnerLogin: () => "owner",+ }),+);+vi.mock("../../../../apps/api/src/plugins/gitea/utils/gitea-api", () => ({+ createGiteaClient: () => ({+ createIssueComment: mocks.createIssueComment,+ listIssueComments: mocks.listIssueComments,+ listIssues: async () => [+ { number: 42, title: "Issue", body: "", labels: [] },+ ],+ listPulls: async () => [],+ }),+}));++function comment(body: string, id = 1) {+ return {+ id,+ body,+ html_url: `https://gitea.example.com/owner/repo/issues/42#issuecomment-${id}`,+ user: { login: "regular-user", avatar_url: "" },+ created_at: "2026-09-27T00:00:00Z",+ };+}++async function deliverWebhook(body: string) {+ await handleGiteaIssueCommentCreated({+ action: "created",+ issue: { number: 42 },+ comment: comment(body),+ repository: {+ owner: { login: "owner" },+ name: "repo",+ html_url: "https://gitea.example.com/owner/repo",+ },+ });+}++async function outboundBody(comment = "A comment from Kaneo") {+ await handleTaskCommentCreated(+ {+ taskId: "task-1",+ projectId: "project-1",+ userId: "user-1",+ comment,+ },+ { integrationId: "integration-1", projectId: "project-1", config },+ );+ expect(mocks.createIssueComment).toHaveBeenCalledWith(+ "owner",+ "repo",+ 42,+ expect.stringContaining(comment),+ );+ return mocks.createIssueComment.mock.calls[0][3] as string;+}++beforeEach(() => vi.clearAllMocks());++describe("Gitea comment sync", () => {+ it("does not reimport outbound comments through repeated personal-token webhooks", async () => {+ const body = await outboundBody();+ await deliverWebhook(body);+ await deliverWebhook(`${body}\n`);+ expect(mocks.values).not.toHaveBeenCalled();+ });++ it("puts the hidden marker before unclosed Markdown code fences", async () => {+ const body = await outboundBody("```ts\nconst example = 1;");+ expect(body).toBe("<!-- kaneo:comment -->\n\n```ts\nconst example = 1;");+ await deliverWebhook(body);+ expect(mocks.values).not.toHaveBeenCalled();+ });++ it.each([+ "Discussing the marker: <!-- kaneo:comment -->",+ "> <!-- kaneo:comment -->\n\nQuoted marker",+ "```html\n<!-- kaneo:comment -->\n```",+ ])(+ "imports native comments discussing or quoting the marker: %s",+ async (body) => {+ await deliverWebhook(body);+ expect(mocks.values).toHaveBeenCalledWith(+ expect.objectContaining({ content: body }),+ );+ mocks.values.mockClear();+ mocks.listIssueComments.mockResolvedValue([comment(body)]);+ await importGiteaIssues("project-1");+ expect(mocks.values).toHaveBeenCalledWith(+ expect.objectContaining({ content: body }),+ );+ },+ );++ it("still imports native Gitea comments from the same personal-token user", async () => {+ await deliverWebhook("A comment written in Gitea");+ expect(mocks.values).toHaveBeenCalledWith(+ expect.objectContaining({+ content: "A comment written in Gitea",+ externalUserName: "regular-user",+ externalSource: "gitea",+ }),+ );+ });++ it("skips outbound comments during bulk import while preserving native comments", async () => {+ const body = await outboundBody();+ mocks.listIssueComments.mockResolvedValue([+ comment(`${body}\nAn edit appended in Gitea`),+ comment("Native comment", 2),+ ]);+ const result = await importGiteaIssues("project-1");+ expect(result.errors).toBeUndefined();+ expect(result.updated).toBe(1);+ expect(mocks.values).toHaveBeenCalledTimes(1);+ expect(mocks.values).toHaveBeenCalledWith(+ expect.objectContaining({ content: "Native comment" }),+ );+ });+});diff --git a/tests/api/plugins/gitea/webhooks/issue-opened.test.ts b/tests/api/plugins/gitea/webhooks/issue-opened.test.tsindex 94201c478..fc05e31ff 100644--- a/tests/api/plugins/gitea/webhooks/issue-opened.test.ts+++ b/tests/api/plugins/gitea/webhooks/issue-opened.test.ts@@ -1,4 +1,5 @@import { beforeEach, describe, expect, it, vi } from "vitest";+import { handleGiteaIssueCommentCreated } from "../../../../../apps/api/src/plugins/gitea/webhooks/issue-comment-created";import { handleGiteaIssueOpened } from "../../../../../apps/api/src/plugins/gitea/webhooks/issue-opened";const mocks = vi.hoisted(() => {@@ -130,6 +131,38 @@ beforeEach(() => {});describe("handleGiteaIssueOpened", () => {+ it("marks automatic task links and skips their comment webhook", async () => {+ const createIssueComment = vi.fn();+ mocks.projectFindFirst.mockResolvedValue({+ workspaceId: "workspace-1",+ slug: "test",+ });+ mocks.createGiteaClient.mockReturnValue({ createIssueComment });+ const payload = issueOpenedPayload([]);+ await handleGiteaIssueOpened(payload);+ expect(createIssueComment).toHaveBeenCalledWith(+ "usekaneo",+ "kaneo",+ 42,+ expect.stringMatching(/^<!-- kaneo:comment -->\n\n\[TEST-7\]\(/),+ );+ const body = createIssueComment.mock.calls[0][3] as string;+ mocks.insertedValues.length = 0;+ mocks.findExternalLink.mockResolvedValue({ taskId: "task-1" });+ await handleGiteaIssueCommentCreated({+ ...payload,+ action: "created",+ comment: {+ id: 1,+ body,+ html_url: `${payload.issue.html_url}#issuecomment-1`,+ user: { login: "regular-user", avatar_url: "" },+ created_at: "2026-09-27T00:00:00Z",+ },+ });+ expect(mocks.insertedValues).toHaveLength(0);+ });+it("persists a valid default priority when the issue has no priority: label", async () => {await handleGiteaIssueOpened(issueOpenedPayload(["type:bug"]));