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: add task title and description change events to GitHub integration

Andrej Acevski60ecffdc93ac
diff --git a/apps/api/src/plugins/github/events/task-description-changed.ts b/apps/api/src/plugins/github/events/task-description-changed.ts
new file mode 100644
index 000000000..d50d2e103
--- /dev/null
+++ b/apps/api/src/plugins/github/events/task-description-changed.ts
@@ -0,0 +1,101 @@
+import type { PluginContext, TaskDescriptionChangedEvent } from "../../types";
+import type { GitHubConfig } from "../config";
+import {
+ findExternalLinksByTask,
+ updateExternalLink,
+} from "../services/link-manager";
+import { formatIssueBody } from "../utils/format";
+import { getGithubApp, getInstallationIdForRepo } from "../utils/github-app";
+
+export async function handleTaskDescriptionChanged(
+ event: TaskDescriptionChangedEvent,
+ context: PluginContext,
+): Promise<void> {
+ const githubApp = getGithubApp();
+ if (!githubApp) {
+ return;
+ }
+
+ const config = context.config as GitHubConfig;
+ 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) : {};
+
+ // LOOP PREVENTION: Check if this update originated from GitHub
+ const lastDescSync = metadata.lastSync?.description;
+ const newDescNormalized = event.newDescription || "";
+
+ if (lastDescSync) {
+ // Skip if value unchanged and last sync was from GitHub
+ if (
+ lastDescSync.value === newDescNormalized &&
+ lastDescSync.source === "github"
+ ) {
+ console.log("Skipping description sync - already synced from GitHub");
+ return;
+ }
+
+ // Skip if recent sync (within 2 seconds) to prevent rapid loops
+ const timeSinceLastSync =
+ Date.now() - new Date(lastDescSync.timestamp).getTime();
+ if (timeSinceLastSync < 2000) {
+ console.log(
+ `Skipping description sync - recent sync detected (${timeSinceLastSync}ms ago)`,
+ );
+ return;
+ }
+ }
+
+ let installationId = config.installationId;
+ if (!installationId) {
+ installationId = await getInstallationIdForRepo(
+ repositoryOwner,
+ repositoryName,
+ );
+ }
+
+ const octokit = await githubApp.getInstallationOctokit(installationId);
+ const issueNumber = Number.parseInt(issueLink.externalId, 10);
+
+ // Format description with task ID footer
+ const formattedBody = formatIssueBody(event.newDescription, event.taskId);
+
+ await octokit.rest.issues.update({
+ owner: repositoryOwner,
+ repo: repositoryName,
+ issue_number: issueNumber,
+ body: formattedBody,
+ });
+
+ // Update metadata to track this sync
+ await updateExternalLink(issueLink.id, {
+ metadata: {
+ ...metadata,
+ lastSync: {
+ ...metadata.lastSync,
+ description: {
+ timestamp: new Date().toISOString(),
+ source: "kaneo",
+ value: newDescNormalized,
+ },
+ },
+ },
+ });
+
+ console.log(`Synced task description to GitHub issue #${issueNumber}`);
+ } catch (error) {
+ console.error("Failed to update GitHub issue description:", error);
+ }
+}
diff --git a/apps/api/src/plugins/github/events/task-title-changed.ts b/apps/api/src/plugins/github/events/task-title-changed.ts
new file mode 100644
index 000000000..13f36ac6f
--- /dev/null
+++ b/apps/api/src/plugins/github/events/task-title-changed.ts
@@ -0,0 +1,96 @@
+import type { PluginContext, TaskTitleChangedEvent } from "../../types";
+import type { GitHubConfig } from "../config";
+import {
+ findExternalLinksByTask,
+ updateExternalLink,
+} from "../services/link-manager";
+import { getGithubApp, getInstallationIdForRepo } from "../utils/github-app";
+
+export async function handleTaskTitleChanged(
+ event: TaskTitleChangedEvent,
+ context: PluginContext,
+): Promise<void> {
+ const githubApp = getGithubApp();
+ if (!githubApp) {
+ return;
+ }
+
+ const config = context.config as GitHubConfig;
+ 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) : {};
+
+ // LOOP PREVENTION: Check if this update originated from GitHub
+ const lastTitleSync = metadata.lastSync?.title;
+ if (lastTitleSync) {
+ // Skip if value unchanged and last sync was from GitHub
+ if (
+ lastTitleSync.value === event.newTitle &&
+ lastTitleSync.source === "github"
+ ) {
+ console.log("Skipping title sync - already synced from GitHub");
+ return;
+ }
+
+ // Skip if recent sync (within 2 seconds) to prevent rapid loops
+ const timeSinceLastSync =
+ Date.now() - new Date(lastTitleSync.timestamp).getTime();
+ if (timeSinceLastSync < 2000) {
+ console.log(
+ `Skipping title sync - recent sync detected (${timeSinceLastSync}ms ago)`,
+ );
+ return;
+ }
+ }
+
+ let installationId = config.installationId;
+ if (!installationId) {
+ installationId = await getInstallationIdForRepo(
+ repositoryOwner,
+ repositoryName,
+ );
+ }
+
+ const octokit = await githubApp.getInstallationOctokit(installationId);
+ const issueNumber = Number.parseInt(issueLink.externalId, 10);
+
+ await octokit.rest.issues.update({
+ owner: repositoryOwner,
+ repo: repositoryName,
+ issue_number: issueNumber,
+ title: event.newTitle,
+ });
+
+ // Update metadata to track this sync
+ 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 GitHub issue #${issueNumber}`);
+ } catch (error) {
+ console.error("Failed to update GitHub issue title:", error);
+ }
+}
diff --git a/apps/api/src/plugins/github/index.ts b/apps/api/src/plugins/github/index.ts
index 474c3d57d..b2afbfe16 100644
--- a/apps/api/src/plugins/github/index.ts
+++ b/apps/api/src/plugins/github/index.ts
@@ -1,8 +1,10 @@
import type { IntegrationPlugin } from "../types";
import { validateGitHubConfig } from "./config";
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";
import { setupWebhookHandlers } from "./webhook-handler";
export const githubPlugin: IntegrationPlugin = {
@@ -11,6 +13,8 @@ export const githubPlugin: IntegrationPlugin = {
onTaskCreated: handleTaskCreated,
onTaskStatusChanged: handleTaskStatusChanged,
onTaskPriorityChanged: handleTaskPriorityChanged,
+ onTaskTitleChanged: handleTaskTitleChanged,
+ onTaskDescriptionChanged: handleTaskDescriptionChanged,
validateConfig: validateGitHubConfig,
};
diff --git a/apps/api/src/plugins/github/webhook-handler.ts b/apps/api/src/plugins/github/webhook-handler.ts
index 1ed485ece..f608485e4 100644
--- a/apps/api/src/plugins/github/webhook-handler.ts
+++ b/apps/api/src/plugins/github/webhook-handler.ts
@@ -1,6 +1,7 @@
import { getGithubApp } from "./utils/github-app";
import { handleIssueClosed } from "./webhooks/issue-closed";
import { handleIssueCommentCreated } from "./webhooks/issue-comment-created";
+import { handleIssueEdited } from "./webhooks/issue-edited";
import { handleIssueLabeled } from "./webhooks/issue-labeled";
import { handleIssueOpened } from "./webhooks/issue-opened";
import { handleLabelCreated } from "./webhooks/label-created";
@@ -72,6 +73,10 @@ export function setupWebhookHandlers() {
);
});
+ githubApp.webhooks.on("issues.edited", async ({ payload }) => {
+ await handleIssueEdited(payload as Parameters<typeof handleIssueEdited>[0]);
+ });
+
githubApp.webhooks.on("push", async ({ payload }) => {
await handlePush(payload as Parameters<typeof handlePush>[0]);
});
diff --git a/apps/api/src/plugins/github/webhooks/issue-edited.ts b/apps/api/src/plugins/github/webhooks/issue-edited.ts
new file mode 100644
index 000000000..c90b502ed
--- /dev/null
+++ b/apps/api/src/plugins/github/webhooks/issue-edited.ts
@@ -0,0 +1,184 @@
+import { eq } from "drizzle-orm";
+import db from "../../../database";
+import { taskTable } from "../../../database/schema";
+import { findExternalLink, updateExternalLink } from "../services/link-manager";
+import { findIntegrationByRepo } from "../services/task-service";
+import { formatTaskDescriptionFromIssue } from "../utils/format";
+
+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 };
+ name: string;
+ full_name: string;
+ };
+};
+
+export async function handleIssueEdited(payload: IssueEditedPayload) {
+ const { issue, repository, changes } = payload;
+
+ // Early exit if no relevant changes
+ if (!changes?.title && !changes?.body) {
+ console.log(
+ `Issue #${issue.number} edited but no title/body changes detected`,
+ );
+ return;
+ }
+
+ const integration = await findIntegrationByRepo(
+ repository.owner.login,
+ repository.name,
+ );
+
+ if (!integration) {
+ console.log(
+ `No integration found for ${repository.owner.login}/${repository.name}`,
+ );
+ return;
+ }
+
+ const externalLink = await findExternalLink(
+ integration.id,
+ "issue",
+ issue.number.toString(),
+ );
+
+ if (!externalLink) {
+ console.log(`No linked task found for issue #${issue.number}`);
+ return;
+ }
+
+ const task = await db.query.taskTable.findFirst({
+ where: eq(taskTable.id, externalLink.taskId),
+ });
+
+ if (!task) {
+ console.error(`Task ${externalLink.taskId} not found`);
+ return;
+ }
+
+ const metadata = externalLink.metadata
+ ? JSON.parse(externalLink.metadata)
+ : {};
+
+ const updateData: Record<string, unknown> = {};
+ const updatedMetadata = { ...metadata };
+
+ // Initialize lastSync if not present
+ if (!updatedMetadata.lastSync) {
+ updatedMetadata.lastSync = {};
+ }
+
+ // Handle title change
+ if (changes.title) {
+ const lastTitleSync = metadata.lastSync?.title;
+
+ // LOOP PREVENTION
+ let shouldUpdateTitle = true;
+
+ if (lastTitleSync) {
+ // Skip if this value was just synced from Kaneo
+ if (
+ lastTitleSync.value === issue.title &&
+ lastTitleSync.source === "kaneo"
+ ) {
+ console.log("Skipping title update - already synced from Kaneo");
+ shouldUpdateTitle = false;
+ }
+
+ // Skip if recent sync (within 2 seconds)
+ const timeSinceLastSync =
+ Date.now() - new Date(lastTitleSync.timestamp).getTime();
+ if (timeSinceLastSync < 2000 && shouldUpdateTitle) {
+ console.log(
+ `Skipping title update - recent sync detected (${timeSinceLastSync}ms ago)`,
+ );
+ shouldUpdateTitle = false;
+ }
+ }
+
+ if (shouldUpdateTitle) {
+ updateData.title = issue.title;
+ updatedMetadata.lastSync.title = {
+ timestamp: new Date().toISOString(),
+ source: "github",
+ value: issue.title,
+ };
+ console.log(
+ `Updating task title from GitHub: "${changes.title.from}" → "${issue.title}"`,
+ );
+ }
+ }
+
+ // Handle description change
+ if (changes.body) {
+ const lastDescSync = metadata.lastSync?.description;
+ const formattedDescription = formatTaskDescriptionFromIssue(issue.body);
+
+ // LOOP PREVENTION
+ let shouldUpdateDescription = true;
+
+ if (lastDescSync) {
+ // Skip if this value was just synced from Kaneo
+ if (
+ lastDescSync.value === formattedDescription &&
+ lastDescSync.source === "kaneo"
+ ) {
+ console.log("Skipping description update - already synced from Kaneo");
+ shouldUpdateDescription = false;
+ }
+
+ // Skip if recent sync (within 2 seconds)
+ const timeSinceLastSync =
+ Date.now() - new Date(lastDescSync.timestamp).getTime();
+ if (timeSinceLastSync < 2000 && shouldUpdateDescription) {
+ console.log(
+ `Skipping description update - recent sync detected (${timeSinceLastSync}ms ago)`,
+ );
+ shouldUpdateDescription = false;
+ }
+ }
+
+ if (shouldUpdateDescription) {
+ updateData.description = formattedDescription;
+ updatedMetadata.lastSync.description = {
+ timestamp: new Date().toISOString(),
+ source: "github",
+ value: formattedDescription,
+ };
+ console.log("Updating task description from GitHub");
+ }
+ }
+
+ // Apply updates if any
+ 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,
+ });
+
+ console.log(
+ `Synced ${Object.keys(updateData).join(", ")} from GitHub issue #${issue.number} to task ${task.id}`,
+ );
+ } else {
+ console.log(
+ `No updates needed for task ${task.id} from issue #${issue.number}`,
+ );
+ }
+}
diff --git a/apps/api/src/plugins/registry.ts b/apps/api/src/plugins/registry.ts
index c225977f7..0d5a4b350 100644
--- a/apps/api/src/plugins/registry.ts
+++ b/apps/api/src/plugins/registry.ts
@@ -6,8 +6,10 @@ import type {
IntegrationPlugin,
PluginContext,
TaskCreatedEvent,
+ TaskDescriptionChangedEvent,
TaskPriorityChangedEvent,
TaskStatusChangedEvent,
+ TaskTitleChangedEvent,
} from "./types";
const plugins = new Map<string, IntegrationPlugin>();
@@ -84,6 +86,38 @@ export function initializeEventSubscriptions(): void {
});
});
+ subscribeToEvent<{
+ taskId: string;
+ userId: string | null;
+ oldTitle: string;
+ newTitle: string;
+ projectId: string;
+ }>("task.title_changed", async (data) => {
+ await broadcastTaskTitleChanged({
+ taskId: data.taskId,
+ projectId: data.projectId,
+ userId: data.userId,
+ oldTitle: data.oldTitle,
+ newTitle: data.newTitle,
+ });
+ });
+
+ subscribeToEvent<{
+ taskId: string;
+ userId: string | null;
+ oldDescription: string | null;
+ newDescription: string | null;
+ projectId: string;
+ }>("task.description_changed", async (data) => {
+ await broadcastTaskDescriptionChanged({
+ taskId: data.taskId,
+ projectId: data.projectId,
+ userId: data.userId,
+ oldDescription: data.oldDescription,
+ newDescription: data.newDescription,
+ });
+ });
+
eventSubscriptionsInitialized = true;
console.log("✓ Plugin event subscriptions initialized");
}
@@ -182,3 +216,47 @@ export async function broadcastTaskPriorityChanged(
}
}
}
+
+export async function broadcastTaskTitleChanged(
+ event: TaskTitleChangedEvent,
+): Promise<void> {
+ const integrations = await getActiveIntegrations(event.projectId);
+
+ for (const integration of integrations) {
+ const plugin = getPlugin(integration.type);
+ if (!plugin?.onTaskTitleChanged) continue;
+
+ const context = createContext(integration);
+
+ try {
+ await plugin.onTaskTitleChanged(event, context);
+ } catch (error) {
+ console.error(
+ `Plugin ${plugin.type} error on task.title_changed:`,
+ error,
+ );
+ }
+ }
+}
+
+export async function broadcastTaskDescriptionChanged(
+ event: TaskDescriptionChangedEvent,
+): Promise<void> {
+ const integrations = await getActiveIntegrations(event.projectId);
+
+ for (const integration of integrations) {
+ const plugin = getPlugin(integration.type);
+ if (!plugin?.onTaskDescriptionChanged) continue;
+
+ const context = createContext(integration);
+
+ try {
+ await plugin.onTaskDescriptionChanged(event, context);
+ } catch (error) {
+ console.error(
+ `Plugin ${plugin.type} error on task.description_changed:`,
+ error,
+ );
+ }
+ }
+}
diff --git a/apps/api/src/plugins/types.ts b/apps/api/src/plugins/types.ts
index b2854696a..5b3deac96 100644
--- a/apps/api/src/plugins/types.ts
+++ b/apps/api/src/plugins/types.ts
@@ -33,10 +33,28 @@ export type TaskPriorityChangedEvent = {
title: string;
};
+export type TaskTitleChangedEvent = {
+ taskId: string;
+ projectId: string;
+ userId: string | null;
+ oldTitle: string;
+ newTitle: string;
+};
+
+export type TaskDescriptionChangedEvent = {
+ taskId: string;
+ projectId: string;
+ userId: string | null;
+ oldDescription: string | null;
+ newDescription: string | null;
+};
+
export type TaskEvent =
| TaskCreatedEvent
| TaskStatusChangedEvent
- | TaskPriorityChangedEvent;
+ | TaskPriorityChangedEvent
+ | TaskTitleChangedEvent
+ | TaskDescriptionChangedEvent;
export type ExternalMetadata = {
type: "issue" | "pull_request" | "branch";
@@ -74,6 +92,8 @@ export type IntegrationPlugin = {
onTaskCreated?: TaskEventHandler<TaskCreatedEvent>;
onTaskStatusChanged?: TaskEventHandler<TaskStatusChangedEvent>;
onTaskPriorityChanged?: TaskEventHandler<TaskPriorityChangedEvent>;
+ onTaskTitleChanged?: TaskEventHandler<TaskTitleChangedEvent>;
+ onTaskDescriptionChanged?: TaskEventHandler<TaskDescriptionChangedEvent>;
handleWebhook?: WebhookHandler;
getTaskMetadata?: MetadataProvider;
diff --git a/apps/api/src/task/index.ts b/apps/api/src/task/index.ts
index df34e7ce3..8023b209b 100644
--- a/apps/api/src/task/index.ts
+++ b/apps/api/src/task/index.ts
@@ -1,7 +1,11 @@
+import { eq } from "drizzle-orm";
import { Hono } from "hono";
+import { HTTPException } from "hono/http-exception";
import { describeRoute, resolver, validator } from "hono-openapi";
import * as v from "valibot";
import { auth } from "../auth";
+import db from "../database";
+import { taskTable } from "../database/schema";
import { publishEvent } from "../events";
import { taskSchema } from "../schemas";
import { workspaceAccess } from "../utils/workspace-access-middleware";
@@ -476,14 +480,23 @@ const task = new Hono<{
const { title } = c.req.valid("json");
const user = c.get("userId");
+ // Fetch task BEFORE update to get old title
+ const existingTask = await db.query.taskTable.findFirst({
+ where: eq(taskTable.id, id),
+ });
+
+ if (!existingTask) {
+ throw new HTTPException(404, { message: "Task not found" });
+ }
+
const task = await updateTaskTitle({ id, title });
await publishEvent("task.title_changed", {
taskId: task.id,
+ projectId: task.projectId,
userId: user,
- oldTitle: task.title,
+ oldTitle: existingTask.title,
newTitle: title,
- title: task.title,
type: "title_changed",
});
@@ -514,12 +527,23 @@ const task = new Hono<{
const { description } = c.req.valid("json");
const user = c.get("userId");
+ // Fetch task BEFORE update to get old description
+ const existingTask = await db.query.taskTable.findFirst({
+ where: eq(taskTable.id, id),
+ });
+
+ if (!existingTask) {
+ throw new HTTPException(404, { message: "Task not found" });
+ }
+
const task = await updateTaskDescription({ id, description });
await publishEvent("task.description_changed", {
taskId: task.id,
+ projectId: task.projectId,
userId: user,
- title: task.title,
+ oldDescription: existingTask.description,
+ newDescription: description,
type: "description_changed",
});