⚡ 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(notifications): notification inbox with real-time WebSocket updates (#1324)
shockalotti3c09c5bb4231
diff --git a/apps/api/src/index.ts b/apps/api/src/index.tsindex b2e874c45..1d2c7c8f5 100644--- a/apps/api/src/index.ts+++ b/apps/api/src/index.ts@@ -77,8 +77,10 @@ import workflowRule from "./workflow-rule";import workspace from "./workspace";import {addConnection,+ addUserConnection,initializeWebSocketAdapter,removeConnection,+ removeUserConnection,shutdownWebSocketAdapter,} from "./ws";@@ -545,6 +547,57 @@ export function createApp() {),);+ // User-scoped WebSocket endpoint — MUST be registered before /ws/:projectId+ // so the literal path "user" isn't consumed by the param route.+ api.get(+ "/ws/user",+ upgradeWebSocket(async (c) => {+ try {+ await authenticateApiRequest(c);+ } catch (error) {+ if (error instanceof HTTPException) {+ throw error;+ }+ console.error("API authentication failed:", error);+ throw new HTTPException(500, { message: "Internal Server Error" });+ }++ const userId = c.get("userId");+ let conn: ReturnType<typeof addUserConnection> | null = null;++ return {+ onOpen(_evt, ws) {+ if (userId) {+ conn = addUserConnection(userId, ws);+ }+ },+ onMessage(evt) {+ try {+ const raw =+ typeof evt.data === "string"+ ? evt.data+ : Buffer.isBuffer(evt.data)+ ? evt.data.toString()+ : null;+ if (raw) {+ const msg = JSON.parse(raw) as { type?: string };+ if (msg?.type === "ping") {+ // keepalive — no-op+ }+ }+ } catch {+ // Ignore malformed messages+ }+ },+ onClose() {+ if (conn && userId) {+ removeUserConnection(userId, conn);+ }+ },+ };+ }),+ );+api.get("/ws/:projectId",upgradeWebSocket(async (c) => {diff --git a/apps/api/src/notification/controllers/get-notifications.ts b/apps/api/src/notification/controllers/get-notifications.tsindex f100b9f00..e79159d7a 100644--- a/apps/api/src/notification/controllers/get-notifications.ts+++ b/apps/api/src/notification/controllers/get-notifications.ts@@ -1,16 +1,54 @@-import { desc, eq } from "drizzle-orm";+import { and, desc, eq } from "drizzle-orm";import db from "../../database";-import { notificationTable } from "../../database/schema";+import {+ notificationTable,+ projectTable,+ taskTable,+ workspaceTable,+} from "../../database/schema";async function getNotifications(userId: string) {- const notifications = await db- .select()+ const rows = await db+ .select({+ notification: notificationTable,+ projectId: projectTable.id,+ workspaceId: workspaceTable.id,+ }).from(notificationTable)+ .leftJoin(+ taskTable,+ and(+ eq(notificationTable.resourceId, taskTable.id),+ eq(notificationTable.resourceType, "task"),+ ),+ )+ .leftJoin(projectTable, eq(taskTable.projectId, projectTable.id))+ .leftJoin(workspaceTable, eq(projectTable.workspaceId, workspaceTable.id)).where(eq(notificationTable.userId, userId)).orderBy(desc(notificationTable.createdAt)).limit(50);- return notifications;+ return rows.map(({ notification, projectId, workspaceId }) => {+ if (!projectId && !workspaceId) {+ return notification;+ }++ const existing =+ notification.eventData &&+ typeof notification.eventData === "object" &&+ !Array.isArray(notification.eventData)+ ? (notification.eventData as Record<string, unknown>)+ : {};++ return {+ ...notification,+ eventData: {+ ...existing,+ projectId: projectId ?? existing.projectId ?? null,+ workspaceId: workspaceId ?? existing.workspaceId ?? null,+ },+ };+ });}export default getNotifications;diff --git a/apps/api/src/notification/index.ts b/apps/api/src/notification/index.tsindex 43ac67a25..29515cb91 100644--- a/apps/api/src/notification/index.ts+++ b/apps/api/src/notification/index.ts@@ -1,6 +1,9 @@+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 { projectTable, taskTable } from "../database/schema";import { subscribeToEvent } from "../events";import { notificationSchema } from "../schemas";import clearNotifications from "./controllers/clear-notifications";@@ -163,11 +166,19 @@ subscribeToEvent<{projectId: string;}>("task.created", async (data) => {if (data.userId) {+ const [project] = await db+ .select({ workspaceId: projectTable.workspaceId })+ .from(projectTable)+ .where(eq(projectTable.id, data.projectId))+ .limit(1);+await createNotification({userId: data.userId,type: "task_created",eventData: {taskTitle: data.title,+ projectId: data.projectId,+ workspaceId: project?.workspaceId ?? null,},resourceId: data.taskId,resourceType: "task",@@ -203,6 +214,20 @@ subscribeToEvent<{assigneeId?: string;}>("task.status_changed", async (data) => {if (data.assigneeId && data.assigneeId !== data.userId) {+ const [task] = await db+ .select({ projectId: taskTable.projectId })+ .from(taskTable)+ .where(eq(taskTable.id, data.taskId))+ .limit(1);++ const [project] = task+ ? await db+ .select({ workspaceId: projectTable.workspaceId })+ .from(projectTable)+ .where(eq(projectTable.id, task.projectId))+ .limit(1)+ : [];+await createNotification({userId: data.assigneeId,type: "task_status_changed",@@ -210,6 +235,8 @@ subscribeToEvent<{taskTitle: data.title,oldStatus: data.oldStatus,newStatus: data.newStatus,+ projectId: task?.projectId ?? null,+ workspaceId: project?.workspaceId ?? null,},resourceId: data.taskId,resourceType: "task",@@ -226,11 +253,27 @@ subscribeToEvent<{title: string;}>("task.assignee_changed", async (data) => {if (data.newAssigneeId) {+ const [task] = await db+ .select({ projectId: taskTable.projectId })+ .from(taskTable)+ .where(eq(taskTable.id, data.taskId))+ .limit(1);++ const [project] = task+ ? await db+ .select({ workspaceId: projectTable.workspaceId })+ .from(projectTable)+ .where(eq(projectTable.id, task.projectId))+ .limit(1)+ : [];+await createNotification({userId: data.newAssigneeId,type: "task_assignee_changed",eventData: {taskTitle: data.title,+ projectId: task?.projectId ?? null,+ workspaceId: project?.workspaceId ?? null,},resourceId: data.taskId,resourceType: "task",@@ -246,11 +289,27 @@ subscribeToEvent<{taskTitle?: string;}>("time-entry.created", async (data) => {if (data.taskOwnerId && data.taskOwnerId !== data.userId) {+ const [task] = await db+ .select({ projectId: taskTable.projectId })+ .from(taskTable)+ .where(eq(taskTable.id, data.taskId))+ .limit(1);++ const [project] = task+ ? await db+ .select({ workspaceId: projectTable.workspaceId })+ .from(projectTable)+ .where(eq(projectTable.id, task.projectId))+ .limit(1)+ : [];+await createNotification({userId: data.taskOwnerId,type: "time_entry_created",eventData: {taskTitle: data.taskTitle ?? null,+ projectId: task?.projectId ?? null,+ workspaceId: project?.workspaceId ?? null,},resourceId: data.taskId,resourceType: "task",diff --git a/apps/api/src/schemas.ts b/apps/api/src/schemas.tsindex 0445cdd89..74f3c5783 100644--- a/apps/api/src/schemas.ts+++ b/apps/api/src/schemas.ts@@ -93,6 +93,7 @@ export const notificationSchema = v.object({"time_entry_created","due_date_reminder","task_overdue",+ "task_mention",] as const),eventData: v.nullable(v.record(v.string(), v.unknown())),isRead: v.optional(v.boolean()),diff --git a/apps/api/src/ws/index.ts b/apps/api/src/ws/index.tsindex e67b2551b..49667a4fb 100644--- a/apps/api/src/ws/index.ts+++ b/apps/api/src/ws/index.ts@@ -15,6 +15,55 @@ type ProjectConnection = {initiatorId: string;};+type UserConnection = {+ ws: WSContext;+};++/**+ * User-scoped connections — tracks WebSocket connections keyed by userId.+ * Used for delivering user-targeted events like NOTIFICATION_CREATED.+ */+const userConnections = new Map<string, Set<UserConnection>>();++export function addUserConnection(userId: string, ws: WSContext) {+ if (!userConnections.has(userId)) {+ userConnections.set(userId, new Set());+ }+ const conn: UserConnection = { ws };+ userConnections.get(userId)?.add(conn);+ return conn;+}++export function removeUserConnection(userId: string, conn: UserConnection) {+ const connections = userConnections.get(userId);+ if (connections) {+ connections.delete(conn);+ if (connections.size === 0) {+ userConnections.delete(userId);+ }+ }+}++export function broadcastToUser(+ userId: string,+ message: { type: string; [key: string]: unknown },+) {+ const connections = userConnections.get(userId);+ if (!connections) return;++ const payload = JSON.stringify(message);+ for (const conn of connections) {+ try {+ conn.ws.send(payload);+ } catch {+ connections.delete(conn);+ }+ }+ if (connections.size === 0) {+ userConnections.delete(userId);+ }+}+/*** Local connections — Each instance tracks only its own WebSocket connections.*/@@ -261,6 +310,15 @@ subscribeToEvent<{);});+subscribeToEvent<{ notificationId: string; userId: string }>(+ "notification.created",+ async (data) => {+ if (data.userId) {+ broadcastToUser(data.userId, { type: "NOTIFICATION_CREATED" });+ }+ },+);+for (const eventName of taskUpdateEvents) {subscribeToEvent<TaskEvent>(eventName, async (data) => {const { projectId, initiatorId } = data;diff --git a/apps/web/src/components/notification/notification-dropdown.tsx b/apps/web/src/components/notification/notification-dropdown.tsxindex baa93d7fd..044256cfd 100644--- a/apps/web/src/components/notification/notification-dropdown.tsx+++ b/apps/web/src/components/notification/notification-dropdown.tsx@@ -1,5 +1,6 @@+import { useNavigate } from "@tanstack/react-router";import { Bell } from "lucide-react";-import { forwardRef, useImperativeHandle, useState } from "react";+import { forwardRef, useCallback, useImperativeHandle, useState } from "react";import { useTranslation } from "react-i18next";import {AlertDialog,@@ -16,6 +17,7 @@ import { KbdSequence } from "@/components/ui/kbd";import {DropdownMenu,DropdownMenuContent,+ DropdownMenuItem,DropdownMenuTrigger,} from "@/components/ui/menu";import {@@ -27,6 +29,7 @@ import {import { shortcuts } from "@/constants/shortcuts";import useClearNotifications from "@/hooks/mutations/notification/use-clear-notifications";import useMarkAllNotificationsAsRead from "@/hooks/mutations/notification/use-mark-all-notifications-as-read";+import useMarkNotificationAsRead from "@/hooks/mutations/notification/use-mark-notification-as-read";import useGetNotifications from "@/hooks/queries/notification/use-get-notifications";import { useRegisterShortcuts } from "@/hooks/use-keyboard-shortcuts";import { cn } from "@/lib/cn";@@ -80,6 +83,11 @@ function getNotificationTitle(...eventData,defaultValue: notification.title ?? notification.type,});+ case "task_mention":+ return t("notifications:events.task_mention.title", {+ ...eventData,+ defaultValue: notification.title ?? notification.type,+ });default:break;}@@ -127,6 +135,11 @@ function getNotificationContent(...eventData,defaultValue: notification.content ?? "",});+ case "task_mention":+ return t("notifications:events.task_mention.content", {+ ...eventData,+ defaultValue: notification.content ?? "",+ });default:break;}@@ -138,12 +151,42 @@ function getNotificationContent(const NotificationDropdown = forwardRef<NotificationDropdownRef>((_props, ref) => {const { t } = useTranslation();+ const navigate = useNavigate();const { data: notifications } = useGetNotifications();const [isOpen, setIsOpen] = useState(false);const [showClearDialog, setShowClearDialog] = useState(false);const { mutate: markAllAsRead } = useMarkAllNotificationsAsRead();const { mutate: clearAll } = useClearNotifications();+ const { mutate: markAsRead } = useMarkNotificationAsRead();++ const handleNotificationClick = useCallback(+ (notification: Notification) => {+ if (!notification.isRead) {+ markAsRead(notification.id);+ }++ const ed = getEventDataRecord(notification.eventData);+ const workspaceId =+ typeof ed?.workspaceId === "string" ? ed.workspaceId : null;+ const projectId =+ typeof ed?.projectId === "string" ? ed.projectId : null;+ const taskId = notification.resourceId ?? null;++ if (+ notification.resourceType === "task" &&+ workspaceId &&+ projectId &&+ taskId+ ) {+ navigate({+ to: "/dashboard/workspace/$workspaceId/project/$projectId/task/$taskId",+ params: { workspaceId, projectId, taskId },+ });+ }+ },+ [markAsRead, navigate],+ );const unreadNotifications = notifications?.filter((n) => !n.isRead) || [];const hasNotifications = notifications && notifications.length > 0;@@ -179,7 +222,11 @@ const NotificationDropdown = forwardRef<NotificationDropdownRef>(><Bell className="h-4 w-4" />{unreadNotifications.length > 0 && (- <span className="absolute top-0 right-0 h-2 w-2 rounded-full bg-destructive" />+ <span className="absolute -top-1 -right-1 flex h-4 min-w-4 items-center justify-center rounded-full bg-destructive px-0.5 text-[10px] font-bold leading-none text-white">+ {unreadNotifications.length > 99+ ? "99+"+ : unreadNotifications.length}+ </span>)}<span className="sr-only">{t("navigation:notifications")}@@ -207,21 +254,11 @@ const NotificationDropdown = forwardRef<NotificationDropdownRef>({t("notifications:title")}</h3>{unreadNotifications.length > 0 && (- <div className="flex items-center gap-2">- <Badge variant="secondary" className="text-xs">- {t("notifications:newCount", {- count: unreadNotifications.length,- })}- </Badge>- <Button- variant="ghost"- size="sm"- onClick={() => markAllAsRead()}- className="text-xs h-6 px-2"- >- {t("common:actions.markAllRead")}- </Button>- </div>+ <Badge variant="secondary" className="text-xs">+ {t("notifications:newCount", {+ count: unreadNotifications.length,+ })}+ </Badge>)}</div>@@ -236,10 +273,11 @@ const NotificationDropdown = forwardRef<NotificationDropdownRef>(</div>) : (notifications.map((notification) => (- <div+ <DropdownMenuItemkey={notification.id}+ onClick={() => handleNotificationClick(notification)}className={cn(- "px-3 py-3 border-b border-border/50 hover:bg-accent/50 transition-colors",+ "px-3 py-3 border-b border-border/50 rounded-none cursor-pointer",!notification.isRead && "bg-accent/20",)}>@@ -263,17 +301,26 @@ const NotificationDropdown = forwardRef<NotificationDropdownRef>(</p></div></div>- </div>+ </DropdownMenuItem>)))}</div>{hasNotifications && (- <div className="border-t border-border p-2">+ <div className="border-t border-border p-2 flex gap-1">+ <Button+ variant="ghost"+ size="sm"+ onClick={() => markAllAsRead()}+ disabled={unreadNotifications.length === 0}+ className="flex-1 text-xs"+ >+ {t("common:actions.markAllRead")}+ </Button><Buttonvariant="ghost"size="sm"onClick={() => setShowClearDialog(true)}- className="w-full text-xs text-destructive hover:text-destructive hover:bg-destructive/10"+ className="flex-1 text-xs text-destructive hover:text-destructive hover:bg-destructive/10">{t("notifications:clearAll")}</Button>diff --git a/apps/web/src/components/workspace-switcher.tsx b/apps/web/src/components/workspace-switcher.tsxindex c274ff000..5b7d2ae82 100644--- a/apps/web/src/components/workspace-switcher.tsx+++ b/apps/web/src/components/workspace-switcher.tsx@@ -2,7 +2,7 @@ import { useNavigate } from "@tanstack/react-router";import { ChevronDown } from "lucide-react";import * as React from "react";import { useTranslation } from "react-i18next";-+import NotificationDropdown from "@/components/notification/notification-dropdown";import {DropdownMenu,DropdownMenuContent,@@ -26,6 +26,7 @@ import {getModifierKeyText,useRegisterShortcuts,} from "@/hooks/use-keyboard-shortcuts";+import { useUserWebSocket } from "@/hooks/use-user-websocket";import { authClient } from "@/lib/auth-client";import type { Workspace } from "@/types/workspace";import CreateWorkspaceModal from "./shared/modals/create-workspace-modal";@@ -33,6 +34,9 @@ import CreateWorkspaceModal from "./shared/modals/create-workspace-modal";export function WorkspaceSwitcher() {const { t } = useTranslation();const { data: workspace } = useActiveWorkspace();++ // User-scoped WebSocket for real-time events (e.g. NOTIFICATION_CREATED)+ useUserWebSocket();const { data: workspaces } = useGetWorkspaces();const navigate = useNavigate();const [isOpen, setIsOpen] = React.useState(false);@@ -183,8 +187,11 @@ export function WorkspaceSwitcher() {</SidebarMenuItem></SidebarMenu>- <div className="h-7 w-7 shrink-0">- <UserAvatar />+ <div className="flex items-center gap-1">+ <NotificationDropdown />+ <div className="h-7 w-7 shrink-0">+ <UserAvatar />+ </div></div></div>diff --git a/apps/web/src/hooks/use-user-websocket.ts b/apps/web/src/hooks/use-user-websocket.tsnew file mode 100644index 000000000..bb5a619b2--- /dev/null+++ b/apps/web/src/hooks/use-user-websocket.ts@@ -0,0 +1,93 @@+import { windowId } from "@kaneo/libs";+import { useQueryClient } from "@tanstack/react-query";+import { useEffect, useRef } from "react";+import { getApiUrl } from "@/fetchers/get-api-url";+import { authClient } from "@/lib/auth-client";++export function getUserWsUrl() {+ const base = getApiUrl("ws");+ const wsBase = base.replace(/^http/, "ws");+ return `${wsBase}/user?windowId=${encodeURIComponent(windowId)}`;+}++const MAX_RETRIES = 5;+const BASE_DELAY = 1000;+const WS_PING_INTERVAL_MS = 30_000;++/**+ * Maintains a user-scoped WebSocket connection for receiving user-targeted+ * real-time events (e.g. NOTIFICATION_CREATED). Invalidates TanStack Query+ * caches as needed — no polling required.+ */+export function useUserWebSocket() {+ 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);+ const pingIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);++ useEffect(() => {+ if (!session?.user?.id) return;++ retriesRef.current = 0;++ function clearPing() {+ if (pingIntervalRef.current) {+ clearInterval(pingIntervalRef.current);+ pingIntervalRef.current = null;+ }+ }++ function connect() {+ const url = getUserWsUrl();+ const ws = new WebSocket(url);+ wsRef.current = ws;++ ws.onopen = () => {+ retriesRef.current = 0;+ clearPing();+ pingIntervalRef.current = setInterval(() => {+ if (ws.readyState === WebSocket.OPEN) {+ ws.send(JSON.stringify({ type: "ping" }));+ }+ }, WS_PING_INTERVAL_MS);+ };++ ws.onmessage = (event) => {+ try {+ const message = JSON.parse(event.data as string) as {+ type?: string;+ };+ if (message.type === "NOTIFICATION_CREATED") {+ queryClient.invalidateQueries({ queryKey: ["notifications"] });+ }+ } catch {+ // Ignore malformed messages+ }+ };++ ws.onclose = () => {+ clearPing();+ wsRef.current = null;++ if (retriesRef.current < MAX_RETRIES) {+ const delay = BASE_DELAY * 2 ** retriesRef.current;+ retriesRef.current += 1;+ timeoutRef.current = setTimeout(connect, delay);+ }+ };+ }++ connect();++ return () => {+ retriesRef.current = MAX_RETRIES; // prevent reconnect after unmount+ clearPing();+ if (timeoutRef.current) {+ clearTimeout(timeoutRef.current);+ }+ wsRef.current?.close();+ };+ }, [session?.user?.id, queryClient]);+}