⚡ 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
feat: add websockets for realtime collaboration
tiran133b94d3625444e
diff --git a/apps/api/package.json b/apps/api/package.jsonindex eef97e40a..215cc07ae 100644--- a/apps/api/package.json+++ b/apps/api/package.json@@ -32,6 +32,7 @@"@better-auth/api-key": "^1.5.6","@better-auth/drizzle-adapter": "^1.5.6","@hono/node-server": "^1.19.11",+ "@hono/node-ws": "^1.3.0","@hono/standard-validator": "^0.2.2","@kaneo/email": "workspace:*","@octokit/webhooks": "^14.2.0",diff --git a/apps/api/src/activity/controllers/create-activity.ts b/apps/api/src/activity/controllers/create-activity.tsindex 22b8cdd89..e3dc5b30a 100644--- a/apps/api/src/activity/controllers/create-activity.ts+++ b/apps/api/src/activity/controllers/create-activity.ts@@ -8,13 +8,16 @@ async function createActivity(content: string | null,eventData?: Record<string, unknown> | null,) {- const activity = await db.insert(activityTable).values({- taskId,- type,- userId,- content,- eventData: eventData ?? null,- });+ const [activity] = await db+ .insert(activityTable)+ .values({+ taskId,+ type,+ userId,+ content,+ eventData: eventData ?? null,+ })+ .returning();return activity;}diff --git a/apps/api/src/activity/controllers/create-comment.ts b/apps/api/src/activity/controllers/create-comment.tsindex c6ce706d8..6bc4b1988 100644--- a/apps/api/src/activity/controllers/create-comment.ts+++ b/apps/api/src/activity/controllers/create-comment.ts@@ -1,13 +1,44 @@+import { eq } from "drizzle-orm";+import { HTTPException } from "hono/http-exception";import db from "../../database";-import { activityTable } from "../../database/schema";+import { activityTable, taskTable, userTable } from "../../database/schema";+import { publishEvent } from "../../events";async function createComment(taskId: string, userId: string, content: string) {- const activity = await db.insert(activityTable).values({- taskId,- type: "comment",- userId,- content,- });+ const [activity] = await db+ .insert(activityTable)+ .values({+ taskId,+ type: "comment",+ userId,+ content,+ })+ .returning();++ if (!activity) {+ throw new HTTPException(500, {+ message: "Failed to create activity",+ });+ }++ const [user] = await db+ .select({ name: userTable.name })+ .from(userTable)+ .where(eq(userTable.id, userId));++ const [task] = await db+ .select({ projectId: taskTable.projectId })+ .from(taskTable)+ .where(eq(taskTable.id, taskId));++ if (task) {+ await publishEvent("task.comment_created", {+ ...activity,+ comment: `"${user?.name}" commented: ${content}`,+ projectId: task.projectId,+ });+ }+return activity;}diff --git a/apps/api/src/activity/controllers/delete-comment.ts b/apps/api/src/activity/controllers/delete-comment.tsindex cf60ee061..4080a0b23 100644--- a/apps/api/src/activity/controllers/delete-comment.ts+++ b/apps/api/src/activity/controllers/delete-comment.ts@@ -1,6 +1,8 @@import { and, eq } from "drizzle-orm";+import { HTTPException } from "hono/http-exception";import db from "../../database";-import { activityTable } from "../../database/schema";+import { activityTable, taskTable } from "../../database/schema";+import { publishEvent } from "../../events";async function deleteComment(userId: string, id: string) {const [deletedComment] = await db@@ -8,6 +10,26 @@ async function deleteComment(userId: string, id: string) {.where(and(eq(activityTable.id, id), eq(activityTable.userId, userId))).returning();+ if (!deletedComment) {+ throw new HTTPException(404, {+ message: "Comment not found or you are not the author",+ });+ }++ const [task] = await db+ .select({ projectId: taskTable.projectId })+ .from(taskTable)+ .where(eq(taskTable.id, deletedComment.taskId))+ .limit(1);++ if (task) {+ await publishEvent("comment.deleted", {+ ...deletedComment,+ projectId: task.projectId,+ userId,+ });+ }+return deletedComment;}diff --git a/apps/api/src/activity/controllers/update-comment.ts b/apps/api/src/activity/controllers/update-comment.tsindex 49bcef420..f462dddc7 100644--- a/apps/api/src/activity/controllers/update-comment.ts+++ b/apps/api/src/activity/controllers/update-comment.ts@@ -1,12 +1,37 @@import { and, eq } from "drizzle-orm";+import { HTTPException } from "hono/http-exception";import db from "../../database";-import { activityTable } from "../../database/schema";+import { activityTable, taskTable } from "../../database/schema";+import { publishEvent } from "../../events";async function updateComment(userId: string, id: string, content: string) {- return await db+ const [updated] = await db.update(activityTable).set({ content })- .where(and(eq(activityTable.id, id), eq(activityTable.userId, userId)));+ .where(and(eq(activityTable.id, id), eq(activityTable.userId, userId)))+ .returning();++ if (!updated) {+ throw new HTTPException(404, {+ message: "Comment not found or you are not the author",+ });+ }++ const [task] = await db+ .select({ projectId: taskTable.projectId })+ .from(taskTable)+ .where(eq(taskTable.id, updated.taskId))+ .limit(1);++ if (task) {+ await publishEvent("comment.updated", {+ ...updated,+ projectId: task.projectId,+ userId,+ });+ }++ return updated;}export default updateComment;diff --git a/apps/api/src/activity/index.ts b/apps/api/src/activity/index.tsindex f14bd7b4b..299700ed8 100644--- a/apps/api/src/activity/index.ts+++ b/apps/api/src/activity/index.ts@@ -1,10 +1,7 @@-import { eq } from "drizzle-orm";import { Hono } from "hono";import { describeRoute, resolver, validator } from "hono-openapi";import * as v from "valibot";-import db from "../database";-import { taskTable, userTable } from "../database/schema";-import { publishEvent, subscribeToEvent } from "../events";+import { subscribeToEvent } from "../events";import { activitySchema } from "../schemas";import { workspaceAccess } from "../utils/workspace-access-middleware";import createActivity from "./controllers/create-activity";@@ -107,25 +104,6 @@ const activity = new Hono<{const userId = c.get("userId");const newComment = await createComment(taskId, userId, comment);- const [user] = await db- .select({ name: userTable.name })- .from(userTable)- .where(eq(userTable.id, userId));-- const [task] = await db- .select({ projectId: taskTable.projectId })- .from(taskTable)- .where(eq(taskTable.id, taskId));-- if (task) {- await publishEvent("task.comment_created", {- taskId,- userId,- comment: `"${user?.name}" commented: ${comment}`,- projectId: task.projectId,- });- }-return c.json(newComment);},)@@ -191,14 +169,14 @@ const activity = new Hono<{subscribeToEvent<{taskId: string;- userId: string;+ currentUserId: string;type: string;content: string | null;}>("task.created", async (data) => {- if (!data.userId || !data.taskId || !data.type) {+ if (!data.currentUserId || !data.taskId || !data.type) {return;}- await createActivity(data.taskId, data.type, data.userId, null, {});+ await createActivity(data.taskId, data.type, data.currentUserId, null, {});});subscribeToEvent<{@@ -206,22 +184,29 @@ subscribeToEvent<{userId: string;type: string;content: string;- eventData: {- fromProjectId: string;- fromProjectName: string;- toProjectId: string;- toProjectName: string;- oldStatus: string;- newStatus: string;- };+ fromProjectId: string;+ fromProjectName: string;+ toProjectId: string;+ toProjectName: string;+ oldStatus: string;+ newStatus: string;}>("task.moved", async (data) => {- await createActivity(data.taskId, data.type, data.userId, data.content, {- fromProjectId: data.eventData.fromProjectId,- fromProjectName: data.eventData.fromProjectName,- toProjectId: data.eventData.toProjectId,- toProjectName: data.eventData.toProjectName,- oldStatus: data.eventData.oldStatus,- newStatus: data.eventData.newStatus,+ const {+ fromProjectId,+ fromProjectName,+ toProjectId,+ toProjectName,+ oldStatus,+ newStatus,+ } = data;++ await createActivity(data.taskId, data.type, data.userId, null, {+ fromProjectId,+ fromProjectName,+ toProjectId,+ toProjectName,+ oldStatus,+ newStatus,});});diff --git a/apps/api/src/comment/controllers/create-comment.ts b/apps/api/src/comment/controllers/create-comment.tsindex 23e5ad4d1..afc2894b5 100644--- a/apps/api/src/comment/controllers/create-comment.ts+++ b/apps/api/src/comment/controllers/create-comment.ts@@ -1,8 +1,20 @@+import { eq } from "drizzle-orm";import { HTTPException } from "hono/http-exception";import db from "../../database";-import { commentTable } from "../../database/schema";+import { commentTable, taskTable } from "../../database/schema";+import { publishEvent } from "../../events";async function createComment(taskId: string, userId: string, content: string) {+ const [task] = await db+ .select({ projectId: taskTable.projectId })+ .from(taskTable)+ .where(eq(taskTable.id, taskId))+ .limit(1);++ if (!task) {+ throw new HTTPException(404, { message: "Task not found" });+ }+const [comment] = await db.insert(commentTable).values({@@ -16,6 +28,12 @@ async function createComment(taskId: string, userId: string, content: string) {throw new HTTPException(500, { message: "Failed to create comment" });}+ await publishEvent("comment.created", {+ ...comment,+ projectId: task.projectId,+ userId,+ });+return comment;}diff --git a/apps/api/src/comment/controllers/delete-comment.ts b/apps/api/src/comment/controllers/delete-comment.tsindex c2687b6c5..92dbbd262 100644--- a/apps/api/src/comment/controllers/delete-comment.ts+++ b/apps/api/src/comment/controllers/delete-comment.ts@@ -1,11 +1,12 @@import { eq } from "drizzle-orm";import { HTTPException } from "hono/http-exception";import db from "../../database";-import { commentTable } from "../../database/schema";+import { commentTable, taskTable } from "../../database/schema";+import { publishEvent } from "../../events";async function deleteComment(userId: string, id: string) {const [existing] = await db- .select({ userId: commentTable.userId })+ .select({ userId: commentTable.userId, taskId: commentTable.taskId }).from(commentTable).where(eq(commentTable.id, id)).limit(1);@@ -20,6 +21,12 @@ async function deleteComment(userId: string, id: string) {});}+ const [task] = await db+ .select({ projectId: taskTable.projectId })+ .from(taskTable)+ .where(eq(taskTable.id, existing.taskId))+ .limit(1);+const [deleted] = await db.delete(commentTable).where(eq(commentTable.id, id))@@ -29,6 +36,14 @@ async function deleteComment(userId: string, id: string) {throw new HTTPException(500, { message: "Failed to delete comment" });}+ if (task) {+ await publishEvent("comment.deleted", {+ ...deleted,+ projectId: task.projectId,+ userId,+ });+ }+return deleted;}diff --git a/apps/api/src/comment/controllers/update-comment.ts b/apps/api/src/comment/controllers/update-comment.tsindex 2b38c5e0b..44e6164e6 100644--- a/apps/api/src/comment/controllers/update-comment.ts+++ b/apps/api/src/comment/controllers/update-comment.ts@@ -1,11 +1,12 @@import { eq } from "drizzle-orm";import { HTTPException } from "hono/http-exception";import db from "../../database";-import { commentTable } from "../../database/schema";+import { commentTable, taskTable } from "../../database/schema";+import { publishEvent } from "../../events";async function updateComment(userId: string, id: string, content: string) {const [existing] = await db- .select({ userId: commentTable.userId })+ .select({ userId: commentTable.userId, taskId: commentTable.taskId }).from(commentTable).where(eq(commentTable.id, id)).limit(1);@@ -20,6 +21,12 @@ async function updateComment(userId: string, id: string, content: string) {});}+ const [task] = await db+ .select({ projectId: taskTable.projectId })+ .from(taskTable)+ .where(eq(taskTable.id, existing.taskId))+ .limit(1);+const [updated] = await db.update(commentTable).set({ content })@@ -30,6 +37,14 @@ async function updateComment(userId: string, id: string, content: string) {throw new HTTPException(500, { message: "Failed to update comment" });}+ if (task) {+ await publishEvent("comment.updated", {+ ...updated,+ projectId: task.projectId,+ userId,+ });+ }+return updated;}diff --git a/apps/api/src/events/index.ts b/apps/api/src/events/index.tsindex 03aab81a0..67525dfd2 100644--- a/apps/api/src/events/index.ts+++ b/apps/api/src/events/index.ts@@ -1,7 +1,9 @@+import { AsyncLocalStorage } from "node:async_hooks";import { EventEmitter } from "node:events";const EVENTS = new EventEmitter();EVENTS.setMaxListeners(100);+export const eventContext = new AsyncLocalStorage<{ initiatorId: string }>();export type EventPayload<T = unknown> = {type: string;@@ -17,6 +19,11 @@ export async function publishEvent(eventType: string,data: unknown,): Promise<void> {+ if (typeof data === "object" && data !== null && "initiatorId" in data) {+ const store = eventContext.getStore();+ data.initiatorId = store?.initiatorId;+ }+const payload: EventPayload = {type: eventType,data,diff --git a/apps/api/src/index.ts b/apps/api/src/index.tsindex ea5ea8071..2e06eb867 100644--- a/apps/api/src/index.ts+++ b/apps/api/src/index.ts@@ -1,6 +1,7 @@import { dirname } from "node:path";import { fileURLToPath, pathToFileURL } from "node:url";import { serve } from "@hono/node-server";+import { createNodeWebSocket } from "@hono/node-ws";import type { Session, User } from "better-auth/types";import { and, eq } from "drizzle-orm";import { migrate } from "drizzle-orm/node-postgres/migrator";@@ -21,6 +22,7 @@ import comment from "./comment";import config from "./config";import db, { schema } from "./database";import discordIntegration from "./discord-integration";+import { eventContext } from "./events";import externalLink from "./external-link";import genericWebhookIntegration from "./generic-webhook-integration";import giteaIntegration, { handleGiteaWebhookRoute } from "./gitea-integration";@@ -66,6 +68,7 @@ import {import { validateWorkspaceAccess } from "./utils/validate-workspace-access";import workflowRule from "./workflow-rule";import workspace from "./workspace";+import { addConnection, removeConnection } from "./ws";type ApiKey = {id: string;@@ -114,8 +117,13 @@ function buildContentDisposition(filename: string) {return `inline; filename="${asciiFallback}"; filename*=UTF-8''${encodedFilename}`;}+let injectWebSocket: ReturnType<typeof createNodeWebSocket>["injectWebSocket"];+export function createApp() {const app = new Hono<AppVariables>();+ const nodeWs = createNodeWebSocket({ app });+ const upgradeWebSocket = nodeWs.upgradeWebSocket;+ injectWebSocket = nodeWs.injectWebSocket;const corsOrigins = process.env.CORS_ORIGINS? process.env.CORS_ORIGINS.split(",").map((origin) => origin.trim()): undefined;@@ -428,7 +436,12 @@ export function createApp() {console.error("API authentication failed:", error);throw new HTTPException(500, { message: "Internal Server Error" });}- return next();++ const windowId = c.req.header("X-Kaneo-Window-Id");+ const userId = c.get("userId");+ const initiatorId = windowId ? `${userId}:${windowId}` : userId;++ return eventContext.run({ initiatorId }, next);});const oauthIdTokenApi = api.get(@@ -504,6 +517,30 @@ export function createApp() {app.route("/api", api);+ app.get(+ "/ws/:projectId",+ upgradeWebSocket((c) => {+ const projectId = c.req.param("projectId");+ const userId = c.req.query("userId") || "anonymous";+ const windowId = c.req.query("windowId");+ const initiatorId = windowId ? `${userId}:${windowId}` : userId;+ let conn: ReturnType<typeof addConnection> | null = null;++ return {+ onOpen(_evt, ws) {+ if (projectId) {+ conn = addConnection(projectId, ws, userId, initiatorId);+ }+ },+ onClose() {+ if (conn && projectId) {+ removeConnection(projectId, conn);+ }+ },+ };+ }),+ );+return {app,api,@@ -568,7 +605,7 @@ export async function startServer(port = 1337) {shutdownScheduler();});- serve(+ const server = serve({fetch: app.fetch,port,@@ -579,6 +616,8 @@ export async function startServer(port = 1337) {);},);++ injectWebSocket(server);}const createdApp = createApp();diff --git a/apps/api/src/label/controllers/assign-label-to-task.ts b/apps/api/src/label/controllers/assign-label-to-task.tsindex a55cf271f..7ef856a9b 100644--- a/apps/api/src/label/controllers/assign-label-to-task.ts+++ b/apps/api/src/label/controllers/assign-label-to-task.ts@@ -2,6 +2,7 @@ import { eq } from "drizzle-orm";import { HTTPException } from "hono/http-exception";import db from "../../database";import { labelTable, projectTable, taskTable } from "../../database/schema";+import { publishEvent } from "../../events";import {removeLabelFromGitea,syncLabelToGitea,@@ -11,7 +12,7 @@ import {syncLabelToGitHub,} from "../../plugins/github/utils/sync-label-to-github";-async function assignLabelToTask(id: string, taskId: string) {+async function assignLabelToTask(id: string, taskId: string, userId: string) {const label = await db.query.labelTable.findFirst({where: (label, { eq }) => eq(label.id, id),});@@ -25,6 +26,7 @@ async function assignLabelToTask(id: string, taskId: string) {const [task] = await db.select({id: taskTable.id,+ projectId: taskTable.projectId,workspaceId: projectTable.workspaceId,}).from(taskTable)@@ -76,6 +78,13 @@ async function assignLabelToTask(id: string, taskId: string) {},);+ await publishEvent("task.label_assigned", {+ ...updatedLabel,+ ...task,+ userId: userId,+ type: "label_assigned",+ });+return updatedLabel;}diff --git a/apps/api/src/label/controllers/create-label.ts b/apps/api/src/label/controllers/create-label.tsindex 74e7eb536..924ec2d24 100644--- a/apps/api/src/label/controllers/create-label.ts+++ b/apps/api/src/label/controllers/create-label.ts@@ -1,6 +1,8 @@import { and, eq, isNull, sql } from "drizzle-orm";+import { HTTPException } from "hono/http-exception";import db from "../../database";-import { labelTable } from "../../database/schema";+import { labelTable, projectTable, taskTable } from "../../database/schema";+import { publishEvent } from "../../events";import { syncLabelToGitea } from "../../plugins/gitea/utils/sync-label-to-gitea";import { syncLabelToGitHub } from "../../plugins/github/utils/sync-label-to-github";@@ -9,8 +11,26 @@ async function createLabel(color: string,taskId: string | undefined,workspaceId: string,+ userId: string,) {if (taskId) {+ const [task] = await db+ .select({+ id: taskTable.id,+ projectId: taskTable.projectId,+ workspaceId: projectTable.workspaceId,+ })+ .from(taskTable)+ .innerJoin(projectTable, eq(taskTable.projectId, projectTable.id))+ .where(eq(taskTable.id, taskId))+ .limit(1);++ if (!task) {+ throw new HTTPException(404, {+ message: "Task not found",+ });+ }+const [inserted] = await db.insert(labelTable).values({ name, color, taskId, workspaceId })@@ -38,6 +58,13 @@ async function createLabel(});}+ await publishEvent("task.label_created", {+ ...label,+ ...task,+ userId: userId,+ type: "label_created",+ });+return label;}diff --git a/apps/api/src/label/controllers/delete-label.ts b/apps/api/src/label/controllers/delete-label.tsindex 8dddb4b4b..291fedecb 100644--- a/apps/api/src/label/controllers/delete-label.ts+++ b/apps/api/src/label/controllers/delete-label.ts@@ -1,10 +1,11 @@import { eq } from "drizzle-orm";import { HTTPException } from "hono/http-exception";import db from "../../database";-import { labelTable } from "../../database/schema";+import { labelTable, projectTable, taskTable } from "../../database/schema";+import { publishEvent } from "../../events";import { removeLabelFromGitHub } from "../../plugins/github/utils/sync-label-to-github";-async function deleteLabel(id: string) {+async function deleteLabel(id: string, userId: string) {const label = await db.query.labelTable.findFirst({where: (label, { eq }) => eq(label.id, id),});@@ -15,6 +16,29 @@ async function deleteLabel(id: string) {});}+ if (!label.taskId) {+ throw new HTTPException(400, {+ message: "Label is not associated with a task",+ });+ }++ const [task] = await db+ .select({+ id: taskTable.id,+ projectId: taskTable.projectId,+ workspaceId: projectTable.workspaceId,+ })+ .from(taskTable)+ .innerJoin(projectTable, eq(taskTable.projectId, projectTable.id))+ .where(eq(taskTable.id, label.taskId))+ .limit(1);++ if (!task) {+ throw new HTTPException(404, {+ message: "Task not found",+ });+ }+const [deletedLabel] = await db.delete(labelTable).where(eq(labelTable.id, id))@@ -28,6 +52,13 @@ async function deleteLabel(id: string) {);}+ await publishEvent("task.label_deleted", {+ ...label,+ ...task,+ userId: userId,+ type: "label_deleted",+ });+return deletedLabel;}diff --git a/apps/api/src/label/controllers/unassign-label-from-task.ts b/apps/api/src/label/controllers/unassign-label-from-task.tsindex eb73313e5..e8b9555c9 100644--- a/apps/api/src/label/controllers/unassign-label-from-task.ts+++ b/apps/api/src/label/controllers/unassign-label-from-task.ts@@ -1,10 +1,11 @@import { eq } from "drizzle-orm";import { HTTPException } from "hono/http-exception";import db from "../../database";-import { labelTable } from "../../database/schema";+import { labelTable, projectTable, taskTable } from "../../database/schema";+import { publishEvent } from "../../events";import { removeLabelFromGitHub } from "../../plugins/github/utils/sync-label-to-github";-async function unassignLabelFromTask(id: string) {+async function unassignLabelFromTask(id: string, userId: string) {const label = await db.query.labelTable.findFirst({where: (label, { eq }) => eq(label.id, id),});@@ -15,6 +16,29 @@ async function unassignLabelFromTask(id: string) {});}+ if (!label.taskId) {+ throw new HTTPException(400, {+ message: "Label is not assigned to a task",+ });+ }++ const [task] = await db+ .select({+ id: taskTable.id,+ projectId: taskTable.projectId,+ workspaceId: projectTable.workspaceId,+ })+ .from(taskTable)+ .innerJoin(projectTable, eq(taskTable.projectId, projectTable.id))+ .where(eq(taskTable.id, label.taskId))+ .limit(1);++ if (!task) {+ throw new HTTPException(404, {+ message: "Task not found",+ });+ }+const [updatedLabel] = await db.update(labelTable).set({ taskId: null })@@ -33,6 +57,13 @@ async function unassignLabelFromTask(id: string) {});}+ await publishEvent("task.label_unassigned", {+ ...updatedLabel,+ ...task,+ userId: userId,+ type: "label_unassigned",+ });+return updatedLabel;}diff --git a/apps/api/src/label/index.ts b/apps/api/src/label/index.tsindex c100ef838..6f33e80b2 100644--- a/apps/api/src/label/index.ts+++ b/apps/api/src/label/index.ts@@ -12,7 +12,11 @@ import getLabelsByWorkspaceId from "./controllers/get-labels-by-workspace-id";import unassignLabelFromTask from "./controllers/unassign-label-from-task";import updateLabel from "./controllers/update-label";-const label = new Hono()+const label = new Hono<{+ Variables: {+ userId: string;+ };+}>().get("/task/:taskId",describeRoute({@@ -86,7 +90,8 @@ const label = new Hono()workspaceAccess.fromBody(),async (c) => {const { name, color, workspaceId, taskId } = c.req.valid("json");- const label = await createLabel(name, color, taskId, workspaceId);+ const userId = c.get("userId");+ const label = await createLabel(name, color, taskId, workspaceId, userId);return c.json(label);},)@@ -134,7 +139,8 @@ const label = new Hono()async (c) => {const { id } = c.req.valid("param");const { taskId } = c.req.valid("json");- const label = await assignLabelToTask(id, taskId);+ const userId = c.get("userId");+ const label = await assignLabelToTask(id, taskId, userId);return c.json(label);},)@@ -157,7 +163,8 @@ const label = new Hono()workspaceAccess.fromLabel(),async (c) => {const { id } = c.req.valid("param");- const label = await unassignLabelFromTask(id);+ const userId = c.get("userId");+ const label = await unassignLabelFromTask(id, userId);return c.json(label);},)@@ -211,7 +218,8 @@ const label = new Hono()workspaceAccess.fromLabel(),async (c) => {const { id } = c.req.valid("param");- const label = await deleteLabel(id);+ const userId = c.get("userId");+ const label = await deleteLabel(id, userId);return c.json(label);},);diff --git a/apps/api/src/task-relation/controllers/create-task-relation.ts b/apps/api/src/task-relation/controllers/create-task-relation.tsindex 466e3d254..2a0fcdc1f 100644--- a/apps/api/src/task-relation/controllers/create-task-relation.ts+++ b/apps/api/src/task-relation/controllers/create-task-relation.ts@@ -2,15 +2,18 @@ import { and, eq, or } from "drizzle-orm";import { HTTPException } from "hono/http-exception";import db from "../../database";import { taskRelationTable, taskTable } from "../../database/schema";+import { publishEvent } from "../../events";async function createTaskRelation({sourceTaskId,targetTaskId,relationType,+ userId,}: {sourceTaskId: string;targetTaskId: string;relationType: string;+ userId: string;}) {if (sourceTaskId === targetTaskId) {throw new HTTPException(400, {@@ -19,7 +22,7 @@ async function createTaskRelation({}const [sourceTask] = await db- .select({ id: taskTable.id })+ .select({ id: taskTable.id, projectId: taskTable.projectId }).from(taskTable).where(eq(taskTable.id, sourceTaskId)).limit(1);@@ -29,7 +32,7 @@ async function createTaskRelation({}const [targetTask] = await db- .select({ id: taskTable.id })+ .select({ id: taskTable.id, projectId: taskTable.projectId }).from(taskTable).where(eq(taskTable.id, targetTaskId)).limit(1);@@ -79,6 +82,13 @@ async function createTaskRelation({});}+ await publishEvent("task-relation.created", {+ ...relation,+ taskId: sourceTaskId,+ projectId: sourceTask.projectId,+ userId,+ });+return relation;}diff --git a/apps/api/src/task-relation/controllers/delete-task-relation.ts b/apps/api/src/task-relation/controllers/delete-task-relation.tsindex 3a027e022..82174fb57 100644--- a/apps/api/src/task-relation/controllers/delete-task-relation.ts+++ b/apps/api/src/task-relation/controllers/delete-task-relation.ts@@ -1,9 +1,31 @@import { eq } from "drizzle-orm";import { HTTPException } from "hono/http-exception";import db from "../../database";-import { taskRelationTable } from "../../database/schema";+import { taskRelationTable, taskTable } from "../../database/schema";+import { publishEvent } from "../../events";++async function deleteTaskRelation(id: string, userId: string) {+ const [rel] = await db+ .select({+ sourceTaskId: taskRelationTable.sourceTaskId,+ targetTaskId: taskRelationTable.targetTaskId,+ })+ .from(taskRelationTable)+ .where(eq(taskRelationTable.id, id))+ .limit(1);++ if (!rel) {+ throw new HTTPException(404, {+ message: "Task relation not found",+ });+ }++ const [task] = await db+ .select({ projectId: taskTable.projectId })+ .from(taskTable)+ .where(eq(taskTable.id, rel.sourceTaskId))+ .limit(1);-async function deleteTaskRelation(id: string) {const [relation] = await db.delete(taskRelationTable).where(eq(taskRelationTable.id, id))@@ -15,6 +37,17 @@ async function deleteTaskRelation(id: string) {});}+ if (task) {+ await publishEvent("task-relation.deleted", {+ ...relation,+ taskId: rel.sourceTaskId,+ sourceTaskId: rel.sourceTaskId,+ targetTaskId: rel.targetTaskId,+ projectId: task.projectId,+ userId,+ });+ }+return relation;}diff --git a/apps/api/src/task-relation/index.ts b/apps/api/src/task-relation/index.tsindex 7ef16306c..b5cb481c8 100644--- a/apps/api/src/task-relation/index.ts+++ b/apps/api/src/task-relation/index.ts@@ -89,11 +89,13 @@ const taskRelation = new Hono<{return next();},async (c) => {+ const userId = c.get("userId");const { sourceTaskId, targetTaskId, relationType } = c.req.valid("json");const relation = await createTaskRelation({sourceTaskId,targetTaskId,relationType,+ userId,});return c.json(relation);},@@ -141,8 +143,9 @@ const taskRelation = new Hono<{return next();},async (c) => {+ const userId = c.get("userId");const { id } = c.req.valid("param");- const relation = await deleteTaskRelation(id);+ const relation = await deleteTaskRelation(id, userId);return c.json(relation);},);diff --git a/apps/api/src/task/controllers/create-task.ts b/apps/api/src/task/controllers/create-task.tsindex 1dbc75496..c7d6bfb70 100644--- a/apps/api/src/task/controllers/create-task.ts+++ b/apps/api/src/task/controllers/create-task.ts@@ -8,6 +8,7 @@ import getNextTaskNumber from "./get-next-task-number";async function createTask({projectId,+ currentUserId,userId,title,status,@@ -17,6 +18,7 @@ async function createTask({priority,}: {projectId: string;+ currentUserId: string;userId?: string;title: string;status: string;@@ -85,7 +87,8 @@ async function createTask({...createdTask,taskId: createdTask.id,userId: createdTask.userId ?? "",- type: "task",+ currentUserId: currentUserId,+ type: "created",content: null,});diff --git a/apps/api/src/task/controllers/delete-task.ts b/apps/api/src/task/controllers/delete-task.tsindex 82d0c9bda..6e1903d35 100644--- a/apps/api/src/task/controllers/delete-task.ts+++ b/apps/api/src/task/controllers/delete-task.ts@@ -1,12 +1,24 @@-import { eq } from "drizzle-orm";+import { eq, or } from "drizzle-orm";import { HTTPException } from "hono/http-exception";import db from "../../database";-import { taskTable } from "../../database/schema";+import { taskRelationTable, taskTable } from "../../database/schema";+import { publishEvent } from "../../events";import getTask from "./get-task";-async function deleteTask(taskId: string) {+async function deleteTask(taskId: string, currentUserId: string) {const task = await getTask(taskId);+ const relations = await db+ .select()+ .from(taskRelationTable)+ .where(+ or(+ eq(taskRelationTable.sourceTaskId, taskId),+ eq(taskRelationTable.targetTaskId, taskId),+ ),+ )+ .execute();+const [deletedTask] = await db.delete(taskTable).where(eq(taskTable.id, taskId))@@ -19,6 +31,22 @@ async function deleteTask(taskId: string) {});}+ await publishEvent("task.deleted", {+ taskId: task.id,+ projectId: task.projectId,+ userId: currentUserId,+ });++ for (const relation of relations) {+ await publishEvent("task-relation.deleted", {+ projectId: task.projectId,+ userId: currentUserId,+ taskId: taskId,+ sourceTaskId: relation.sourceTaskId,+ targetTaskId: relation.targetTaskId,+ });+ }+return task;}diff --git a/apps/api/src/task/controllers/move-task.ts b/apps/api/src/task/controllers/move-task.tsindex cde0c4c26..0bedd1e81 100644--- a/apps/api/src/task/controllers/move-task.ts+++ b/apps/api/src/task/controllers/move-task.ts@@ -81,12 +81,12 @@ async function moveTask({taskId,destinationProjectId,destinationStatus,- userId,+ currentUserId,}: {taskId: string;destinationProjectId: string;destinationStatus?: string;- userId: string;+ currentUserId: string;}) {const existingTask = await db.query.taskTable.findFirst({where: eq(taskTable.id, taskId),@@ -131,6 +131,12 @@ async function moveTask({destinationStatus,);+ if (!resolvedColumn) {+ throw new HTTPException(400, {+ message: "Selected status is not valid for the destination project",+ });+ }+const movedTask = await db.transaction(async (tx) => {const [nextTaskNumber, nextPosition] = await Promise.all([getNextTaskNumber(destinationProjectId, tx),@@ -170,17 +176,14 @@ async function moveTask({await publishEvent("task.moved", {taskId,- type: "task",- userId,- content: `Moved task from ${sourceProject.name} to ${destinationProject.name}`,- eventData: {- fromProjectId: sourceProject.id,- fromProjectName: sourceProject.name,- toProjectId: destinationProject.id,- toProjectName: destinationProject.name,- oldStatus: existingTask.status,- newStatus: resolvedColumn.slug,- },+ type: "moved",+ userId: currentUserId,+ fromProjectId: sourceProject.id,+ fromProjectName: sourceProject.name,+ toProjectId: destinationProject.id,+ toProjectName: destinationProject.name,+ oldStatus: existingTask.status,+ newStatus: resolvedColumn.slug,});return {diff --git a/apps/api/src/task/controllers/update-task-assignee.ts b/apps/api/src/task/controllers/update-task-assignee.tsindex 7486c5c9a..04e5c7409 100644--- a/apps/api/src/task/controllers/update-task-assignee.ts+++ b/apps/api/src/task/controllers/update-task-assignee.ts@@ -1,14 +1,17 @@import { eq } from "drizzle-orm";import { HTTPException } from "hono/http-exception";import db from "../../database";-import { taskTable } from "../../database/schema";+import { taskTable, userTable } from "../../database/schema";+import { publishEvent } from "../../events";async function updateTaskAssignee({id,userId,+ currentUserId,}: {id: string;userId: string;+ currentUserId: string;}) {const existingTask = await db.query.taskTable.findFirst({where: eq(taskTable.id, id),@@ -19,7 +22,6 @@ async function updateTaskAssignee({message: "Task not found",});}-const [updatedTask] = await db.update(taskTable).set({ userId: userId || null })@@ -32,6 +34,39 @@ async function updateTaskAssignee({});}+ const newAssigneeName = userId+ ? (+ await db+ .select({ name: userTable.name })+ .from(userTable)+ .where(eq(userTable.id, userId))+ .limit(1)+ )[0]?.name+ : undefined;++ if (!userId) {+ await publishEvent("task.unassigned", {+ taskId: updatedTask.id,+ projectId: updatedTask.projectId,+ userId: currentUserId,+ title: updatedTask.title,+ type: "unassigned",+ });++ return updatedTask;+ }++ await publishEvent("task.assignee_changed", {+ taskId: updatedTask.id,+ projectId: updatedTask.projectId,+ userId: currentUserId,+ oldAssignee: existingTask.userId,+ newAssignee: newAssigneeName,+ newAssigneeId: userId,+ title: updatedTask.title,+ type: "assignee_changed",+ });+return updatedTask;}diff --git a/apps/api/src/task/controllers/update-task-description.ts b/apps/api/src/task/controllers/update-task-description.tsindex bf9fffd53..4c1580c65 100644--- a/apps/api/src/task/controllers/update-task-description.ts+++ b/apps/api/src/task/controllers/update-task-description.ts@@ -2,13 +2,16 @@ import { eq } from "drizzle-orm";import { HTTPException } from "hono/http-exception";import db from "../../database";import { taskTable } from "../../database/schema";+import { publishEvent } from "../../events";async function updateTaskDescription({id,description,+ currentUserId,}: {id: string;description: string;+ currentUserId: string;}) {const existingTask = await db.query.taskTable.findFirst({where: eq(taskTable.id, id),@@ -32,6 +35,15 @@ async function updateTaskDescription({});}+ await publishEvent("task.description_changed", {+ taskId: updatedTask.id,+ projectId: updatedTask.projectId,+ userId: currentUserId,+ oldDescription: existingTask.description,+ newDescription: description,+ type: "description_changed",+ });+return updatedTask;}diff --git a/apps/api/src/task/controllers/update-task-due-date.ts b/apps/api/src/task/controllers/update-task-due-date.tsindex 7661e5809..de50436ac 100644--- a/apps/api/src/task/controllers/update-task-due-date.ts+++ b/apps/api/src/task/controllers/update-task-due-date.ts@@ -2,13 +2,16 @@ import { eq } from "drizzle-orm";import { HTTPException } from "hono/http-exception";import db from "../../database";import { taskReminderSentTable, taskTable } from "../../database/schema";+import { publishEvent } from "../../events";async function updateTaskDueDate({id,dueDate,+ currentUserId,}: {id: string;dueDate: Date | null;+ currentUserId: string;}) {const existingTask = await db.query.taskTable.findFirst({where: eq(taskTable.id, id),@@ -37,6 +40,16 @@ async function updateTaskDueDate({});}+ await publishEvent("task.due_date_changed", {+ taskId: updatedTask.id,+ projectId: updatedTask.projectId,+ userId: currentUserId,+ oldDueDate: existingTask.dueDate,+ newDueDate: dueDate,+ title: updatedTask.title,+ type: "due_date_changed",+ });+return updatedTask;}diff --git a/apps/api/src/task/controllers/update-task-priority.ts b/apps/api/src/task/controllers/update-task-priority.tsindex 1f9fba445..ce63fd728 100644--- a/apps/api/src/task/controllers/update-task-priority.ts+++ b/apps/api/src/task/controllers/update-task-priority.ts@@ -2,13 +2,16 @@ import { eq } from "drizzle-orm";import { HTTPException } from "hono/http-exception";import db from "../../database";import { taskTable } from "../../database/schema";+import { publishEvent } from "../../events";async function updateTaskPriority({id,priority,+ currentUserId,}: {id: string;priority: string;+ currentUserId: string;}) {const existingTask = await db.query.taskTable.findFirst({where: eq(taskTable.id, id),@@ -32,6 +35,16 @@ async function updateTaskPriority({});}+ await publishEvent("task.priority_changed", {+ taskId: updatedTask.id,+ projectId: updatedTask.projectId,+ userId: currentUserId,+ oldPriority: existingTask.priority,+ newPriority: priority,+ title: updatedTask.title,+ type: "priority_changed",+ });+return updatedTask;}diff --git a/apps/api/src/task/controllers/update-task-status.ts b/apps/api/src/task/controllers/update-task-status.tsindex 3af1551d4..4a46dfac1 100644--- a/apps/api/src/task/controllers/update-task-status.ts+++ b/apps/api/src/task/controllers/update-task-status.ts@@ -2,14 +2,17 @@ import { and, eq } from "drizzle-orm";import { HTTPException } from "hono/http-exception";import db from "../../database";import { columnTable, taskTable } from "../../database/schema";+import { publishEvent } from "../../events";import { assertValidTaskStatus } from "../validate-task-fields";async function updateTaskStatus({id,status,+ currentUserId,}: {id: string;status: string;+ currentUserId: string;}) {const existingTask = await db.query.taskTable.findFirst({where: eq(taskTable.id, id),@@ -42,6 +45,17 @@ async function updateTaskStatus({});}+ await publishEvent("task.status_changed", {+ taskId: updatedTask.id,+ projectId: updatedTask.projectId,+ userId: currentUserId,+ oldStatus: existingTask.status,+ newStatus: status,+ title: updatedTask.title,+ assigneeId: updatedTask.userId,+ type: "status_changed",+ });+return updatedTask;}diff --git a/apps/api/src/task/controllers/update-task-title.ts b/apps/api/src/task/controllers/update-task-title.tsindex f32715bb0..be32bd097 100644--- a/apps/api/src/task/controllers/update-task-title.ts+++ b/apps/api/src/task/controllers/update-task-title.ts@@ -2,8 +2,17 @@ import { eq } from "drizzle-orm";import { HTTPException } from "hono/http-exception";import db from "../../database";import { taskTable } from "../../database/schema";+import { publishEvent } from "../../events";-async function updateTaskTitle({ id, title }: { id: string; title: string }) {+async function updateTaskTitle({+ id,+ title,+ currentUserId,+}: {+ id: string;+ title: string;+ currentUserId: string;+}) {const existingTask = await db.query.taskTable.findFirst({where: eq(taskTable.id, id),});@@ -26,6 +35,15 @@ async function updateTaskTitle({ id, title }: { id: string; title: string }) {});}+ await publishEvent("task.title_changed", {+ taskId: updatedTask.id,+ projectId: updatedTask.projectId,+ userId: currentUserId,+ oldTitle: existingTask.title,+ newTitle: title,+ type: "title_changed",+ });+return updatedTask;}diff --git a/apps/api/src/task/controllers/update-task.ts b/apps/api/src/task/controllers/update-task.tsindex 151f2d839..6ad3bf00a 100644--- a/apps/api/src/task/controllers/update-task.ts+++ b/apps/api/src/task/controllers/update-task.ts@@ -2,6 +2,7 @@ import { and, eq } from "drizzle-orm";import { HTTPException } from "hono/http-exception";import db from "../../database";import { columnTable, taskTable } from "../../database/schema";+import { publishEvent } from "../../events";import { assertValidTaskStatus } from "../validate-task-fields";async function updateTask(@@ -15,6 +16,7 @@ async function updateTask(priority: string,position: number,userId?: string,+ currentUserId?: string,) {const existingTask = await db.query.taskTable.findFirst({where: eq(taskTable.id, id),@@ -58,6 +60,25 @@ async function updateTask(});}+ if (existingTask.status !== status) {+ await publishEvent("task.status_changed", {+ taskId: updatedTask.id,+ projectId: updatedTask.projectId,+ userId: currentUserId,+ oldStatus: existingTask.status,+ newStatus: status,+ title: updatedTask.title,+ assigneeId: updatedTask.userId,+ type: "status_changed",+ });+ }++ await publishEvent("task.updated", {+ ...updatedTask,+ taskId: updatedTask.id,+ userId: currentUserId,+ });+return updatedTask;}diff --git a/apps/api/src/task/index.ts b/apps/api/src/task/index.tsindex 7c714073a..fd33a8ddc 100644--- a/apps/api/src/task/index.ts+++ b/apps/api/src/task/index.ts@@ -8,10 +8,8 @@ import {assetTable,projectTable,taskTable,- userTable,workspaceTable,} from "../database/schema";-import { publishEvent } from "../events";import { taskSchema } from "../schemas";import {assertTaskImageKeyMatchesContext,@@ -201,7 +199,8 @@ const task = new Hono<{const task = await createTask({projectId,- userId,+ currentUserId: c.get("userId"),+ userId: userId,title,description,startDate: startDate ? new Date(startDate) : undefined,@@ -273,13 +272,13 @@ const task = new Hono<{async (c) => {const { id } = c.req.valid("param");const { destinationProjectId, destinationStatus } = c.req.valid("json");- const userId = c.get("userId");+ const currentUserId = c.get("userId");const result = await moveTask({taskId: id,destinationProjectId,destinationStatus,- userId,+ currentUserId,});return c.json(result);@@ -318,9 +317,6 @@ const task = new Hono<{workspaceAccess.fromTask(),async (c) => {const { id } = c.req.valid("param");- const existingTask = await db.query.taskTable.findFirst({- where: eq(taskTable.id, id),- });const {title,description,@@ -333,9 +329,7 @@ const task = new Hono<{userId,} = c.req.valid("json");- if (!existingTask) {- throw new HTTPException(404, { message: "Task not found" });- }+ const currentUserId = c.get("userId");const task = await updateTask(id,@@ -348,22 +342,9 @@ const task = new Hono<{priority,position,userId,+ currentUserId,);- if (existingTask.status !== status) {- const user = c.get("userId");- await publishEvent("task.status_changed", {- taskId: task.id,- projectId: task.projectId,- userId: user,- oldStatus: existingTask.status,- newStatus: status,- title: task.title,- assigneeId: task.userId,- type: "status_changed",- });- }-return c.json(task);},)@@ -454,7 +435,8 @@ const task = new Hono<{async (c) => {const { id } = c.req.valid("param");- const task = await deleteTask(id);+ const currentUserId = c.get("userId");+ const task = await deleteTask(id, currentUserId);return c.json(task);},@@ -480,27 +462,9 @@ const task = new Hono<{async (c) => {const { id } = c.req.valid("param");const { status } = c.req.valid("json");- const user = c.get("userId");- const existingTask = await db.query.taskTable.findFirst({- where: eq(taskTable.id, id),- });-- if (!existingTask) {- throw new HTTPException(404, { message: "Task not found" });- }+ const currentUserId = c.get("userId");- const task = await updateTaskStatus({ id, status });-- await publishEvent("task.status_changed", {- taskId: task.id,- projectId: task.projectId,- userId: user,- oldStatus: existingTask.status,- newStatus: status,- title: task.title,- assigneeId: task.userId,- type: "status_changed",- });+ const task = await updateTaskStatus({ id, status, currentUserId });return c.json(task);},@@ -526,26 +490,9 @@ const task = new Hono<{async (c) => {const { id } = c.req.valid("param");const { priority } = c.req.valid("json");- const user = c.get("userId");- const existingTask = await db.query.taskTable.findFirst({- where: eq(taskTable.id, id),- });+ const currentUserId = c.get("userId");- if (!existingTask) {- throw new HTTPException(404, { message: "Task not found" });- }-- const task = await updateTaskPriority({ id, priority });-- await publishEvent("task.priority_changed", {- taskId: task.id,- projectId: task.projectId,- userId: user,- oldPriority: existingTask.priority,- newPriority: priority,- title: task.title,- type: "priority_changed",- });+ const task = await updateTaskPriority({ id, priority, currentUserId });return c.json(task);},@@ -571,45 +518,9 @@ const task = new Hono<{async (c) => {const { id } = c.req.valid("param");const { userId } = c.req.valid("json");- const user = c.get("userId");- const existingTask = await db.query.taskTable.findFirst({- where: eq(taskTable.id, id),- });-- if (!existingTask) {- throw new HTTPException(404, { message: "Task not found" });- }+ const currentUserId = c.get("userId");- const task = await updateTaskAssignee({ id, userId });- const newAssigneeName = userId- ? (- await db- .select({ name: userTable.name })- .from(userTable)- .where(eq(userTable.id, userId))- .limit(1)- )[0]?.name- : undefined;-- if (!userId) {- await publishEvent("task.unassigned", {- taskId: task.id,- userId: user,- title: task.title,- type: "unassigned",- });- return c.json(task);- }-- await publishEvent("task.assignee_changed", {- taskId: task.id,- userId: user,- oldAssignee: existingTask.userId,- newAssignee: newAssigneeName,- newAssigneeId: userId,- title: task.title,- type: "assignee_changed",- });+ const task = await updateTaskAssignee({ id, userId, currentUserId });return c.json(task);},@@ -635,27 +546,12 @@ const task = new Hono<{async (c) => {const { id } = c.req.valid("param");const { dueDate = null } = c.req.valid("json");- const user = c.get("userId");- const existingTask = await db.query.taskTable.findFirst({- where: eq(taskTable.id, id),- });-- if (!existingTask) {- throw new HTTPException(404, { message: "Task not found" });- }+ const currentUserId = c.get("userId");const task = await updateTaskDueDate({id,dueDate: dueDate ? new Date(dueDate) : null,- });-- await publishEvent("task.due_date_changed", {- taskId: task.id,- userId: user,- oldDueDate: existingTask.dueDate,- newDueDate: dueDate,- title: task.title,- type: "due_date_changed",+ currentUserId,});return c.json(task);@@ -683,27 +579,9 @@ const task = new Hono<{async (c) => {const { id } = c.req.valid("param");const { title } = c.req.valid("json");- const user = c.get("userId");+ const currentUserId = 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: existingTask.title,- newTitle: title,- type: "title_changed",- });+ const task = await updateTaskTitle({ id, title, currentUserId });return c.json(task);},@@ -937,26 +815,12 @@ const task = new Hono<{async (c) => {const { id } = c.req.valid("param");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),- });+ const currentUserId = c.get("userId");- 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,- oldDescription: existingTask.description,- newDescription: description,- type: "description_changed",+ const task = await updateTaskDescription({+ id,+ description,+ currentUserId,});return c.json(task);diff --git a/apps/api/src/ws/index.ts b/apps/api/src/ws/index.tsnew file mode 100644index 000000000..f39fe6f7e--- /dev/null+++ b/apps/api/src/ws/index.ts@@ -0,0 +1,191 @@+import type { WSContext } from "hono/ws";+import { subscribeToEvent } from "../events";++type ProjectConnection = {+ ws: WSContext;+ userId: string;+ initiatorId: string;+};++const projectConnections = new Map<string, Set<ProjectConnection>>();+const projectBroadcastQueues = new Map<+ string,+ Map<string, { message: Record<string, unknown>; excludeInitiatorId?: string }>+>();+const projectBroadcastTimeouts = new Map<+ string,+ ReturnType<typeof setTimeout>+>();++export function addConnection(+ projectId: string,+ ws: WSContext,+ userId: string,+ initiatorId: string,+) {+ if (!projectConnections.has(projectId)) {+ projectConnections.set(projectId, new Set());+ }+ const conn: ProjectConnection = { ws, userId, initiatorId };+ projectConnections.get(projectId)?.add(conn);+ return conn;+}++export function removeConnection(projectId: string, conn: ProjectConnection) {+ const connections = projectConnections.get(projectId);+ if (connections) {+ connections.delete(conn);+ if (connections.size === 0) {+ projectConnections.delete(projectId);+ }+ }+}++export function broadcastToProject(+ projectId: string,+ message: Record<string, unknown>,+ excludeInitiatorId?: string,+) {+ if (!projectBroadcastQueues.has(projectId)) {+ projectBroadcastQueues.set(projectId, new Map());+ }++ const messageKey = `${message.type}:${message.taskId || ""}:${message.sourceTaskId || ""}:${message.targetTaskId || ""}`;+ projectBroadcastQueues+ .get(projectId)+ ?.set(messageKey, { message, excludeInitiatorId });++ if (projectBroadcastTimeouts.has(projectId)) {+ return;+ }++ const timeout = setTimeout(() => {+ projectBroadcastTimeouts.delete(projectId);+ const queue = projectBroadcastQueues.get(projectId);+ projectBroadcastQueues.delete(projectId);++ const connections = projectConnections.get(projectId);+ if (!connections || !queue) return;++ for (const { message: msg, excludeInitiatorId: exId } of queue.values()) {+ const payload = JSON.stringify(msg);+ for (const conn of connections) {+ if (exId && conn.initiatorId === exId) continue;+ try {+ conn.ws.send(payload);+ } catch {+ // Connection might be closed, will be cleaned up on close event+ }+ }+ }+ }, 100);++ projectBroadcastTimeouts.set(projectId, timeout);+}++type TaskEvent = {+ id: string | undefined;+ projectId: string;+ userId: string;+ initiatorId?: string;+ taskId: string;+ sourceTaskId: string | undefined;+ targetTaskId: string | undefined;+};++const taskUpdateEvents = [+ "task.created",+ "task.updated",+ "task.deleted",+ "task.status_changed",+ "task.priority_changed",+ "task.unassigned",+ "task.assignee_changed",+ "task.due_date_changed",+ "task.title_changed",+ "task.description_changed",+ "task.label_assigned",+ "task.label_unassigned",+ "task.label_created",+ "task.label_deleted",+ "task-relation.created",+ "task-relation.deleted",+ "task.comment_created",+ "comment.created",+ "comment.deleted",+ "comment.updated",+];++subscribeToEvent<{+ taskId: string;+ userId: string;+ initiatorId?: string;+ type: string;+ content: string;+ fromProjectId: string;+ fromProjectName: string;+ toProjectId: string;+ toProjectName: string;+ oldStatus: string;+ newStatus: string;+}>("task.moved", async (data) => {+ const { fromProjectId, initiatorId, toProjectId, taskId } = data;++ broadcastToProject(+ toProjectId,+ { type: "TASK_MOVED", projectId: toProjectId, taskId },+ initiatorId,+ );+ broadcastToProject(+ fromProjectId,+ { type: "TASK_MOVED", projectId: fromProjectId, taskId },+ initiatorId,+ );+});++for (const eventName of taskUpdateEvents) {+ subscribeToEvent<TaskEvent>(eventName, async (data) => {+ console.log("Broadcasting task update event", eventName);+ const { projectId, initiatorId } = data;+ const taskId = data.taskId || data.id;+ let type: string;+ switch (eventName) {+ case "task.created":+ type = "TASK_CREATED";+ break;+ case "task.deleted":+ type = "TASK_DELETED";+ break;+ case "task-relation.created":+ case "task-relation.deleted":+ type = "TASK_RELATION_UPDATED";+ break;+ case "task.label_assigned":+ case "task.label_unassigned":+ case "task.label_created":+ case "task.label_deleted":+ type = "TASK_LABEL_UPDATED";+ break;+ case "task.comment_created":+ case "comment.created":+ case "comment.deleted":+ case "comment.updated":+ type = "COMMENT_UPDATED";+ break;+ default:+ type = "TASK_UPDATED";+ }++ broadcastToProject(+ projectId,+ {+ type,+ projectId,+ taskId: taskId,+ sourceTaskId: data.sourceTaskId,+ targetTaskId: data.targetTaskId,+ },+ initiatorId,+ );+ });+}diff --git a/apps/web/src/components/activity/index.tsx b/apps/web/src/components/activity/index.tsxindex cb8733d29..60edd1dc8 100644--- a/apps/web/src/components/activity/index.tsx+++ b/apps/web/src/components/activity/index.tsx@@ -379,6 +379,29 @@ function renderActivityContent({}}+ if (activity.type === "moved") {+ if (eventData) {+ return (+ <span className="text-sm text-muted-foreground">+ {t("activity:moved", {+ from: String(eventData.fromProjectName ?? ""),+ to: String(eventData.toProjectName ?? ""),+ })}+ </span>+ );+ }+ }++ if (activity.type === "created") {+ if (eventData) {+ return (+ <span className="text-sm text-muted-foreground">+ {t("activity:created")}+ </span>+ );+ }+ }+return (<span className="text-sm text-muted-foreground">{content || toDisplayCase(activity.type)}diff --git a/apps/web/src/components/common/project-layout.tsx b/apps/web/src/components/common/project-layout.tsxindex b6c1d4fb2..1d2702128 100644--- a/apps/web/src/components/common/project-layout.tsx+++ b/apps/web/src/components/common/project-layout.tsx@@ -17,6 +17,7 @@ import {} from "@/components/ui/tooltip";import { shortcuts } from "@/constants/shortcuts";import useGetProject from "@/hooks/queries/project/use-get-project";+import { useProjectWebSocket } from "@/hooks/use-project-websocket";import { cn } from "@/lib/cn";type ProjectLayoutProps = {@@ -42,6 +43,8 @@ export default function ProjectLayout({const [isCreateProjectModalOpen, setIsCreateProjectModalOpen] =useState(false);+ useProjectWebSocket(projectId);+const resolvedView =activeView ??(location.pathname.includes("/backlog")diff --git a/apps/web/src/components/common/task-layout.tsx b/apps/web/src/components/common/task-layout.tsxindex 552035ede..c4414fb1e 100644--- a/apps/web/src/components/common/task-layout.tsx+++ b/apps/web/src/components/common/task-layout.tsx@@ -14,6 +14,7 @@ import {import { shortcuts } from "@/constants/shortcuts";import useGetProject from "@/hooks/queries/project/use-get-project";import useGetTask from "@/hooks/queries/task/use-get-task";+import { useProjectWebSocket } from "@/hooks/use-project-websocket";type TaskLayoutProps = {taskId: string;@@ -36,6 +37,9 @@ export default function TaskLayout({const navigate = useNavigate();const { data: project } = useGetProject({ id: projectId, workspaceId });const { data: task } = useGetTask(taskId);++ useProjectWebSocket(projectId);+const taskLabel =project?.slug && task?.number != null? `${project.slug}-${task.number}`diff --git a/apps/web/src/hooks/use-project-websocket.ts b/apps/web/src/hooks/use-project-websocket.tsnew file mode 100644index 000000000..bde56cd6b--- /dev/null+++ b/apps/web/src/hooks/use-project-websocket.ts@@ -0,0 +1,115 @@+import { windowId } from "@kaneo/libs";+import { useQueryClient } from "@tanstack/react-query";+import { useEffect, useRef } from "react";+import { authClient } from "@/lib/auth-client";++function getWsUrl(projectId: string, userId: string | null | undefined) {+ const base = (+ import.meta.env.VITE_API_URL || "http://localhost:1337"+ ).replace(/\/+$/, "");+ const wsBase = base.replace(/^http/, "ws");+ return `${wsBase}/ws/${projectId}?userId=${userId}&windowId=${windowId}`;+}++const MAX_RETRIES = 5;+const BASE_DELAY = 1000; // 1 second++export function useProjectWebSocket(projectId: string) {+ const queryClient = useQueryClient();+ const { data: session } = authClient.useSession();+ const wsRef = useRef<WebSocket | null>(null);+ const retriesRef = useRef(0);+ const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);++ useEffect(() => {+ if (!projectId || !session?.user?.id) return;++ function connect() {+ const url = getWsUrl(projectId, session?.user?.id);+ const ws = new WebSocket(url);+ wsRef.current = ws;++ ws.onopen = () => {+ retriesRef.current = 0; // Reset retries on successful connection+ };++ ws.onmessage = (event) => {+ try {+ const message = JSON.parse(event.data);+ if (+ message.type === "TASK_UPDATED" ||+ message.type === "TASK_CREATED" ||+ message.type === "TASK_DELETED" ||+ message.type === "TASK_LABEL_UPDATED" ||+ message.type === "TASK_MOVED" ||+ message.type === "TASK_RELATION_UPDATED" ||+ message.type === "COMMENT_UPDATED"+ ) {+ queryClient.invalidateQueries({+ queryKey: ["tasks", message.projectId],+ });++ if (message.type === "TASK_RELATION_UPDATED") {+ if (message.sourceTaskId) {+ queryClient.invalidateQueries({+ queryKey: ["task", message.sourceTaskId],+ });+ queryClient.invalidateQueries({+ queryKey: ["task-relations", message.sourceTaskId],+ });+ }+ if (message.targetTaskId) {+ queryClient.invalidateQueries({+ queryKey: ["task", message.targetTaskId],+ });+ queryClient.invalidateQueries({+ queryKey: ["task-relations", message.targetTaskId],+ });+ }+ } else {+ queryClient.invalidateQueries({+ queryKey: ["task", message.taskId],+ });+ }++ if (message.type === "TASK_LABEL_UPDATED") {+ queryClient.invalidateQueries({+ queryKey: ["labels", message.taskId],+ });+ }++ if (message.type === "COMMENT_UPDATED") {+ queryClient.invalidateQueries({+ queryKey: ["activities", message.taskId],+ });+ queryClient.invalidateQueries({+ queryKey: ["comments", message.taskId],+ });+ }+ }+ } catch {+ // Ignore malformed messages+ }+ };++ ws.onclose = () => {+ wsRef.current = null;++ if (retriesRef.current < MAX_RETRIES) {+ const delay = BASE_DELAY * 2 ** retriesRef.current; // 1s, 2s, 4s, 8s, 16s+ retriesRef.current += 1;+ timeoutRef.current = setTimeout(connect, delay);+ }+ };+ }+ connect();++ return () => {+ retriesRef.current = MAX_RETRIES; // Prevent reconnect after unmount+ if (timeoutRef.current) {+ clearTimeout(timeoutRef.current);+ }+ wsRef.current?.close();+ };+ }, [projectId, session?.user?.id, queryClient]);+}diff --git a/i18n/de-DE.json b/i18n/de-DE.jsonindex ff2303e44..6381fb6a6 100644--- a/i18n/de-DE.json+++ b/i18n/de-DE.json@@ -1162,6 +1162,8 @@"setDueDate": "hat das Fälligkeitsdatum auf {{date}} gesetzt","changedDueDate": "hat das Fälligkeitsdatum von {{from}} zu {{to}} geändert","changedTitle": "hat den Titel von \"{{from}}\" zu \"{{to}}\" geändert",+ "moved": "hat die Aufgabe von \"{{from}}\" nach \"{{to}}\" verschoben",+ "created": "hat diese Aufgabe erstellt","githubUser": "GitHub-Benutzer","comment": {"github": "GitHub",@@ -1275,7 +1277,9 @@},"common": {"selectTask": "Aufgabe auswählen",- "loadingTask": "Aufgabe wird geladen..."+ "loadingTask": "Aufgabe wird geladen...",+ "taskNotFound": "Aufgabe nicht gefunden",+ "taskNotFoundDescription": "Die gesuchte Aufgabe existiert nicht oder wurde gelöscht."},"detail": {"subtaskOf": "Teilaufgabe von",diff --git a/i18n/el-GR.json b/i18n/el-GR.jsonindex 0bea0b260..feaef0f5b 100644--- a/i18n/el-GR.json+++ b/i18n/el-GR.json@@ -1160,6 +1160,8 @@"setDueDate": "όρισε ως ημερομηνία λήξης την {{date}}","changedDueDate": "άλλαξε την ημερομηνία λήξης από {{from}} σε {{to}}","changedTitle": "άλλαξε τον τίτλο από \"{{from}}\" σε \"{{to}}\"",+ "created": "δημιούργησε αυτή την εργασία",+ "moved": "μετακινήσει την εργασία από \"{{from}}\" σε \"{{to}}\"","githubUser": "Χρήστης GitHub","comment": {"github": "GitHub",@@ -1273,7 +1275,9 @@},"common": {"selectTask": "Επιλέξτε εργασία",- "loadingTask": "Φόρτωση εργασίας..."+ "loadingTask": "Φόρτωση εργασίας...",+ "taskNotFound": "Η εργασία δεν βρέθηκε",+ "taskNotFoundDescription": "Η εργασία που αναζητάτε δεν υπάρχει ή έχει διαγραφεί."},"detail": {"subtaskOf": "Υποεργασία του",diff --git a/i18n/en-US.json b/i18n/en-US.jsonindex b4813eadb..f25a10e7f 100644--- a/i18n/en-US.json+++ b/i18n/en-US.json@@ -1162,6 +1162,8 @@"setDueDate": "set due date to {{date}}","changedDueDate": "changed due date from {{from}} to {{to}}","changedTitle": "changed title from \"{{from}}\" to \"{{to}}\"",+ "moved": "moved task from \"{{from}}\" to \"{{to}}\"",+ "created": "created this task","githubUser": "GitHub User","comment": {"github": "GitHub",@@ -1275,7 +1277,9 @@},"common": {"selectTask": "Select task",- "loadingTask": "Loading task..."+ "loadingTask": "Loading task...",+ "taskNotFound": "Task not found",+ "taskNotFoundDescription": "The task you are looking for does not exist or has been deleted."},"detail": {"subtaskOf": "Subtask of",diff --git a/i18n/es-ES.json b/i18n/es-ES.jsonindex 72fa4f57f..acbf3ddd6 100644--- a/i18n/es-ES.json+++ b/i18n/es-ES.json@@ -945,6 +945,8 @@"setDueDate": "ha configurado la fecha de vencimiento a {{date}}","changedDueDate": "ha cambiado la fecha de vencimiento de {{from}} a {{to}}","changedTitle": "ha cambiado el título de \"{{from}}\" a \"{{to}}\"",+ "created": "ha creado esta tarea",+ "moved": "ha movido la tarea de \"{{from}}\" a \"{{to}}\"","githubUser": "Usuario de GitHub","comment": {"github": "GitHub",@@ -1058,7 +1060,9 @@},"common": {"selectTask": "Seleccionar tarea",- "loadingTask": "Cargando tarea..."+ "loadingTask": "Cargando tarea...",+ "taskNotFound": "Tarea no encontrada",+ "taskNotFoundDescription": "La tarea que busca no existe o ha sido eliminada."},"detail": {"subtaskOf": "Subtarea de",diff --git a/i18n/fr-FR.json b/i18n/fr-FR.jsonindex c048f4b2c..d44c245c0 100644--- a/i18n/fr-FR.json+++ b/i18n/fr-FR.json@@ -1160,6 +1160,8 @@"setDueDate": "a défini la date d'échéance à {{date}}","changedDueDate": "a changé la date d'échéance de {{from}} à {{to}}","changedTitle": "a changé le titre de \"{{from}}\" à \"{{to}}\"",+ "created": "a créé cette tâche",+ "moved": "a déplacé la tâche de \"{{from}}\" à \"{{to}}\"","githubUser": "GitHub User","comment": {"github": "GitHub",@@ -1273,7 +1275,9 @@},"common": {"selectTask": "Sélectionner une tâche",- "loadingTask": "Chargement de la tâche..."+ "loadingTask": "Chargement de la tâche...",+ "taskNotFound": "Tâche non trouvée",+ "taskNotFoundDescription": "La tâche que vous recherchez n'existe pas ou a été supprimée."},"detail": {"subtaskOf": "Sous-tâche de",diff --git a/i18n/mk-MK.json b/i18n/mk-MK.jsonindex 738edcc23..73c58a047 100644--- a/i18n/mk-MK.json+++ b/i18n/mk-MK.json@@ -1160,6 +1160,8 @@"setDueDate": "го постави краениот рок на {{date}}","changedDueDate": "го промени краениот рок од {{from}} во {{to}}","changedTitle": "го промени насловот од \"{{from}}\" во \"{{to}}\"",+ "created": "ја создаде задачата",+ "moved": "ја премести задачата од \"{{from}}\" во \"{{to}}\"","githubUser": "GitHub корисник","comment": {"github": "GitHub",@@ -1273,7 +1275,9 @@},"common": {"selectTask": "Избери задача",- "loadingTask": "Се вчитува задача..."+ "loadingTask": "Се вчитува задача...",+ "taskNotFound": "Задачата не е пронајдена",+ "taskNotFoundDescription": "Задачата што ја барате не постои или е избришана."},"detail": {"subtaskOf": "Подзадача на",diff --git a/i18n/nl-NL.json b/i18n/nl-NL.jsonindex 47741cd76..e03821e8f 100644--- a/i18n/nl-NL.json+++ b/i18n/nl-NL.json@@ -946,6 +946,8 @@"setDueDate": "heeft de einddatum ingesteld op {{date}}","changedDueDate": "heeft de einddatum gewijzigd van {{from}} naar {{to}}","changedTitle": "heeft de titel gewijzigd van \"{{from}}\" naar \"{{to}}\"",+ "created": "heeft deze taak aangemaakt",+ "moved": "heeft de taak van \"{{from}}\" naar \"{{to}}\" verplaatst","githubUser": "GitHub-gebruiker","comment": {"github": "GitHub",@@ -1059,7 +1061,9 @@},"common": {"selectTask": "Selecteer taak",- "loadingTask": "Taak laden..."+ "loadingTask": "Taak laden...",+ "taskNotFound": "Taak niet gevonden",+ "taskNotFoundDescription": "De taak die u zoekt bestaat niet of is verwijderd."},"detail": {"subtaskOf": "Subtaak van",diff --git a/packages/libs/src/hono.ts b/packages/libs/src/hono.tsindex 5ee8d92ae..237900930 100644--- a/packages/libs/src/hono.ts+++ b/packages/libs/src/hono.ts@@ -6,6 +6,9 @@ import { resolveApiBaseUrl } from "./api-url";const apiUrl = resolveApiBaseUrl(import.meta.env.VITE_API_URL);+// Generate once per tab load+export const windowId = Math.random().toString(36).substring(2, 11);+export const client = hc<AppType>(apiUrl, {fetch: (input: RequestInfo | URL, init?: RequestInit) => {return fetch(input, {@@ -13,6 +16,7 @@ export const client = hc<AppType>(apiUrl, {headers: {...init?.headers,"Content-Type": "application/json",+ "X-Kaneo-Window-Id": windowId,},credentials: "include",}).catch((error) => {diff --git a/packages/libs/src/index.ts b/packages/libs/src/index.tsindex 496d10b5c..6e9808eb8 100644--- a/packages/libs/src/index.ts+++ b/packages/libs/src/index.ts@@ -1,2 +1,2 @@export { resolveApiBaseUrl } from "./api-url";-export { client } from "./hono";+export { client, windowId } from "./hono";diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex c015a42b5..718ab6d1f 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -78,6 +78,9 @@ importers:'@hono/node-server':specifier: 1.19.10version: 1.19.10([email protected])+ '@hono/node-ws':+ specifier: ^1.3.0'@hono/standard-validator':specifier: ^0.2.2version: 0.2.2(@standard-schema/[email protected])([email protected])@@ -1521,6 +1524,13 @@ packages:peerDependencies:hono: 4.12.7+ '@hono/[email protected]':+ resolution: {integrity: sha512-ju25YbbvLuXdqBCmLZLqnNYu1nbHIQjoyUqA8ApZOeL1k4skuiTcw5SW77/5SUYo2Xi2NVBJoVlfQurnKEp03Q==}+ engines: {node: '>=18.14.1'}+ peerDependencies:+ '@hono/node-server': 1.19.10+ hono: 4.12.7+'@hono/[email protected]':resolution: {integrity: sha512-mJ7W84Bt/rSvoIl63Ynew+UZOHAzzRAoAXb3JaWuxAkM/Lzg+ZHTCUiz77KOtn2e623WNN8LkD57Dk0szqUrIw==}peerDependencies:@@ -9026,6 +9036,15 @@ snapshots:dependencies:hono: 4.12.7+ dependencies:+ '@hono/node-server': 1.19.10([email protected])+ hono: 4.12.7+ ws: 8.17.1+ transitivePeerDependencies:+ - bufferutil+ - utf-8-validate+dependencies:'@standard-schema/spec': 1.1.0