From 4278c045870cd22ce537f5ba3e7b6df84fe8582b Mon Sep 17 00:00:00 2001 From: yassinedorbozgithub Date: Mon, 27 Jan 2025 12:13:02 +0100 Subject: [PATCH 01/49] fix(frontend): disconnect from ws on logout --- frontend/src/contexts/auth.context.tsx | 14 ++++++ frontend/src/hooks/entities/auth-hooks.ts | 5 +++ frontend/src/hooks/useBroadcastChannel.ts | 55 +++++++++++++++++++++++ 3 files changed, 74 insertions(+) create mode 100644 frontend/src/hooks/useBroadcastChannel.ts diff --git a/frontend/src/contexts/auth.context.tsx b/frontend/src/contexts/auth.context.tsx index a2faf186..a3d27ace 100644 --- a/frontend/src/contexts/auth.context.tsx +++ b/frontend/src/contexts/auth.context.tsx @@ -21,6 +21,11 @@ import { Progress } from "@/app-components/displays/Progress"; import { useLogout } from "@/hooks/entities/auth-hooks"; import { useApiClient } from "@/hooks/useApiClient"; import { CURRENT_USER_KEY, PUBLIC_PATHS } from "@/hooks/useAuth"; +import { + EBCEvent, + ETabMode, + useBroadcastChannel, +} from "@/hooks/useBroadcastChannel"; import { useTranslate } from "@/hooks/useTranslate"; import { RouterType } from "@/services/types"; import { IUser } from "@/types/user.types"; @@ -59,6 +64,9 @@ export const AuthProvider = ({ children }: AuthProviderProps): JSX.Element => { i18n.changeLanguage(lang); }; const { mutate: logoutSession } = useLogout(); + const { mode, value } = useBroadcastChannel({ + channelName: "websocket-session", + }); const logout = async () => { updateLanguage(publicRuntimeConfig.lang.default); logoutSession(); @@ -107,6 +115,12 @@ export const AuthProvider = ({ children }: AuthProviderProps): JSX.Element => { setIsReady(true); }, []); + useEffect(() => { + if (value === EBCEvent.LOGOUT_END_SESSION && mode === ETabMode.SECONDARY) { + router.reload(); + } + }, [value, mode, router]); + if (!isReady || isLoading) return ; return ( diff --git a/frontend/src/hooks/entities/auth-hooks.ts b/frontend/src/hooks/entities/auth-hooks.ts index e3a1b07b..b655b3b7 100755 --- a/frontend/src/hooks/entities/auth-hooks.ts +++ b/frontend/src/hooks/entities/auth-hooks.ts @@ -22,6 +22,7 @@ import { useSocket } from "@/websocket/socket-hooks"; import { useFind } from "../crud/useFind"; import { useApiClient } from "../useApiClient"; import { CURRENT_USER_KEY, useAuth, useLogoutRedirection } from "../useAuth"; +import { EBCEvent, useBroadcastChannel } from "../useBroadcastChannel"; import { useToast } from "../useToast"; import { useTranslate } from "../useTranslate"; @@ -58,6 +59,9 @@ export const useLogout = ( const { logoutRedirection } = useLogoutRedirection(); const { toast } = useToast(); const { t } = useTranslate(); + const { send } = useBroadcastChannel({ + channelName: "websocket-session", + }); return useMutation({ ...options, @@ -67,6 +71,7 @@ export const useLogout = ( return await apiClient.logout(); }, onSuccess: async () => { + send(EBCEvent.LOGOUT_END_SESSION); queryClient.removeQueries([CURRENT_USER_KEY]); await logoutRedirection(); toast.success(t("message.logout_success")); diff --git a/frontend/src/hooks/useBroadcastChannel.ts b/frontend/src/hooks/useBroadcastChannel.ts new file mode 100644 index 00000000..0ec4f1a3 --- /dev/null +++ b/frontend/src/hooks/useBroadcastChannel.ts @@ -0,0 +1,55 @@ +/* + * Copyright © 2025 Hexastack. All rights reserved. + * + * Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms: + * 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission. + * 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file). + */ + +import { useEffect, useMemo, useState } from "react"; + +export enum ETabMode { + PRIMARY = "primary", + SECONDARY = "secondary", +} + +export enum EBCEvent { + LOGOUT_END_SESSION = "logout-end-session", +} + +export const useBroadcastChannel = ({ + channelName, + initialValue, +}: { + channelName: string; + initialValue?: EBCEvent; +}) => { + const [value, setValue] = useState(initialValue); + const [mode, setMode] = useState(ETabMode.PRIMARY); + const channel = useMemo( + () => new BroadcastChannel(channelName), + [channelName], + ); + + useEffect(() => { + channel.onmessage = (event) => { + if (mode === ETabMode.PRIMARY) { + setValue(event.data); + setMode(ETabMode.SECONDARY); + } + }; + + channel.postMessage(initialValue); + + return () => { + channel.close(); + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [channel, channelName, initialValue]); + + const send = (data?: EBCEvent) => { + channel?.postMessage(data); + }; + + return { mode, value, send }; +}; From 7f45fc8d396e2bf57627442d3987c19e86ec082c Mon Sep 17 00:00:00 2001 From: yassinedorbozgithub Date: Mon, 27 Jan 2025 16:08:38 +0100 Subject: [PATCH 02/49] fix: apply feedback update --- frontend/src/hooks/entities/auth-hooks.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/src/hooks/entities/auth-hooks.ts b/frontend/src/hooks/entities/auth-hooks.ts index b655b3b7..8dd9d783 100755 --- a/frontend/src/hooks/entities/auth-hooks.ts +++ b/frontend/src/hooks/entities/auth-hooks.ts @@ -71,8 +71,8 @@ export const useLogout = ( return await apiClient.logout(); }, onSuccess: async () => { - send(EBCEvent.LOGOUT_END_SESSION); queryClient.removeQueries([CURRENT_USER_KEY]); + send(EBCEvent.LOGOUT_END_SESSION); await logoutRedirection(); toast.success(t("message.logout_success")); }, From b46bda0a07dbf36a1b6d31ab872c88539bbe7f74 Mon Sep 17 00:00:00 2001 From: yassinedorbozgithub Date: Mon, 27 Jan 2025 16:11:33 +0100 Subject: [PATCH 03/49] fix: apply feedback update --- frontend/src/hooks/useBroadcastChannel.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/src/hooks/useBroadcastChannel.ts b/frontend/src/hooks/useBroadcastChannel.ts index 0ec4f1a3..f4e74628 100644 --- a/frontend/src/hooks/useBroadcastChannel.ts +++ b/frontend/src/hooks/useBroadcastChannel.ts @@ -47,7 +47,7 @@ export const useBroadcastChannel = ({ // eslint-disable-next-line react-hooks/exhaustive-deps }, [channel, channelName, initialValue]); - const send = (data?: EBCEvent) => { + const send = (data: EBCEvent) => { channel?.postMessage(data); }; From efc512e2625bd531baee5301c372537399f83dc9 Mon Sep 17 00:00:00 2001 From: yassinedorbozgithub Date: Mon, 27 Jan 2025 16:27:06 +0100 Subject: [PATCH 04/49] fix: apply feedback update --- frontend/src/hooks/useBroadcastChannel.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/src/hooks/useBroadcastChannel.ts b/frontend/src/hooks/useBroadcastChannel.ts index f4e74628..66a30582 100644 --- a/frontend/src/hooks/useBroadcastChannel.ts +++ b/frontend/src/hooks/useBroadcastChannel.ts @@ -48,7 +48,7 @@ export const useBroadcastChannel = ({ }, [channel, channelName, initialValue]); const send = (data: EBCEvent) => { - channel?.postMessage(data); + channel.postMessage(data); }; return { mode, value, send }; From 8dc753ee39b206e1a70d3e565876fc6377005fc3 Mon Sep 17 00:00:00 2001 From: yassinedorbozgithub Date: Tue, 28 Jan 2025 11:16:23 +0100 Subject: [PATCH 05/49] fix: apply feedback updates --- frontend/src/contexts/auth.context.tsx | 14 ------ frontend/src/hooks/entities/auth-hooks.ts | 4 +- frontend/src/hooks/useBroadcastChannel.ts | 46 +++++++++--------- widget/src/hooks/useBroadcastChannel.ts | 57 +++++++++++++++++++++++ widget/src/providers/ChatProvider.tsx | 15 +++++- 5 files changed, 95 insertions(+), 41 deletions(-) create mode 100644 widget/src/hooks/useBroadcastChannel.ts diff --git a/frontend/src/contexts/auth.context.tsx b/frontend/src/contexts/auth.context.tsx index a3d27ace..a2faf186 100644 --- a/frontend/src/contexts/auth.context.tsx +++ b/frontend/src/contexts/auth.context.tsx @@ -21,11 +21,6 @@ import { Progress } from "@/app-components/displays/Progress"; import { useLogout } from "@/hooks/entities/auth-hooks"; import { useApiClient } from "@/hooks/useApiClient"; import { CURRENT_USER_KEY, PUBLIC_PATHS } from "@/hooks/useAuth"; -import { - EBCEvent, - ETabMode, - useBroadcastChannel, -} from "@/hooks/useBroadcastChannel"; import { useTranslate } from "@/hooks/useTranslate"; import { RouterType } from "@/services/types"; import { IUser } from "@/types/user.types"; @@ -64,9 +59,6 @@ export const AuthProvider = ({ children }: AuthProviderProps): JSX.Element => { i18n.changeLanguage(lang); }; const { mutate: logoutSession } = useLogout(); - const { mode, value } = useBroadcastChannel({ - channelName: "websocket-session", - }); const logout = async () => { updateLanguage(publicRuntimeConfig.lang.default); logoutSession(); @@ -115,12 +107,6 @@ export const AuthProvider = ({ children }: AuthProviderProps): JSX.Element => { setIsReady(true); }, []); - useEffect(() => { - if (value === EBCEvent.LOGOUT_END_SESSION && mode === ETabMode.SECONDARY) { - router.reload(); - } - }, [value, mode, router]); - if (!isReady || isLoading) return ; return ( diff --git a/frontend/src/hooks/entities/auth-hooks.ts b/frontend/src/hooks/entities/auth-hooks.ts index 8dd9d783..fb78fed4 100755 --- a/frontend/src/hooks/entities/auth-hooks.ts +++ b/frontend/src/hooks/entities/auth-hooks.ts @@ -59,9 +59,7 @@ export const useLogout = ( const { logoutRedirection } = useLogoutRedirection(); const { toast } = useToast(); const { t } = useTranslate(); - const { send } = useBroadcastChannel({ - channelName: "websocket-session", - }); + const { send } = useBroadcastChannel(); return useMutation({ ...options, diff --git a/frontend/src/hooks/useBroadcastChannel.ts b/frontend/src/hooks/useBroadcastChannel.ts index 66a30582..beba882d 100644 --- a/frontend/src/hooks/useBroadcastChannel.ts +++ b/frontend/src/hooks/useBroadcastChannel.ts @@ -6,7 +6,7 @@ * 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file). */ -import { useEffect, useMemo, useState } from "react"; +import { useEffect, useRef, useState } from "react"; export enum ETabMode { PRIMARY = "primary", @@ -17,38 +17,40 @@ export enum EBCEvent { LOGOUT_END_SESSION = "logout-end-session", } -export const useBroadcastChannel = ({ - channelName, - initialValue, -}: { - channelName: string; - initialValue?: EBCEvent; -}) => { +export const useBroadcastChannel = ( + channelName: string = "main-broadcast-channel", + initialValue?: EBCEvent, +) => { + const channelRef = useRef(null); const [value, setValue] = useState(initialValue); const [mode, setMode] = useState(ETabMode.PRIMARY); - const channel = useMemo( - () => new BroadcastChannel(channelName), - [channelName], - ); useEffect(() => { - channel.onmessage = (event) => { - if (mode === ETabMode.PRIMARY) { - setValue(event.data); - setMode(ETabMode.SECONDARY); - } - }; + channelRef.current = new BroadcastChannel(channelName); + }, [channelName]); - channel.postMessage(initialValue); + useEffect(() => { + if (channelRef.current) { + channelRef.current.addEventListener("message", (event) => { + if (mode === ETabMode.PRIMARY) { + setValue(event.data); + setMode(ETabMode.SECONDARY); + } + }); + channelRef.current.postMessage(initialValue); + } return () => { - channel.close(); + if (channelRef.current?.onmessage) { + channelRef.current.onmessage = null; + } + channelRef.current?.close(); }; // eslint-disable-next-line react-hooks/exhaustive-deps - }, [channel, channelName, initialValue]); + }, [channelName, initialValue]); const send = (data: EBCEvent) => { - channel.postMessage(data); + channelRef.current?.postMessage(data); }; return { mode, value, send }; diff --git a/widget/src/hooks/useBroadcastChannel.ts b/widget/src/hooks/useBroadcastChannel.ts new file mode 100644 index 00000000..beba882d --- /dev/null +++ b/widget/src/hooks/useBroadcastChannel.ts @@ -0,0 +1,57 @@ +/* + * Copyright © 2025 Hexastack. All rights reserved. + * + * Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms: + * 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission. + * 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file). + */ + +import { useEffect, useRef, useState } from "react"; + +export enum ETabMode { + PRIMARY = "primary", + SECONDARY = "secondary", +} + +export enum EBCEvent { + LOGOUT_END_SESSION = "logout-end-session", +} + +export const useBroadcastChannel = ( + channelName: string = "main-broadcast-channel", + initialValue?: EBCEvent, +) => { + const channelRef = useRef(null); + const [value, setValue] = useState(initialValue); + const [mode, setMode] = useState(ETabMode.PRIMARY); + + useEffect(() => { + channelRef.current = new BroadcastChannel(channelName); + }, [channelName]); + + useEffect(() => { + if (channelRef.current) { + channelRef.current.addEventListener("message", (event) => { + if (mode === ETabMode.PRIMARY) { + setValue(event.data); + setMode(ETabMode.SECONDARY); + } + }); + channelRef.current.postMessage(initialValue); + } + + return () => { + if (channelRef.current?.onmessage) { + channelRef.current.onmessage = null; + } + channelRef.current?.close(); + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [channelName, initialValue]); + + const send = (data: EBCEvent) => { + channelRef.current?.postMessage(data); + }; + + return { mode, value, send }; +}; diff --git a/widget/src/providers/ChatProvider.tsx b/widget/src/providers/ChatProvider.tsx index f24795cd..eefb0937 100644 --- a/widget/src/providers/ChatProvider.tsx +++ b/widget/src/providers/ChatProvider.tsx @@ -6,7 +6,6 @@ * 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file). */ - import React, { createContext, ReactNode, @@ -17,6 +16,11 @@ import React, { useState, } from "react"; +import { + EBCEvent, + ETabMode, + useBroadcastChannel, +} from "../hooks/useBroadcastChannel"; import { StdEventType } from "../types/chat-io-messages.types"; import { Direction, @@ -188,6 +192,7 @@ const ChatProvider: React.FC<{ defaultConnectionState?: ConnectionState; children: ReactNode; }> = ({ wantToConnect, defaultConnectionState = 0, children }) => { + const { mode, value } = useBroadcastChannel(); const config = useConfig(); const settings = useSettings(); const { screen, setScreen } = useWidget(); @@ -269,7 +274,7 @@ const ChatProvider: React.FC<{ content_type: QuickReplyType.text, text: qr.title, payload: qr.payload, - } as ISuggestion), + }) as ISuggestion, ), ); } else { @@ -419,6 +424,12 @@ const ChatProvider: React.FC<{ // eslint-disable-next-line react-hooks/exhaustive-deps }, [settings.avatarUrl]); + useEffect(() => { + if (value === EBCEvent.LOGOUT_END_SESSION && mode === ETabMode.SECONDARY) { + socketCtx.socket.disconnect(); + } + }, [value, mode]); + const contextValue: ChatContextType = { participants, setParticipants, From cb76979311c0de7a4f06b47af655e32a5c9d99bc Mon Sep 17 00:00:00 2001 From: yassinedorbozgithub Date: Tue, 28 Jan 2025 11:29:15 +0100 Subject: [PATCH 06/49] fix(widget): fix linting issue --- widget/src/providers/ChatProvider.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/widget/src/providers/ChatProvider.tsx b/widget/src/providers/ChatProvider.tsx index eefb0937..61342785 100644 --- a/widget/src/providers/ChatProvider.tsx +++ b/widget/src/providers/ChatProvider.tsx @@ -428,7 +428,7 @@ const ChatProvider: React.FC<{ if (value === EBCEvent.LOGOUT_END_SESSION && mode === ETabMode.SECONDARY) { socketCtx.socket.disconnect(); } - }, [value, mode]); + }, [value, mode, socketCtx.socket]); const contextValue: ChatContextType = { participants, From 7145404dbce2749132cca2b0477e1386bfae0a1c Mon Sep 17 00:00:00 2001 From: yassinedorbozgithub Date: Tue, 28 Jan 2025 11:49:46 +0100 Subject: [PATCH 07/49] feat(frontend): add BroadcastChannel hook --- frontend/src/contexts/auth.context.tsx | 12 +++++ frontend/src/hooks/entities/auth-hooks.ts | 3 ++ frontend/src/hooks/useBroadcastChannel.ts | 57 +++++++++++++++++++++++ 3 files changed, 72 insertions(+) create mode 100644 frontend/src/hooks/useBroadcastChannel.ts diff --git a/frontend/src/contexts/auth.context.tsx b/frontend/src/contexts/auth.context.tsx index a2faf186..a68651a4 100644 --- a/frontend/src/contexts/auth.context.tsx +++ b/frontend/src/contexts/auth.context.tsx @@ -21,6 +21,11 @@ import { Progress } from "@/app-components/displays/Progress"; import { useLogout } from "@/hooks/entities/auth-hooks"; import { useApiClient } from "@/hooks/useApiClient"; import { CURRENT_USER_KEY, PUBLIC_PATHS } from "@/hooks/useAuth"; +import { + EBCEvent, + ETabMode, + useBroadcastChannel, +} from "@/hooks/useBroadcastChannel"; import { useTranslate } from "@/hooks/useTranslate"; import { RouterType } from "@/services/types"; import { IUser } from "@/types/user.types"; @@ -59,6 +64,7 @@ export const AuthProvider = ({ children }: AuthProviderProps): JSX.Element => { i18n.changeLanguage(lang); }; const { mutate: logoutSession } = useLogout(); + const { mode, value } = useBroadcastChannel(); const logout = async () => { updateLanguage(publicRuntimeConfig.lang.default); logoutSession(); @@ -107,6 +113,12 @@ export const AuthProvider = ({ children }: AuthProviderProps): JSX.Element => { setIsReady(true); }, []); + useEffect(() => { + if (value === EBCEvent.LOGOUT_END_SESSION && mode === ETabMode.SECONDARY) { + router.reload(); + } + }, [value, mode, router]); + if (!isReady || isLoading) return ; return ( diff --git a/frontend/src/hooks/entities/auth-hooks.ts b/frontend/src/hooks/entities/auth-hooks.ts index e3a1b07b..fb78fed4 100755 --- a/frontend/src/hooks/entities/auth-hooks.ts +++ b/frontend/src/hooks/entities/auth-hooks.ts @@ -22,6 +22,7 @@ import { useSocket } from "@/websocket/socket-hooks"; import { useFind } from "../crud/useFind"; import { useApiClient } from "../useApiClient"; import { CURRENT_USER_KEY, useAuth, useLogoutRedirection } from "../useAuth"; +import { EBCEvent, useBroadcastChannel } from "../useBroadcastChannel"; import { useToast } from "../useToast"; import { useTranslate } from "../useTranslate"; @@ -58,6 +59,7 @@ export const useLogout = ( const { logoutRedirection } = useLogoutRedirection(); const { toast } = useToast(); const { t } = useTranslate(); + const { send } = useBroadcastChannel(); return useMutation({ ...options, @@ -68,6 +70,7 @@ export const useLogout = ( }, onSuccess: async () => { queryClient.removeQueries([CURRENT_USER_KEY]); + send(EBCEvent.LOGOUT_END_SESSION); await logoutRedirection(); toast.success(t("message.logout_success")); }, diff --git a/frontend/src/hooks/useBroadcastChannel.ts b/frontend/src/hooks/useBroadcastChannel.ts new file mode 100644 index 00000000..beba882d --- /dev/null +++ b/frontend/src/hooks/useBroadcastChannel.ts @@ -0,0 +1,57 @@ +/* + * Copyright © 2025 Hexastack. All rights reserved. + * + * Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms: + * 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission. + * 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file). + */ + +import { useEffect, useRef, useState } from "react"; + +export enum ETabMode { + PRIMARY = "primary", + SECONDARY = "secondary", +} + +export enum EBCEvent { + LOGOUT_END_SESSION = "logout-end-session", +} + +export const useBroadcastChannel = ( + channelName: string = "main-broadcast-channel", + initialValue?: EBCEvent, +) => { + const channelRef = useRef(null); + const [value, setValue] = useState(initialValue); + const [mode, setMode] = useState(ETabMode.PRIMARY); + + useEffect(() => { + channelRef.current = new BroadcastChannel(channelName); + }, [channelName]); + + useEffect(() => { + if (channelRef.current) { + channelRef.current.addEventListener("message", (event) => { + if (mode === ETabMode.PRIMARY) { + setValue(event.data); + setMode(ETabMode.SECONDARY); + } + }); + channelRef.current.postMessage(initialValue); + } + + return () => { + if (channelRef.current?.onmessage) { + channelRef.current.onmessage = null; + } + channelRef.current?.close(); + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [channelName, initialValue]); + + const send = (data: EBCEvent) => { + channelRef.current?.postMessage(data); + }; + + return { mode, value, send }; +}; From cb2861d6b2b880da7ebdaae723875fda747a444f Mon Sep 17 00:00:00 2001 From: yassinedorbozgithub Date: Tue, 28 Jan 2025 16:55:28 +0100 Subject: [PATCH 08/49] fix(frontend): update BroadcastChannel hook --- frontend/src/contexts/auth.context.tsx | 15 +- frontend/src/hooks/entities/auth-hooks.ts | 6 +- frontend/src/hooks/useBroadcastChannel.ts | 166 ++++++++++++++++------ 3 files changed, 132 insertions(+), 55 deletions(-) diff --git a/frontend/src/contexts/auth.context.tsx b/frontend/src/contexts/auth.context.tsx index a68651a4..41e4c81f 100644 --- a/frontend/src/contexts/auth.context.tsx +++ b/frontend/src/contexts/auth.context.tsx @@ -21,11 +21,7 @@ import { Progress } from "@/app-components/displays/Progress"; import { useLogout } from "@/hooks/entities/auth-hooks"; import { useApiClient } from "@/hooks/useApiClient"; import { CURRENT_USER_KEY, PUBLIC_PATHS } from "@/hooks/useAuth"; -import { - EBCEvent, - ETabMode, - useBroadcastChannel, -} from "@/hooks/useBroadcastChannel"; +import { useBroadcastChannel } from "@/hooks/useBroadcastChannel"; import { useTranslate } from "@/hooks/useTranslate"; import { RouterType } from "@/services/types"; import { IUser } from "@/types/user.types"; @@ -64,7 +60,6 @@ export const AuthProvider = ({ children }: AuthProviderProps): JSX.Element => { i18n.changeLanguage(lang); }; const { mutate: logoutSession } = useLogout(); - const { mode, value } = useBroadcastChannel(); const logout = async () => { updateLanguage(publicRuntimeConfig.lang.default); logoutSession(); @@ -113,11 +108,9 @@ export const AuthProvider = ({ children }: AuthProviderProps): JSX.Element => { setIsReady(true); }, []); - useEffect(() => { - if (value === EBCEvent.LOGOUT_END_SESSION && mode === ETabMode.SECONDARY) { - router.reload(); - } - }, [value, mode, router]); + useBroadcastChannel("session", () => { + router.reload(); + }); if (!isReady || isLoading) return ; diff --git a/frontend/src/hooks/entities/auth-hooks.ts b/frontend/src/hooks/entities/auth-hooks.ts index fb78fed4..1dc65bf0 100755 --- a/frontend/src/hooks/entities/auth-hooks.ts +++ b/frontend/src/hooks/entities/auth-hooks.ts @@ -22,7 +22,7 @@ import { useSocket } from "@/websocket/socket-hooks"; import { useFind } from "../crud/useFind"; import { useApiClient } from "../useApiClient"; import { CURRENT_USER_KEY, useAuth, useLogoutRedirection } from "../useAuth"; -import { EBCEvent, useBroadcastChannel } from "../useBroadcastChannel"; +import { useBroadcastChannel } from "../useBroadcastChannel"; import { useToast } from "../useToast"; import { useTranslate } from "../useTranslate"; @@ -59,7 +59,7 @@ export const useLogout = ( const { logoutRedirection } = useLogoutRedirection(); const { toast } = useToast(); const { t } = useTranslate(); - const { send } = useBroadcastChannel(); + const postDisconnectionSignal = useBroadcastChannel("session"); return useMutation({ ...options, @@ -70,7 +70,7 @@ export const useLogout = ( }, onSuccess: async () => { queryClient.removeQueries([CURRENT_USER_KEY]); - send(EBCEvent.LOGOUT_END_SESSION); + postDisconnectionSignal("logout"); await logoutRedirection(); toast.success(t("message.logout_success")); }, diff --git a/frontend/src/hooks/useBroadcastChannel.ts b/frontend/src/hooks/useBroadcastChannel.ts index beba882d..7caaa69d 100644 --- a/frontend/src/hooks/useBroadcastChannel.ts +++ b/frontend/src/hooks/useBroadcastChannel.ts @@ -6,52 +6,136 @@ * 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file). */ -import { useEffect, useRef, useState } from "react"; +import * as React from "react"; -export enum ETabMode { - PRIMARY = "primary", - SECONDARY = "secondary", -} +export type BroadcastChannelData = + | string + | number + | boolean + | Record + | undefined + | null; -export enum EBCEvent { - LOGOUT_END_SESSION = "logout-end-session", -} +/** + * React hook to create and manage a Broadcast Channel across multiple browser windows. + * + * @param channelName Static name of channel used across the browser windows. + * @param handleMessage Callback to handle the event generated when `message` is received. + * @param handleMessageError [optional] Callback to handle the event generated when `error` is received. + * @returns A function to send/post message on the channel. + * @example + * ```tsx + * import {useBroadcastChannel} from 'react-broadcast-channel'; + * + * function App () { + * const postUserIdMessage = useBroadcastChannel('userId', (e) => alert(e.data)); + * return (); + * } + * ``` + * --- + * Works in browser that support Broadcast Channel API natively. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API#browser_compatibility). + * To support other browsers, install and use [broadcastchannel-polyfill](https://www.npmjs.com/package/broadcastchannel-polyfill). + */ +export function useBroadcastChannel( + channelName: string, + handleMessage?: (event: MessageEvent) => void, + handleMessageError?: (event: MessageEvent) => void, +): (data: T) => void { + const channelRef = React.useRef(null); -export const useBroadcastChannel = ( - channelName: string = "main-broadcast-channel", - initialValue?: EBCEvent, -) => { - const channelRef = useRef(null); - const [value, setValue] = useState(initialValue); - const [mode, setMode] = useState(ETabMode.PRIMARY); - - useEffect(() => { - channelRef.current = new BroadcastChannel(channelName); + React.useEffect(() => { + if (typeof window !== "undefined" && "BroadcastChannel" in window) { + channelRef.current = new BroadcastChannel(channelName + "-channel"); + } }, [channelName]); - useEffect(() => { - if (channelRef.current) { - channelRef.current.addEventListener("message", (event) => { - if (mode === ETabMode.PRIMARY) { - setValue(event.data); - setMode(ETabMode.SECONDARY); - } - }); - channelRef.current.postMessage(initialValue); + useChannelEventListener(channelRef.current, "message", handleMessage); + useChannelEventListener( + channelRef.current, + "messageerror", + handleMessageError, + ); + + return React.useCallback( + (data: T) => channelRef.current?.postMessage(data), + [channelRef.current], + ); +} + +/** + * React hook to manage state across browser windows. Has the similar signature as `React.useState`. + * + * @param channelName Static name of channel used across the browser windows. + * @param initialState Initial state. + * @returns Tuple of state and setter for the state. + * @example + * ```tsx + * import {useBroadcastState} from 'react-broadcast-channel'; + * + * function App () { + * const [count, setCount] = useBroadcastState('count', 0); + * return ( + *
+ * + * {count} + * + *
+ * ); + * } + * ``` + * --- + * Works in browser that support Broadcast Channel API natively. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API#browser_compatibility). + * To support other browsers, install and use [broadcastchannel-polyfill](https://www.npmjs.com/package/broadcastchannel-polyfill). + */ +export function useBroadcastState( + channelName: string, + initialState: T, +): [T, React.Dispatch>, boolean] { + const [isPending, startTransition] = React.useTransition(); + const [state, setState] = React.useState(initialState); + const broadcast = useBroadcastChannel(channelName, (ev) => + setState(ev.data), + ); + const updateState: React.Dispatch> = + React.useCallback( + (input) => { + setState((prev) => { + const newState = typeof input === "function" ? input(prev) : input; + + startTransition(() => broadcast(newState)); + + return newState; + }); + }, + [broadcast], + ); + + return [state, updateState, isPending]; +} + +// Helpers + +/** Hook to subscribe/unsubscribe from channel events. */ +function useChannelEventListener( + channel: BroadcastChannel | null, + event: K, + handler?: (e: BroadcastChannelEventMap[K]) => void, +) { + const callbackRef = React.useRef(handler); + + if (callbackRef.current !== handler) { + callbackRef.current = handler; + } + + React.useEffect(() => { + const callback = callbackRef.current; + + if (!channel || !callback) { + return; } - return () => { - if (channelRef.current?.onmessage) { - channelRef.current.onmessage = null; - } - channelRef.current?.close(); - }; - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [channelName, initialValue]); + channel.addEventListener(event, callback); - const send = (data: EBCEvent) => { - channelRef.current?.postMessage(data); - }; - - return { mode, value, send }; -}; + return () => channel.removeEventListener(event, callback); + }, [channel, event]); +} From 049ffb7f5031807d329dc2a2eddeb47f658cb490 Mon Sep 17 00:00:00 2001 From: yassinedorbozgithub Date: Tue, 28 Jan 2025 17:04:40 +0100 Subject: [PATCH 09/49] fix(widget): update BroadcastChannel hook --- widget/src/hooks/useBroadcastChannel.ts | 166 ++++++++++++++++++------ widget/src/providers/ChatProvider.tsx | 17 +-- 2 files changed, 130 insertions(+), 53 deletions(-) diff --git a/widget/src/hooks/useBroadcastChannel.ts b/widget/src/hooks/useBroadcastChannel.ts index beba882d..7caaa69d 100644 --- a/widget/src/hooks/useBroadcastChannel.ts +++ b/widget/src/hooks/useBroadcastChannel.ts @@ -6,52 +6,136 @@ * 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file). */ -import { useEffect, useRef, useState } from "react"; +import * as React from "react"; -export enum ETabMode { - PRIMARY = "primary", - SECONDARY = "secondary", -} +export type BroadcastChannelData = + | string + | number + | boolean + | Record + | undefined + | null; -export enum EBCEvent { - LOGOUT_END_SESSION = "logout-end-session", -} +/** + * React hook to create and manage a Broadcast Channel across multiple browser windows. + * + * @param channelName Static name of channel used across the browser windows. + * @param handleMessage Callback to handle the event generated when `message` is received. + * @param handleMessageError [optional] Callback to handle the event generated when `error` is received. + * @returns A function to send/post message on the channel. + * @example + * ```tsx + * import {useBroadcastChannel} from 'react-broadcast-channel'; + * + * function App () { + * const postUserIdMessage = useBroadcastChannel('userId', (e) => alert(e.data)); + * return (); + * } + * ``` + * --- + * Works in browser that support Broadcast Channel API natively. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API#browser_compatibility). + * To support other browsers, install and use [broadcastchannel-polyfill](https://www.npmjs.com/package/broadcastchannel-polyfill). + */ +export function useBroadcastChannel( + channelName: string, + handleMessage?: (event: MessageEvent) => void, + handleMessageError?: (event: MessageEvent) => void, +): (data: T) => void { + const channelRef = React.useRef(null); -export const useBroadcastChannel = ( - channelName: string = "main-broadcast-channel", - initialValue?: EBCEvent, -) => { - const channelRef = useRef(null); - const [value, setValue] = useState(initialValue); - const [mode, setMode] = useState(ETabMode.PRIMARY); - - useEffect(() => { - channelRef.current = new BroadcastChannel(channelName); + React.useEffect(() => { + if (typeof window !== "undefined" && "BroadcastChannel" in window) { + channelRef.current = new BroadcastChannel(channelName + "-channel"); + } }, [channelName]); - useEffect(() => { - if (channelRef.current) { - channelRef.current.addEventListener("message", (event) => { - if (mode === ETabMode.PRIMARY) { - setValue(event.data); - setMode(ETabMode.SECONDARY); - } - }); - channelRef.current.postMessage(initialValue); + useChannelEventListener(channelRef.current, "message", handleMessage); + useChannelEventListener( + channelRef.current, + "messageerror", + handleMessageError, + ); + + return React.useCallback( + (data: T) => channelRef.current?.postMessage(data), + [channelRef.current], + ); +} + +/** + * React hook to manage state across browser windows. Has the similar signature as `React.useState`. + * + * @param channelName Static name of channel used across the browser windows. + * @param initialState Initial state. + * @returns Tuple of state and setter for the state. + * @example + * ```tsx + * import {useBroadcastState} from 'react-broadcast-channel'; + * + * function App () { + * const [count, setCount] = useBroadcastState('count', 0); + * return ( + *
+ * + * {count} + * + *
+ * ); + * } + * ``` + * --- + * Works in browser that support Broadcast Channel API natively. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API#browser_compatibility). + * To support other browsers, install and use [broadcastchannel-polyfill](https://www.npmjs.com/package/broadcastchannel-polyfill). + */ +export function useBroadcastState( + channelName: string, + initialState: T, +): [T, React.Dispatch>, boolean] { + const [isPending, startTransition] = React.useTransition(); + const [state, setState] = React.useState(initialState); + const broadcast = useBroadcastChannel(channelName, (ev) => + setState(ev.data), + ); + const updateState: React.Dispatch> = + React.useCallback( + (input) => { + setState((prev) => { + const newState = typeof input === "function" ? input(prev) : input; + + startTransition(() => broadcast(newState)); + + return newState; + }); + }, + [broadcast], + ); + + return [state, updateState, isPending]; +} + +// Helpers + +/** Hook to subscribe/unsubscribe from channel events. */ +function useChannelEventListener( + channel: BroadcastChannel | null, + event: K, + handler?: (e: BroadcastChannelEventMap[K]) => void, +) { + const callbackRef = React.useRef(handler); + + if (callbackRef.current !== handler) { + callbackRef.current = handler; + } + + React.useEffect(() => { + const callback = callbackRef.current; + + if (!channel || !callback) { + return; } - return () => { - if (channelRef.current?.onmessage) { - channelRef.current.onmessage = null; - } - channelRef.current?.close(); - }; - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [channelName, initialValue]); + channel.addEventListener(event, callback); - const send = (data: EBCEvent) => { - channelRef.current?.postMessage(data); - }; - - return { mode, value, send }; -}; + return () => channel.removeEventListener(event, callback); + }, [channel, event]); +} diff --git a/widget/src/providers/ChatProvider.tsx b/widget/src/providers/ChatProvider.tsx index 61342785..0bd20df8 100644 --- a/widget/src/providers/ChatProvider.tsx +++ b/widget/src/providers/ChatProvider.tsx @@ -16,11 +16,7 @@ import React, { useState, } from "react"; -import { - EBCEvent, - ETabMode, - useBroadcastChannel, -} from "../hooks/useBroadcastChannel"; +import { useBroadcastChannel } from "../hooks/useBroadcastChannel"; import { StdEventType } from "../types/chat-io-messages.types"; import { Direction, @@ -192,7 +188,6 @@ const ChatProvider: React.FC<{ defaultConnectionState?: ConnectionState; children: ReactNode; }> = ({ wantToConnect, defaultConnectionState = 0, children }) => { - const { mode, value } = useBroadcastChannel(); const config = useConfig(); const settings = useSettings(); const { screen, setScreen } = useWidget(); @@ -424,12 +419,6 @@ const ChatProvider: React.FC<{ // eslint-disable-next-line react-hooks/exhaustive-deps }, [settings.avatarUrl]); - useEffect(() => { - if (value === EBCEvent.LOGOUT_END_SESSION && mode === ETabMode.SECONDARY) { - socketCtx.socket.disconnect(); - } - }, [value, mode, socketCtx.socket]); - const contextValue: ChatContextType = { participants, setParticipants, @@ -464,6 +453,10 @@ const ChatProvider: React.FC<{ handleSubscription, }; + useBroadcastChannel("session", () => { + socketCtx.socket.disconnect(); + }); + return ( {children} ); From dab65b46a97f9f1f5793b5a297132fa228748dcf Mon Sep 17 00:00:00 2001 From: yassinedorbozgithub Date: Wed, 29 Jan 2025 08:14:46 +0100 Subject: [PATCH 10/49] fix: apply feedback updates --- widget/src/hooks/useBroadcastChannel.ts | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/widget/src/hooks/useBroadcastChannel.ts b/widget/src/hooks/useBroadcastChannel.ts index 7caaa69d..d20151a7 100644 --- a/widget/src/hooks/useBroadcastChannel.ts +++ b/widget/src/hooks/useBroadcastChannel.ts @@ -41,13 +41,11 @@ export function useBroadcastChannel( handleMessage?: (event: MessageEvent) => void, handleMessageError?: (event: MessageEvent) => void, ): (data: T) => void { - const channelRef = React.useRef(null); - - React.useEffect(() => { - if (typeof window !== "undefined" && "BroadcastChannel" in window) { - channelRef.current = new BroadcastChannel(channelName + "-channel"); - } - }, [channelName]); + const channelRef = React.useRef( + typeof window !== "undefined" && "BroadcastChannel" in window + ? new BroadcastChannel(channelName + "-channel") + : null, + ); useChannelEventListener(channelRef.current, "message", handleMessage); useChannelEventListener( @@ -56,10 +54,7 @@ export function useBroadcastChannel( handleMessageError, ); - return React.useCallback( - (data: T) => channelRef.current?.postMessage(data), - [channelRef.current], - ); + return (data: T) => channelRef.current?.postMessage(data); } /** From d883e99eb3aa76f98ba848ff1e4b51a6849ce3a6 Mon Sep 17 00:00:00 2001 From: yassinedorbozgithub Date: Wed, 29 Jan 2025 08:17:12 +0100 Subject: [PATCH 11/49] fix: apply feedback updates --- frontend/src/hooks/useBroadcastChannel.ts | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/frontend/src/hooks/useBroadcastChannel.ts b/frontend/src/hooks/useBroadcastChannel.ts index 7caaa69d..d20151a7 100644 --- a/frontend/src/hooks/useBroadcastChannel.ts +++ b/frontend/src/hooks/useBroadcastChannel.ts @@ -41,13 +41,11 @@ export function useBroadcastChannel( handleMessage?: (event: MessageEvent) => void, handleMessageError?: (event: MessageEvent) => void, ): (data: T) => void { - const channelRef = React.useRef(null); - - React.useEffect(() => { - if (typeof window !== "undefined" && "BroadcastChannel" in window) { - channelRef.current = new BroadcastChannel(channelName + "-channel"); - } - }, [channelName]); + const channelRef = React.useRef( + typeof window !== "undefined" && "BroadcastChannel" in window + ? new BroadcastChannel(channelName + "-channel") + : null, + ); useChannelEventListener(channelRef.current, "message", handleMessage); useChannelEventListener( @@ -56,10 +54,7 @@ export function useBroadcastChannel( handleMessageError, ); - return React.useCallback( - (data: T) => channelRef.current?.postMessage(data), - [channelRef.current], - ); + return (data: T) => channelRef.current?.postMessage(data); } /** From 3165b3b8dee44b60a9694c115d491853e14dfae8 Mon Sep 17 00:00:00 2001 From: yassinedorbozgithub Date: Wed, 29 Jan 2025 08:45:37 +0100 Subject: [PATCH 12/49] fix: apply feedback updates --- frontend/src/hooks/entities/auth-hooks.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/frontend/src/hooks/entities/auth-hooks.ts b/frontend/src/hooks/entities/auth-hooks.ts index 1dc65bf0..86d52d6d 100755 --- a/frontend/src/hooks/entities/auth-hooks.ts +++ b/frontend/src/hooks/entities/auth-hooks.ts @@ -59,7 +59,7 @@ export const useLogout = ( const { logoutRedirection } = useLogoutRedirection(); const { toast } = useToast(); const { t } = useTranslate(); - const postDisconnectionSignal = useBroadcastChannel("session"); + const broadcastLogoutAcrossTabs = useBroadcastChannel("session"); return useMutation({ ...options, @@ -70,7 +70,7 @@ export const useLogout = ( }, onSuccess: async () => { queryClient.removeQueries([CURRENT_USER_KEY]); - postDisconnectionSignal("logout"); + broadcastLogoutAcrossTabs("logout"); await logoutRedirection(); toast.success(t("message.logout_success")); }, From fade7070ff1cd9fc318fee3cd7cc99f71401921a Mon Sep 17 00:00:00 2001 From: yassinedorbozgithub Date: Wed, 29 Jan 2025 08:48:51 +0100 Subject: [PATCH 13/49] fix: apply feedback updates --- widget/src/providers/ChatProvider.tsx | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/widget/src/providers/ChatProvider.tsx b/widget/src/providers/ChatProvider.tsx index 0bd20df8..f907c428 100644 --- a/widget/src/providers/ChatProvider.tsx +++ b/widget/src/providers/ChatProvider.tsx @@ -453,8 +453,10 @@ const ChatProvider: React.FC<{ handleSubscription, }; - useBroadcastChannel("session", () => { - socketCtx.socket.disconnect(); + useBroadcastChannel("session", (e) => { + if (e.data === "logout") { + socketCtx.socket.disconnect(); + } }); return ( From 39d526ced03b419fa14369c2b2ad5d3946a6ee91 Mon Sep 17 00:00:00 2001 From: yassinedorbozgithub Date: Wed, 29 Jan 2025 10:12:16 +0100 Subject: [PATCH 14/49] fix: apply feedback updates --- widget/src/hooks/useBroadcastChannel.ts | 30 ------------------------- 1 file changed, 30 deletions(-) diff --git a/widget/src/hooks/useBroadcastChannel.ts b/widget/src/hooks/useBroadcastChannel.ts index d20151a7..32172c31 100644 --- a/widget/src/hooks/useBroadcastChannel.ts +++ b/widget/src/hooks/useBroadcastChannel.ts @@ -23,18 +23,6 @@ export type BroadcastChannelData = * @param handleMessage Callback to handle the event generated when `message` is received. * @param handleMessageError [optional] Callback to handle the event generated when `error` is received. * @returns A function to send/post message on the channel. - * @example - * ```tsx - * import {useBroadcastChannel} from 'react-broadcast-channel'; - * - * function App () { - * const postUserIdMessage = useBroadcastChannel('userId', (e) => alert(e.data)); - * return (); - * } - * ``` - * --- - * Works in browser that support Broadcast Channel API natively. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API#browser_compatibility). - * To support other browsers, install and use [broadcastchannel-polyfill](https://www.npmjs.com/package/broadcastchannel-polyfill). */ export function useBroadcastChannel( channelName: string, @@ -63,24 +51,6 @@ export function useBroadcastChannel( * @param channelName Static name of channel used across the browser windows. * @param initialState Initial state. * @returns Tuple of state and setter for the state. - * @example - * ```tsx - * import {useBroadcastState} from 'react-broadcast-channel'; - * - * function App () { - * const [count, setCount] = useBroadcastState('count', 0); - * return ( - *
- * - * {count} - * - *
- * ); - * } - * ``` - * --- - * Works in browser that support Broadcast Channel API natively. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API#browser_compatibility). - * To support other browsers, install and use [broadcastchannel-polyfill](https://www.npmjs.com/package/broadcastchannel-polyfill). */ export function useBroadcastState( channelName: string, From a0844efc4a66dddde9c6b54346b241a96bad88f5 Mon Sep 17 00:00:00 2001 From: yassinedorbozgithub Date: Wed, 29 Jan 2025 10:17:37 +0100 Subject: [PATCH 15/49] fix(frontend): update useBroadcastChannel hook --- frontend/src/hooks/useBroadcastChannel.ts | 30 ----------------------- 1 file changed, 30 deletions(-) diff --git a/frontend/src/hooks/useBroadcastChannel.ts b/frontend/src/hooks/useBroadcastChannel.ts index d20151a7..32172c31 100644 --- a/frontend/src/hooks/useBroadcastChannel.ts +++ b/frontend/src/hooks/useBroadcastChannel.ts @@ -23,18 +23,6 @@ export type BroadcastChannelData = * @param handleMessage Callback to handle the event generated when `message` is received. * @param handleMessageError [optional] Callback to handle the event generated when `error` is received. * @returns A function to send/post message on the channel. - * @example - * ```tsx - * import {useBroadcastChannel} from 'react-broadcast-channel'; - * - * function App () { - * const postUserIdMessage = useBroadcastChannel('userId', (e) => alert(e.data)); - * return (); - * } - * ``` - * --- - * Works in browser that support Broadcast Channel API natively. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API#browser_compatibility). - * To support other browsers, install and use [broadcastchannel-polyfill](https://www.npmjs.com/package/broadcastchannel-polyfill). */ export function useBroadcastChannel( channelName: string, @@ -63,24 +51,6 @@ export function useBroadcastChannel( * @param channelName Static name of channel used across the browser windows. * @param initialState Initial state. * @returns Tuple of state and setter for the state. - * @example - * ```tsx - * import {useBroadcastState} from 'react-broadcast-channel'; - * - * function App () { - * const [count, setCount] = useBroadcastState('count', 0); - * return ( - *
- * - * {count} - * - *
- * ); - * } - * ``` - * --- - * Works in browser that support Broadcast Channel API natively. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API#browser_compatibility). - * To support other browsers, install and use [broadcastchannel-polyfill](https://www.npmjs.com/package/broadcastchannel-polyfill). */ export function useBroadcastState( channelName: string, From aa4a0fe43817a2eaf698f8b6e84356eb3e436ae3 Mon Sep 17 00:00:00 2001 From: yassinedorbozgithub Date: Wed, 29 Jan 2025 11:06:23 +0100 Subject: [PATCH 16/49] fix: make logout close sockets --- api/src/user/controllers/auth.controller.ts | 15 ++++++++++++++- api/src/websocket/websocket.gateway.ts | 15 +++++++++++++-- api/types/event-emitter.d.ts | 3 ++- package-lock.json | 4 ++-- 4 files changed, 31 insertions(+), 6 deletions(-) diff --git a/api/src/user/controllers/auth.controller.ts b/api/src/user/controllers/auth.controller.ts index 559bc2ee..5a49cb53 100644 --- a/api/src/user/controllers/auth.controller.ts +++ b/api/src/user/controllers/auth.controller.ts @@ -1,5 +1,5 @@ /* - * Copyright © 2024 Hexastack. All rights reserved. + * Copyright © 2025 Hexastack. All rights reserved. * * Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms: * 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission. @@ -11,6 +11,8 @@ import { Body, Controller, Get, + Headers, + Inject, InternalServerErrorException, Param, Post, @@ -21,7 +23,9 @@ import { UseGuards, UseInterceptors, } from '@nestjs/common'; +import { EventEmitter2 } from '@nestjs/event-emitter'; import { CsrfCheck, CsrfGen, CsrfGenAuth } from '@tekuconcept/nestjs-csrf'; +import cookie from 'cookie'; import { Request, Response } from 'express'; import { Session as ExpressSession } from 'express-session'; @@ -38,6 +42,9 @@ import { UserService } from '../services/user.service'; import { ValidateAccountService } from '../services/validate-account.service'; export class BaseAuthController { + @Inject(EventEmitter2) + private readonly eventEmitter: EventEmitter2; + constructor(protected readonly logger: LoggerService) {} /** @@ -66,7 +73,13 @@ export class BaseAuthController { logout( @Session() session: ExpressSession, @Res({ passthrough: true }) res: Response, + @Headers() headers: Record, ) { + const parsedCookie = cookie.parse(headers['cookie']); + const sessionCookie = encodeURIComponent( + String(parsedCookie[config.session.name] || ''), + ); + this.eventEmitter.emit('hook:websocket:session_data', sessionCookie); res.clearCookie(config.session.name); session.destroy((error) => { diff --git a/api/src/websocket/websocket.gateway.ts b/api/src/websocket/websocket.gateway.ts index 10c7c628..85ab1a72 100644 --- a/api/src/websocket/websocket.gateway.ts +++ b/api/src/websocket/websocket.gateway.ts @@ -1,12 +1,12 @@ /* - * Copyright © 2024 Hexastack. All rights reserved. + * Copyright © 2025 Hexastack. All rights reserved. * * Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms: * 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission. * 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file). */ -import { EventEmitter2 } from '@nestjs/event-emitter'; +import { EventEmitter2, OnEvent } from '@nestjs/event-emitter'; import { ConnectedSocket, MessageBody, @@ -258,6 +258,17 @@ export class WebsocketGateway this.eventEmitter.emit(`hook:websocket:connection`, client); } + @OnEvent('hook:websocket:session_data') + disconnectSockets(sessionCookie: string) { + if (sessionCookie.length) { + for (const [socketId, socket] of this.io.sockets.sockets) { + if (socket.handshake.headers.cookie?.includes(sessionCookie)) { + this.io.sockets.sockets.get(socketId)?.disconnect(true); + } + } + } + } + async handleDisconnect(client: Socket): Promise { this.logger.log(`Client id:${client.id} disconnected`); // Configurable custom afterDisconnect logic here diff --git a/api/types/event-emitter.d.ts b/api/types/event-emitter.d.ts index a39d15cf..4c46f1ea 100644 --- a/api/types/event-emitter.d.ts +++ b/api/types/event-emitter.d.ts @@ -1,5 +1,5 @@ /* - * Copyright © 2024 Hexastack. All rights reserved. + * Copyright © 2025 Hexastack. All rights reserved. * * Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms: * 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission. @@ -116,6 +116,7 @@ declare module '@nestjs/event-emitter' { object, { connection: Socket; + session_data: string; } >; } diff --git a/package-lock.json b/package-lock.json index 2372b00e..a201be15 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "hexabot", - "version": "2.2.2", + "version": "2.2.3", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "hexabot", - "version": "2.2.2", + "version": "2.2.3", "license": "AGPL-3.0-only", "workspaces": [ "frontend", From 1492b7cdeb0f03871cd25ccd8c6ca6e9eda33853 Mon Sep 17 00:00:00 2001 From: yassinedorbozgithub Date: Wed, 29 Jan 2025 11:17:53 +0100 Subject: [PATCH 17/49] fix: close channel on unmount --- frontend/src/hooks/useBroadcastChannel.ts | 5 ++++- widget/src/hooks/useBroadcastChannel.ts | 5 ++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/frontend/src/hooks/useBroadcastChannel.ts b/frontend/src/hooks/useBroadcastChannel.ts index 32172c31..8e718996 100644 --- a/frontend/src/hooks/useBroadcastChannel.ts +++ b/frontend/src/hooks/useBroadcastChannel.ts @@ -101,6 +101,9 @@ function useChannelEventListener( channel.addEventListener(event, callback); - return () => channel.removeEventListener(event, callback); + return () => { + channel.close(); + channel.removeEventListener(event, callback); + }; }, [channel, event]); } diff --git a/widget/src/hooks/useBroadcastChannel.ts b/widget/src/hooks/useBroadcastChannel.ts index 32172c31..8e718996 100644 --- a/widget/src/hooks/useBroadcastChannel.ts +++ b/widget/src/hooks/useBroadcastChannel.ts @@ -101,6 +101,9 @@ function useChannelEventListener( channel.addEventListener(event, callback); - return () => channel.removeEventListener(event, callback); + return () => { + channel.close(); + channel.removeEventListener(event, callback); + }; }, [channel, event]); } From 34e10fa8aa12d34087d80bf2724e4698d0165012 Mon Sep 17 00:00:00 2001 From: yassinedorbozgithub Date: Wed, 29 Jan 2025 11:54:19 +0100 Subject: [PATCH 18/49] fix: apply feedback update --- frontend/src/contexts/auth.context.tsx | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/frontend/src/contexts/auth.context.tsx b/frontend/src/contexts/auth.context.tsx index 41e4c81f..d6b72228 100644 --- a/frontend/src/contexts/auth.context.tsx +++ b/frontend/src/contexts/auth.context.tsx @@ -108,8 +108,10 @@ export const AuthProvider = ({ children }: AuthProviderProps): JSX.Element => { setIsReady(true); }, []); - useBroadcastChannel("session", () => { - router.reload(); + useBroadcastChannel("session", (e) => { + if (e.data === "logout") { + router.reload(); + } }); if (!isReady || isLoading) return ; From e3d113470b533169429825c5cc2b0230c43b1a0e Mon Sep 17 00:00:00 2001 From: yassinedorbozgithub Date: Wed, 29 Jan 2025 12:56:07 +0100 Subject: [PATCH 19/49] feat: add uuid to restrict broadcast to other tabs --- frontend/src/contexts/auth.context.tsx | 6 ++++- frontend/src/hooks/entities/auth-hooks.ts | 8 +++++- frontend/src/hooks/useBroadcastChannel.ts | 23 ++++++++--------- frontend/src/hooks/useTabUuid.ts | 30 +++++++++++++++++++++++ widget/src/hooks/useBroadcastChannel.ts | 23 ++++++++--------- widget/src/hooks/useTabUuid.ts | 30 +++++++++++++++++++++++ widget/src/providers/ChatProvider.tsx | 9 ++++--- widget/src/utils/generateId.ts | 21 ++++++++++++++++ widget/src/utils/safeRandom.ts | 16 ++++++++++++ 9 files changed, 139 insertions(+), 27 deletions(-) create mode 100644 frontend/src/hooks/useTabUuid.ts create mode 100644 widget/src/hooks/useTabUuid.ts create mode 100644 widget/src/utils/generateId.ts create mode 100644 widget/src/utils/safeRandom.ts diff --git a/frontend/src/contexts/auth.context.tsx b/frontend/src/contexts/auth.context.tsx index d6b72228..7fac0e86 100644 --- a/frontend/src/contexts/auth.context.tsx +++ b/frontend/src/contexts/auth.context.tsx @@ -22,6 +22,7 @@ import { useLogout } from "@/hooks/entities/auth-hooks"; import { useApiClient } from "@/hooks/useApiClient"; import { CURRENT_USER_KEY, PUBLIC_PATHS } from "@/hooks/useAuth"; import { useBroadcastChannel } from "@/hooks/useBroadcastChannel"; +import { useTabUuid } from "@/hooks/useTabUuid"; import { useTranslate } from "@/hooks/useTranslate"; import { RouterType } from "@/services/types"; import { IUser } from "@/types/user.types"; @@ -108,8 +109,11 @@ export const AuthProvider = ({ children }: AuthProviderProps): JSX.Element => { setIsReady(true); }, []); + const tabUuidRef = useTabUuid(); + const tabUuid = tabUuidRef.current; + useBroadcastChannel("session", (e) => { - if (e.data === "logout") { + if (e.data.value === "logout" && e.data.uuid !== tabUuid) { router.reload(); } }); diff --git a/frontend/src/hooks/entities/auth-hooks.ts b/frontend/src/hooks/entities/auth-hooks.ts index 86d52d6d..60a69094 100755 --- a/frontend/src/hooks/entities/auth-hooks.ts +++ b/frontend/src/hooks/entities/auth-hooks.ts @@ -23,6 +23,7 @@ import { useFind } from "../crud/useFind"; import { useApiClient } from "../useApiClient"; import { CURRENT_USER_KEY, useAuth, useLogoutRedirection } from "../useAuth"; import { useBroadcastChannel } from "../useBroadcastChannel"; +import { useTabUuid } from "../useTabUuid"; import { useToast } from "../useToast"; import { useTranslate } from "../useTranslate"; @@ -60,6 +61,8 @@ export const useLogout = ( const { toast } = useToast(); const { t } = useTranslate(); const broadcastLogoutAcrossTabs = useBroadcastChannel("session"); + const tabUuidRef = useTabUuid(); + const tabUuid = tabUuidRef.current; return useMutation({ ...options, @@ -70,7 +73,10 @@ export const useLogout = ( }, onSuccess: async () => { queryClient.removeQueries([CURRENT_USER_KEY]); - broadcastLogoutAcrossTabs("logout"); + broadcastLogoutAcrossTabs({ + value: "logout", + uuid: tabUuid || "", + }); await logoutRedirection(); toast.success(t("message.logout_success")); }, diff --git a/frontend/src/hooks/useBroadcastChannel.ts b/frontend/src/hooks/useBroadcastChannel.ts index 8e718996..4d4417a2 100644 --- a/frontend/src/hooks/useBroadcastChannel.ts +++ b/frontend/src/hooks/useBroadcastChannel.ts @@ -8,13 +8,10 @@ import * as React from "react"; -export type BroadcastChannelData = - | string - | number - | boolean - | Record - | undefined - | null; +export type BroadcastChannelData = { + uuid: string; + value: string | number | boolean | Record | undefined | null; +}; /** * React hook to create and manage a Broadcast Channel across multiple browser windows. @@ -24,10 +21,12 @@ export type BroadcastChannelData = * @param handleMessageError [optional] Callback to handle the event generated when `error` is received. * @returns A function to send/post message on the channel. */ -export function useBroadcastChannel( +export function useBroadcastChannel< + T extends BroadcastChannelData = BroadcastChannelData, +>( channelName: string, - handleMessage?: (event: MessageEvent) => void, - handleMessageError?: (event: MessageEvent) => void, + handleMessage?: (event: MessageEvent) => void, + handleMessageError?: (event: MessageEvent) => void, ): (data: T) => void { const channelRef = React.useRef( typeof window !== "undefined" && "BroadcastChannel" in window @@ -52,7 +51,9 @@ export function useBroadcastChannel( * @param initialState Initial state. * @returns Tuple of state and setter for the state. */ -export function useBroadcastState( +export function useBroadcastState< + T extends BroadcastChannelData = BroadcastChannelData, +>( channelName: string, initialState: T, ): [T, React.Dispatch>, boolean] { diff --git a/frontend/src/hooks/useTabUuid.ts b/frontend/src/hooks/useTabUuid.ts new file mode 100644 index 00000000..50f07020 --- /dev/null +++ b/frontend/src/hooks/useTabUuid.ts @@ -0,0 +1,30 @@ +/* + * Copyright © 2025 Hexastack. All rights reserved. + * + * Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms: + * 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission. + * 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file). + */ + +import { useEffect, useRef } from "react"; + +import { generateId } from "@/utils/generateId"; + +export const useTabUuid = (key: string = "tab_uuid") => { + const tabUuidRef = useRef(null); + + useEffect(() => { + const storedUuid = sessionStorage.getItem(key); + + if (storedUuid) { + tabUuidRef.current = storedUuid; + } else { + const newUuid = generateId(); + + sessionStorage.setItem(key, newUuid); + tabUuidRef.current = newUuid; + } + }, []); + + return tabUuidRef; +}; diff --git a/widget/src/hooks/useBroadcastChannel.ts b/widget/src/hooks/useBroadcastChannel.ts index 8e718996..4d4417a2 100644 --- a/widget/src/hooks/useBroadcastChannel.ts +++ b/widget/src/hooks/useBroadcastChannel.ts @@ -8,13 +8,10 @@ import * as React from "react"; -export type BroadcastChannelData = - | string - | number - | boolean - | Record - | undefined - | null; +export type BroadcastChannelData = { + uuid: string; + value: string | number | boolean | Record | undefined | null; +}; /** * React hook to create and manage a Broadcast Channel across multiple browser windows. @@ -24,10 +21,12 @@ export type BroadcastChannelData = * @param handleMessageError [optional] Callback to handle the event generated when `error` is received. * @returns A function to send/post message on the channel. */ -export function useBroadcastChannel( +export function useBroadcastChannel< + T extends BroadcastChannelData = BroadcastChannelData, +>( channelName: string, - handleMessage?: (event: MessageEvent) => void, - handleMessageError?: (event: MessageEvent) => void, + handleMessage?: (event: MessageEvent) => void, + handleMessageError?: (event: MessageEvent) => void, ): (data: T) => void { const channelRef = React.useRef( typeof window !== "undefined" && "BroadcastChannel" in window @@ -52,7 +51,9 @@ export function useBroadcastChannel( * @param initialState Initial state. * @returns Tuple of state and setter for the state. */ -export function useBroadcastState( +export function useBroadcastState< + T extends BroadcastChannelData = BroadcastChannelData, +>( channelName: string, initialState: T, ): [T, React.Dispatch>, boolean] { diff --git a/widget/src/hooks/useTabUuid.ts b/widget/src/hooks/useTabUuid.ts new file mode 100644 index 00000000..02363252 --- /dev/null +++ b/widget/src/hooks/useTabUuid.ts @@ -0,0 +1,30 @@ +/* + * Copyright © 2025 Hexastack. All rights reserved. + * + * Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms: + * 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission. + * 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file). + */ + +import { useEffect, useRef } from "react"; + +import { generateId } from "../utils/generateId"; + +export const useTabUuid = (key: string = "tab_uuid") => { + const tabUuidRef = useRef(null); + + useEffect(() => { + const storedUuid = sessionStorage.getItem(key); + + if (storedUuid) { + tabUuidRef.current = storedUuid; + } else { + const newUuid = generateId(); + + sessionStorage.setItem(key, newUuid); + tabUuidRef.current = newUuid; + } + }, []); + + return tabUuidRef; +}; diff --git a/widget/src/providers/ChatProvider.tsx b/widget/src/providers/ChatProvider.tsx index f907c428..cf05da4f 100644 --- a/widget/src/providers/ChatProvider.tsx +++ b/widget/src/providers/ChatProvider.tsx @@ -17,6 +17,7 @@ import React, { } from "react"; import { useBroadcastChannel } from "../hooks/useBroadcastChannel"; +import { useTabUuid } from "../hooks/useTabUuid"; import { StdEventType } from "../types/chat-io-messages.types"; import { Direction, @@ -269,7 +270,7 @@ const ChatProvider: React.FC<{ content_type: QuickReplyType.text, text: qr.title, payload: qr.payload, - }) as ISuggestion, + } as ISuggestion), ), ); } else { @@ -452,9 +453,11 @@ const ChatProvider: React.FC<{ setMessage, handleSubscription, }; + const tabUuidRef = useTabUuid(); + const tabUuid = tabUuidRef.current; - useBroadcastChannel("session", (e) => { - if (e.data === "logout") { + useBroadcastChannel("session", ({ data }) => { + if (data.value === "logout" && data.uuid !== tabUuid) { socketCtx.socket.disconnect(); } }); diff --git a/widget/src/utils/generateId.ts b/widget/src/utils/generateId.ts new file mode 100644 index 00000000..44078912 --- /dev/null +++ b/widget/src/utils/generateId.ts @@ -0,0 +1,21 @@ +/* + * Copyright © 2025 Hexastack. All rights reserved. + * + * Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms: + * 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission. + * 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file). + */ + + +import { getRandom } from "./safeRandom"; + +export const generateId = () => { + const d = + typeof performance === "undefined" ? Date.now() : performance.now() * 1000; + + return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => { + const r = (getRandom() * 16 + d) % 16 | 0; + + return (c == "x" ? r : (r & 0x3) | 0x8).toString(16); + }); +}; diff --git a/widget/src/utils/safeRandom.ts b/widget/src/utils/safeRandom.ts new file mode 100644 index 00000000..a344522b --- /dev/null +++ b/widget/src/utils/safeRandom.ts @@ -0,0 +1,16 @@ +/* + * Copyright © 2025 Hexastack. All rights reserved. + * + * Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms: + * 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission. + * 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file). + */ + + +/** + * Return a cryptographically secure random value between 0 and 1 + * + * @returns A cryptographically secure random value between 0 and 1 + */ +export const getRandom = (): number => + window.crypto.getRandomValues(new Uint32Array(1))[0] * Math.pow(2, -32); From 83c85c31a7eca0f719edddb97054dcf87d2244cd Mon Sep 17 00:00:00 2001 From: yassinedorbozgithub Date: Wed, 29 Jan 2025 13:01:22 +0100 Subject: [PATCH 20/49] fix: update useTabUuid --- widget/src/hooks/useTabUuid.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/widget/src/hooks/useTabUuid.ts b/widget/src/hooks/useTabUuid.ts index 02363252..13cf48a3 100644 --- a/widget/src/hooks/useTabUuid.ts +++ b/widget/src/hooks/useTabUuid.ts @@ -24,6 +24,7 @@ export const useTabUuid = (key: string = "tab_uuid") => { sessionStorage.setItem(key, newUuid); tabUuidRef.current = newUuid; } + // eslint-disable-next-line react-hooks/exhaustive-deps }, []); return tabUuidRef; From 79cb85f74f4ac5778ff646189a8a2c11dea04da3 Mon Sep 17 00:00:00 2001 From: yassinedorbozgithub Date: Wed, 29 Jan 2025 14:50:05 +0100 Subject: [PATCH 21/49] fix: logout disconnection sockets --- api/src/user/controllers/auth.controller.ts | 15 ++++++++++++++- api/src/websocket/websocket.gateway.ts | 15 +++++++++++++-- api/types/event-emitter.d.ts | 4 ++-- 3 files changed, 29 insertions(+), 5 deletions(-) diff --git a/api/src/user/controllers/auth.controller.ts b/api/src/user/controllers/auth.controller.ts index 559bc2ee..fc5e1341 100644 --- a/api/src/user/controllers/auth.controller.ts +++ b/api/src/user/controllers/auth.controller.ts @@ -1,5 +1,5 @@ /* - * Copyright © 2024 Hexastack. All rights reserved. + * Copyright © 2025 Hexastack. All rights reserved. * * Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms: * 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission. @@ -11,6 +11,8 @@ import { Body, Controller, Get, + Headers, + Inject, InternalServerErrorException, Param, Post, @@ -21,7 +23,9 @@ import { UseGuards, UseInterceptors, } from '@nestjs/common'; +import { EventEmitter2 } from '@nestjs/event-emitter'; import { CsrfCheck, CsrfGen, CsrfGenAuth } from '@tekuconcept/nestjs-csrf'; +import cookie from 'cookie'; import { Request, Response } from 'express'; import { Session as ExpressSession } from 'express-session'; @@ -38,6 +42,9 @@ import { UserService } from '../services/user.service'; import { ValidateAccountService } from '../services/validate-account.service'; export class BaseAuthController { + @Inject(EventEmitter2) + private readonly eventEmitter: EventEmitter2; + constructor(protected readonly logger: LoggerService) {} /** @@ -66,7 +73,13 @@ export class BaseAuthController { logout( @Session() session: ExpressSession, @Res({ passthrough: true }) res: Response, + @Headers() headers: Record, ) { + const parsedCookie = cookie.parse(headers['cookie']); + const sessionCookie = encodeURIComponent( + String(parsedCookie[config.session.name] || ''), + ); + this.eventEmitter.emit('hook:user:logout', sessionCookie); res.clearCookie(config.session.name); session.destroy((error) => { diff --git a/api/src/websocket/websocket.gateway.ts b/api/src/websocket/websocket.gateway.ts index 10c7c628..0477d6ee 100644 --- a/api/src/websocket/websocket.gateway.ts +++ b/api/src/websocket/websocket.gateway.ts @@ -1,12 +1,12 @@ /* - * Copyright © 2024 Hexastack. All rights reserved. + * Copyright © 2025 Hexastack. All rights reserved. * * Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms: * 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission. * 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file). */ -import { EventEmitter2 } from '@nestjs/event-emitter'; +import { EventEmitter2, OnEvent } from '@nestjs/event-emitter'; import { ConnectedSocket, MessageBody, @@ -258,6 +258,17 @@ export class WebsocketGateway this.eventEmitter.emit(`hook:websocket:connection`, client); } + @OnEvent('hook:user:logout') + disconnectSockets(sessionCookie: string) { + if (sessionCookie.length) { + for (const [socketId, socket] of this.io.sockets.sockets) { + if (socket.handshake.headers.cookie?.includes(sessionCookie)) { + this.io.sockets.sockets.get(socketId)?.disconnect(true); + } + } + } + } + async handleDisconnect(client: Socket): Promise { this.logger.log(`Client id:${client.id} disconnected`); // Configurable custom afterDisconnect logic here diff --git a/api/types/event-emitter.d.ts b/api/types/event-emitter.d.ts index a39d15cf..9af687ce 100644 --- a/api/types/event-emitter.d.ts +++ b/api/types/event-emitter.d.ts @@ -1,5 +1,5 @@ /* - * Copyright © 2024 Hexastack. All rights reserved. + * Copyright © 2025 Hexastack. All rights reserved. * * Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms: * 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission. @@ -162,7 +162,7 @@ declare module '@nestjs/event-emitter' { model: TDefinition; permission: TDefinition; role: TDefinition; - user: TDefinition; + user: TDefinition; } /* entities hooks having schemas */ From 2587ee4e3beee8e4bf584928f231a64090063568 Mon Sep 17 00:00:00 2001 From: yassinedorbozgithub Date: Wed, 29 Jan 2025 14:55:32 +0100 Subject: [PATCH 22/49] fix: revert API updates --- api/src/user/controllers/auth.controller.ts | 15 +-------------- api/src/websocket/websocket.gateway.ts | 15 ++------------- api/types/event-emitter.d.ts | 3 +-- 3 files changed, 4 insertions(+), 29 deletions(-) diff --git a/api/src/user/controllers/auth.controller.ts b/api/src/user/controllers/auth.controller.ts index 5a49cb53..559bc2ee 100644 --- a/api/src/user/controllers/auth.controller.ts +++ b/api/src/user/controllers/auth.controller.ts @@ -1,5 +1,5 @@ /* - * Copyright © 2025 Hexastack. All rights reserved. + * Copyright © 2024 Hexastack. All rights reserved. * * Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms: * 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission. @@ -11,8 +11,6 @@ import { Body, Controller, Get, - Headers, - Inject, InternalServerErrorException, Param, Post, @@ -23,9 +21,7 @@ import { UseGuards, UseInterceptors, } from '@nestjs/common'; -import { EventEmitter2 } from '@nestjs/event-emitter'; import { CsrfCheck, CsrfGen, CsrfGenAuth } from '@tekuconcept/nestjs-csrf'; -import cookie from 'cookie'; import { Request, Response } from 'express'; import { Session as ExpressSession } from 'express-session'; @@ -42,9 +38,6 @@ import { UserService } from '../services/user.service'; import { ValidateAccountService } from '../services/validate-account.service'; export class BaseAuthController { - @Inject(EventEmitter2) - private readonly eventEmitter: EventEmitter2; - constructor(protected readonly logger: LoggerService) {} /** @@ -73,13 +66,7 @@ export class BaseAuthController { logout( @Session() session: ExpressSession, @Res({ passthrough: true }) res: Response, - @Headers() headers: Record, ) { - const parsedCookie = cookie.parse(headers['cookie']); - const sessionCookie = encodeURIComponent( - String(parsedCookie[config.session.name] || ''), - ); - this.eventEmitter.emit('hook:websocket:session_data', sessionCookie); res.clearCookie(config.session.name); session.destroy((error) => { diff --git a/api/src/websocket/websocket.gateway.ts b/api/src/websocket/websocket.gateway.ts index 85ab1a72..10c7c628 100644 --- a/api/src/websocket/websocket.gateway.ts +++ b/api/src/websocket/websocket.gateway.ts @@ -1,12 +1,12 @@ /* - * Copyright © 2025 Hexastack. All rights reserved. + * Copyright © 2024 Hexastack. All rights reserved. * * Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms: * 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission. * 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file). */ -import { EventEmitter2, OnEvent } from '@nestjs/event-emitter'; +import { EventEmitter2 } from '@nestjs/event-emitter'; import { ConnectedSocket, MessageBody, @@ -258,17 +258,6 @@ export class WebsocketGateway this.eventEmitter.emit(`hook:websocket:connection`, client); } - @OnEvent('hook:websocket:session_data') - disconnectSockets(sessionCookie: string) { - if (sessionCookie.length) { - for (const [socketId, socket] of this.io.sockets.sockets) { - if (socket.handshake.headers.cookie?.includes(sessionCookie)) { - this.io.sockets.sockets.get(socketId)?.disconnect(true); - } - } - } - } - async handleDisconnect(client: Socket): Promise { this.logger.log(`Client id:${client.id} disconnected`); // Configurable custom afterDisconnect logic here diff --git a/api/types/event-emitter.d.ts b/api/types/event-emitter.d.ts index 4c46f1ea..a39d15cf 100644 --- a/api/types/event-emitter.d.ts +++ b/api/types/event-emitter.d.ts @@ -1,5 +1,5 @@ /* - * Copyright © 2025 Hexastack. All rights reserved. + * Copyright © 2024 Hexastack. All rights reserved. * * Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms: * 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission. @@ -116,7 +116,6 @@ declare module '@nestjs/event-emitter' { object, { connection: Socket; - session_data: string; } >; } From 09ec35f520eb3dacb2e2dee3dfe3f73e28d15f33 Mon Sep 17 00:00:00 2001 From: yassinedorbozgithub Date: Wed, 29 Jan 2025 16:47:55 +0100 Subject: [PATCH 23/49] fix: add brodcastChannel HOC --- frontend/src/contexts/auth.context.tsx | 6 +- frontend/src/contexts/broadcast-channel.tsx | 48 ++++++++++++++ frontend/src/hooks/entities/auth-hooks.ts | 3 +- ...castChannel.ts => useBroadcastChannel.tsx} | 64 +++++++++---------- frontend/src/pages/_app.tsx | 21 +++--- 5 files changed, 94 insertions(+), 48 deletions(-) create mode 100644 frontend/src/contexts/broadcast-channel.tsx rename frontend/src/hooks/{useBroadcastChannel.ts => useBroadcastChannel.tsx} (63%) diff --git a/frontend/src/contexts/auth.context.tsx b/frontend/src/contexts/auth.context.tsx index 7fac0e86..e2ac9227 100644 --- a/frontend/src/contexts/auth.context.tsx +++ b/frontend/src/contexts/auth.context.tsx @@ -110,10 +110,10 @@ export const AuthProvider = ({ children }: AuthProviderProps): JSX.Element => { }, []); const tabUuidRef = useTabUuid(); - const tabUuid = tabUuidRef.current; + const { useBroadcast } = useBroadcastChannel(); - useBroadcastChannel("session", (e) => { - if (e.data.value === "logout" && e.data.uuid !== tabUuid) { + useBroadcast("session", (e) => { + if (e.data.value === "logout" && e.data.uuid !== tabUuidRef.current) { router.reload(); } }); diff --git a/frontend/src/contexts/broadcast-channel.tsx b/frontend/src/contexts/broadcast-channel.tsx new file mode 100644 index 00000000..b11fd2df --- /dev/null +++ b/frontend/src/contexts/broadcast-channel.tsx @@ -0,0 +1,48 @@ +/* + * Copyright © 2025 Hexastack. All rights reserved. + * + * Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms: + * 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission. + * 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file). + */ + +import { createContext } from "react"; + +import { useBroadcast } from "@/hooks/useBroadcastChannel"; + +export interface IBroadcastChannelContext { + useBroadcast: ( + channelName: string, + handleMessage?: (event: MessageEvent) => void, + handleMessageError?: (event: MessageEvent) => void, + ) => (data: BroadcastChannelData) => void; +} + +export type BroadcastChannelData = { + uuid: string; + value: string | number | boolean | Record | undefined | null; +}; + +export interface IBroadcastChannelProps { + children?: React.ReactNode; +} + +export const BroadcastChannelContext = createContext({ + useBroadcast: () => () => {}, +}); + +export const BroadcastChannelProvider: React.FC = ({ + children, +}) => { + return ( + + {children} + + ); +}; + +export default BroadcastChannelProvider; diff --git a/frontend/src/hooks/entities/auth-hooks.ts b/frontend/src/hooks/entities/auth-hooks.ts index 60a69094..f3687549 100755 --- a/frontend/src/hooks/entities/auth-hooks.ts +++ b/frontend/src/hooks/entities/auth-hooks.ts @@ -60,7 +60,8 @@ export const useLogout = ( const { logoutRedirection } = useLogoutRedirection(); const { toast } = useToast(); const { t } = useTranslate(); - const broadcastLogoutAcrossTabs = useBroadcastChannel("session"); + const { useBroadcast } = useBroadcastChannel(); + const broadcastLogoutAcrossTabs = useBroadcast("session"); const tabUuidRef = useTabUuid(); const tabUuid = tabUuidRef.current; diff --git a/frontend/src/hooks/useBroadcastChannel.ts b/frontend/src/hooks/useBroadcastChannel.tsx similarity index 63% rename from frontend/src/hooks/useBroadcastChannel.ts rename to frontend/src/hooks/useBroadcastChannel.tsx index 4d4417a2..b933ca53 100644 --- a/frontend/src/hooks/useBroadcastChannel.ts +++ b/frontend/src/hooks/useBroadcastChannel.tsx @@ -1,5 +1,5 @@ /* - * Copyright © 2025 Hexastack. All rights reserved. + * Copyright © 2024 Hexastack. All rights reserved. * * Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms: * 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission. @@ -7,27 +7,21 @@ */ import * as React from "react"; +import { useContext } from "react"; -export type BroadcastChannelData = { - uuid: string; - value: string | number | boolean | Record | undefined | null; -}; +import { + BroadcastChannelContext, + BroadcastChannelData, + IBroadcastChannelContext, +} from "@/contexts/broadcast-channel"; -/** - * React hook to create and manage a Broadcast Channel across multiple browser windows. - * - * @param channelName Static name of channel used across the browser windows. - * @param handleMessage Callback to handle the event generated when `message` is received. - * @param handleMessageError [optional] Callback to handle the event generated when `error` is received. - * @returns A function to send/post message on the channel. - */ -export function useBroadcastChannel< +export const useBroadcast = < T extends BroadcastChannelData = BroadcastChannelData, >( channelName: string, handleMessage?: (event: MessageEvent) => void, handleMessageError?: (event: MessageEvent) => void, -): (data: T) => void { +): ((data: T) => void) => { const channelRef = React.useRef( typeof window !== "undefined" && "BroadcastChannel" in window ? new BroadcastChannel(channelName + "-channel") @@ -42,26 +36,17 @@ export function useBroadcastChannel< ); return (data: T) => channelRef.current?.postMessage(data); -} +}; -/** - * React hook to manage state across browser windows. Has the similar signature as `React.useState`. - * - * @param channelName Static name of channel used across the browser windows. - * @param initialState Initial state. - * @returns Tuple of state and setter for the state. - */ -export function useBroadcastState< +export const useBroadcastState = < T extends BroadcastChannelData = BroadcastChannelData, >( channelName: string, initialState: T, -): [T, React.Dispatch>, boolean] { +): [T, React.Dispatch>, boolean] => { const [isPending, startTransition] = React.useTransition(); const [state, setState] = React.useState(initialState); - const broadcast = useBroadcastChannel(channelName, (ev) => - setState(ev.data), - ); + const broadcast = useBroadcast(channelName, (ev) => setState(ev.data)); const updateState: React.Dispatch> = React.useCallback( (input) => { @@ -77,16 +62,13 @@ export function useBroadcastState< ); return [state, updateState, isPending]; -} +}; -// Helpers - -/** Hook to subscribe/unsubscribe from channel events. */ -function useChannelEventListener( +const useChannelEventListener = ( channel: BroadcastChannel | null, event: K, handler?: (e: BroadcastChannelEventMap[K]) => void, -) { +) => { const callbackRef = React.useRef(handler); if (callbackRef.current !== handler) { @@ -107,4 +89,16 @@ function useChannelEventListener( channel.removeEventListener(event, callback); }; }, [channel, event]); -} +}; + +export const useBroadcastChannel = (): IBroadcastChannelContext => { + const context = useContext(BroadcastChannelContext); + + if (!context) { + throw new Error( + "useBroadcastChannel must be used within an BroadcastChannelContext", + ); + } + + return context; +}; diff --git a/frontend/src/pages/_app.tsx b/frontend/src/pages/_app.tsx index a0b2067d..4f69a198 100644 --- a/frontend/src/pages/_app.tsx +++ b/frontend/src/pages/_app.tsx @@ -19,6 +19,7 @@ import { ReactQueryDevtools } from "react-query/devtools"; import { SnackbarCloseButton } from "@/app-components/displays/Toast/CloseButton"; import { ApiClientProvider } from "@/contexts/apiClient.context"; import { AuthProvider } from "@/contexts/auth.context"; +import BroadcastChannelProvider from "@/contexts/broadcast-channel"; import { ConfigProvider } from "@/contexts/config.context"; import { PermissionProvider } from "@/contexts/permission.context"; import { SettingsProvider } from "@/contexts/setting.context"; @@ -83,15 +84,17 @@ const App = ({ Component, pageProps }: TAppPropsWithLayout) => { - - - - - {getLayout()} - - - - + + + + + + {getLayout()} + + + + + From 50406af6c2c346aac9db038d675629785f9b7b76 Mon Sep 17 00:00:00 2001 From: yassinedorbozgithub Date: Wed, 29 Jan 2025 17:01:06 +0100 Subject: [PATCH 24/49] fix: update useTabUuid hooks --- frontend/src/hooks/useTabUuid.ts | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/frontend/src/hooks/useTabUuid.ts b/frontend/src/hooks/useTabUuid.ts index 50f07020..2a8fdeb4 100644 --- a/frontend/src/hooks/useTabUuid.ts +++ b/frontend/src/hooks/useTabUuid.ts @@ -6,25 +6,23 @@ * 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file). */ -import { useEffect, useRef } from "react"; +import { useRef } from "react"; import { generateId } from "@/utils/generateId"; -export const useTabUuid = (key: string = "tab_uuid") => { - const tabUuidRef = useRef(null); +const getOrCreateTabId = () => { + let tabId = sessionStorage.getItem("tab_uuid"); - useEffect(() => { - const storedUuid = sessionStorage.getItem(key); + if (!tabId) { + tabId = generateId(); + sessionStorage.setItem("tab_uuid", tabId); + } - if (storedUuid) { - tabUuidRef.current = storedUuid; - } else { - const newUuid = generateId(); + return tabId; +}; - sessionStorage.setItem(key, newUuid); - tabUuidRef.current = newUuid; - } - }, []); +export const useTabUuid = () => { + const tabUuidRef = useRef(getOrCreateTabId()); return tabUuidRef; }; From 9844ae133c88ee573aac207d9722f8d6fd980f0a Mon Sep 17 00:00:00 2001 From: yassinedorbozgithub Date: Wed, 29 Jan 2025 17:01:47 +0100 Subject: [PATCH 25/49] fix(widget): update useTabUuid hooks --- widget/src/hooks/useTabUuid.ts | 25 +++++++++++-------------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/widget/src/hooks/useTabUuid.ts b/widget/src/hooks/useTabUuid.ts index 13cf48a3..759db158 100644 --- a/widget/src/hooks/useTabUuid.ts +++ b/widget/src/hooks/useTabUuid.ts @@ -6,26 +6,23 @@ * 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file). */ -import { useEffect, useRef } from "react"; +import { useRef } from "react"; import { generateId } from "../utils/generateId"; -export const useTabUuid = (key: string = "tab_uuid") => { - const tabUuidRef = useRef(null); +const getOrCreateTabId = () => { + let tabId = sessionStorage.getItem("tab_uuid"); - useEffect(() => { - const storedUuid = sessionStorage.getItem(key); + if (!tabId) { + tabId = generateId(); + sessionStorage.setItem("tab_uuid", tabId); + } - if (storedUuid) { - tabUuidRef.current = storedUuid; - } else { - const newUuid = generateId(); + return tabId; +}; - sessionStorage.setItem(key, newUuid); - tabUuidRef.current = newUuid; - } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); +export const useTabUuid = () => { + const tabUuidRef = useRef(getOrCreateTabId()); return tabUuidRef; }; From ce6c865fe6c19aa17379c622fa3ed2b88ac9e254 Mon Sep 17 00:00:00 2001 From: yassinedorbozgithub Date: Wed, 29 Jan 2025 17:16:36 +0100 Subject: [PATCH 26/49] fix(widget): add brodcastChannel HOC --- ...nnel.tsx => broadcast-channel.context.tsx} | 0 ...castChannel.tsx => useBroadcastChannel.ts} | 2 +- frontend/src/pages/_app.tsx | 2 +- widget/src/UiChatWidget.tsx | 25 ++++---- widget/src/hooks/useBroadcastChannel.ts | 64 +++++++++---------- .../providers/BroadcastChannelProvider.tsx | 49 ++++++++++++++ widget/src/providers/ChatProvider.tsx | 6 +- 7 files changed, 97 insertions(+), 51 deletions(-) rename frontend/src/contexts/{broadcast-channel.tsx => broadcast-channel.context.tsx} (100%) rename frontend/src/hooks/{useBroadcastChannel.tsx => useBroadcastChannel.ts} (98%) create mode 100644 widget/src/providers/BroadcastChannelProvider.tsx diff --git a/frontend/src/contexts/broadcast-channel.tsx b/frontend/src/contexts/broadcast-channel.context.tsx similarity index 100% rename from frontend/src/contexts/broadcast-channel.tsx rename to frontend/src/contexts/broadcast-channel.context.tsx diff --git a/frontend/src/hooks/useBroadcastChannel.tsx b/frontend/src/hooks/useBroadcastChannel.ts similarity index 98% rename from frontend/src/hooks/useBroadcastChannel.tsx rename to frontend/src/hooks/useBroadcastChannel.ts index b933ca53..81ec012c 100644 --- a/frontend/src/hooks/useBroadcastChannel.tsx +++ b/frontend/src/hooks/useBroadcastChannel.ts @@ -13,7 +13,7 @@ import { BroadcastChannelContext, BroadcastChannelData, IBroadcastChannelContext, -} from "@/contexts/broadcast-channel"; +} from "@/contexts/broadcast-channel.context"; export const useBroadcast = < T extends BroadcastChannelData = BroadcastChannelData, diff --git a/frontend/src/pages/_app.tsx b/frontend/src/pages/_app.tsx index 4f69a198..21c31c6e 100644 --- a/frontend/src/pages/_app.tsx +++ b/frontend/src/pages/_app.tsx @@ -19,7 +19,7 @@ import { ReactQueryDevtools } from "react-query/devtools"; import { SnackbarCloseButton } from "@/app-components/displays/Toast/CloseButton"; import { ApiClientProvider } from "@/contexts/apiClient.context"; import { AuthProvider } from "@/contexts/auth.context"; -import BroadcastChannelProvider from "@/contexts/broadcast-channel"; +import BroadcastChannelProvider from "@/contexts/broadcast-channel.context"; import { ConfigProvider } from "@/contexts/config.context"; import { PermissionProvider } from "@/contexts/permission.context"; import { SettingsProvider } from "@/contexts/setting.context"; diff --git a/widget/src/UiChatWidget.tsx b/widget/src/UiChatWidget.tsx index 96dc5de4..0e636a19 100644 --- a/widget/src/UiChatWidget.tsx +++ b/widget/src/UiChatWidget.tsx @@ -10,6 +10,7 @@ import { PropsWithChildren } from "react"; import Launcher from "./components/Launcher"; import UserSubscription from "./components/UserSubscription"; +import BroadcastChannelProvider from "./providers/BroadcastChannelProvider"; import ChatProvider from "./providers/ChatProvider"; import { ColorProvider } from "./providers/ColorProvider"; import { ConfigProvider } from "./providers/ConfigProvider"; @@ -41,17 +42,19 @@ function UiChatWidget({ - - - - - + + + + + + + diff --git a/widget/src/hooks/useBroadcastChannel.ts b/widget/src/hooks/useBroadcastChannel.ts index 4d4417a2..d23578e1 100644 --- a/widget/src/hooks/useBroadcastChannel.ts +++ b/widget/src/hooks/useBroadcastChannel.ts @@ -1,5 +1,5 @@ /* - * Copyright © 2025 Hexastack. All rights reserved. + * Copyright © 2024 Hexastack. All rights reserved. * * Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms: * 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission. @@ -7,27 +7,21 @@ */ import * as React from "react"; +import { useContext } from "react"; -export type BroadcastChannelData = { - uuid: string; - value: string | number | boolean | Record | undefined | null; -}; +import { + BroadcastChannelContext, + BroadcastChannelData, + IBroadcastChannelContext, +} from "../providers/BroadcastChannelProvider"; -/** - * React hook to create and manage a Broadcast Channel across multiple browser windows. - * - * @param channelName Static name of channel used across the browser windows. - * @param handleMessage Callback to handle the event generated when `message` is received. - * @param handleMessageError [optional] Callback to handle the event generated when `error` is received. - * @returns A function to send/post message on the channel. - */ -export function useBroadcastChannel< +export const useBroadcast = < T extends BroadcastChannelData = BroadcastChannelData, >( channelName: string, handleMessage?: (event: MessageEvent) => void, handleMessageError?: (event: MessageEvent) => void, -): (data: T) => void { +): ((data: T) => void) => { const channelRef = React.useRef( typeof window !== "undefined" && "BroadcastChannel" in window ? new BroadcastChannel(channelName + "-channel") @@ -42,26 +36,17 @@ export function useBroadcastChannel< ); return (data: T) => channelRef.current?.postMessage(data); -} +}; -/** - * React hook to manage state across browser windows. Has the similar signature as `React.useState`. - * - * @param channelName Static name of channel used across the browser windows. - * @param initialState Initial state. - * @returns Tuple of state and setter for the state. - */ -export function useBroadcastState< +export const useBroadcastState = < T extends BroadcastChannelData = BroadcastChannelData, >( channelName: string, initialState: T, -): [T, React.Dispatch>, boolean] { +): [T, React.Dispatch>, boolean] => { const [isPending, startTransition] = React.useTransition(); const [state, setState] = React.useState(initialState); - const broadcast = useBroadcastChannel(channelName, (ev) => - setState(ev.data), - ); + const broadcast = useBroadcast(channelName, (ev) => setState(ev.data)); const updateState: React.Dispatch> = React.useCallback( (input) => { @@ -77,16 +62,13 @@ export function useBroadcastState< ); return [state, updateState, isPending]; -} +}; -// Helpers - -/** Hook to subscribe/unsubscribe from channel events. */ -function useChannelEventListener( +const useChannelEventListener = ( channel: BroadcastChannel | null, event: K, handler?: (e: BroadcastChannelEventMap[K]) => void, -) { +) => { const callbackRef = React.useRef(handler); if (callbackRef.current !== handler) { @@ -107,4 +89,16 @@ function useChannelEventListener( channel.removeEventListener(event, callback); }; }, [channel, event]); -} +}; + +export const useBroadcastChannel = (): IBroadcastChannelContext => { + const context = useContext(BroadcastChannelContext); + + if (!context) { + throw new Error( + "useBroadcastChannel must be used within an BroadcastChannelContext", + ); + } + + return context; +}; diff --git a/widget/src/providers/BroadcastChannelProvider.tsx b/widget/src/providers/BroadcastChannelProvider.tsx new file mode 100644 index 00000000..ba323639 --- /dev/null +++ b/widget/src/providers/BroadcastChannelProvider.tsx @@ -0,0 +1,49 @@ +/* + * Copyright © 2025 Hexastack. All rights reserved. + * + * Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms: + * 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission. + * 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file). + */ + +import { createContext } from "react"; + +import { useBroadcast } from "../hooks/useBroadcastChannel"; + +export interface IBroadcastChannelContext { + useBroadcast: ( + channelName: string, + handleMessage?: (event: MessageEvent) => void, + handleMessageError?: (event: MessageEvent) => void, + ) => (data: BroadcastChannelData) => void; +} + +export type BroadcastChannelData = { + uuid: string; + value: string | number | boolean | Record | undefined | null; +}; + +export interface IBroadcastChannelProps { + children?: React.ReactNode; +} + +export const BroadcastChannelContext = createContext({ + useBroadcast: () => () => {}, +}); + +export const BroadcastChannelProvider: React.FC = ({ + // eslint-disable-next-line react/prop-types + children, +}) => { + return ( + + {children} + + ); +}; + +export default BroadcastChannelProvider; diff --git a/widget/src/providers/ChatProvider.tsx b/widget/src/providers/ChatProvider.tsx index cf05da4f..ff408791 100644 --- a/widget/src/providers/ChatProvider.tsx +++ b/widget/src/providers/ChatProvider.tsx @@ -454,10 +454,10 @@ const ChatProvider: React.FC<{ handleSubscription, }; const tabUuidRef = useTabUuid(); - const tabUuid = tabUuidRef.current; + const { useBroadcast } = useBroadcastChannel(); - useBroadcastChannel("session", ({ data }) => { - if (data.value === "logout" && data.uuid !== tabUuid) { + useBroadcast("session", ({ data }) => { + if (data.value === "logout" && data.uuid !== tabUuidRef.current) { socketCtx.socket.disconnect(); } }); From 30c142f5b63acf2f5710cb069e72746388218025 Mon Sep 17 00:00:00 2001 From: yassinedorbozgithub Date: Wed, 29 Jan 2025 17:23:20 +0100 Subject: [PATCH 27/49] fix(widget): resolve typecheck issue --- widget/src/providers/BroadcastChannelProvider.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/widget/src/providers/BroadcastChannelProvider.tsx b/widget/src/providers/BroadcastChannelProvider.tsx index ba323639..21af88c8 100644 --- a/widget/src/providers/BroadcastChannelProvider.tsx +++ b/widget/src/providers/BroadcastChannelProvider.tsx @@ -6,7 +6,7 @@ * 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file). */ -import { createContext } from "react"; +import { createContext, ReactNode } from "react"; import { useBroadcast } from "../hooks/useBroadcastChannel"; @@ -24,7 +24,7 @@ export type BroadcastChannelData = { }; export interface IBroadcastChannelProps { - children?: React.ReactNode; + children?: ReactNode; } export const BroadcastChannelContext = createContext({ From 961ca05d339b4e6de3a4837d7cc7be5aeada9962 Mon Sep 17 00:00:00 2001 From: yassinedorbozgithub Date: Wed, 29 Jan 2025 19:42:10 +0100 Subject: [PATCH 28/49] fix: enhance broadcast channel logic --- frontend/src/contexts/auth.context.tsx | 11 +- .../contexts/broadcast-channel.context.tsx | 111 ++++++++++++++---- frontend/src/hooks/entities/auth-hooks.ts | 13 +- frontend/src/hooks/useBroadcastChannel.ts | 104 ---------------- frontend/src/hooks/useTabUuid.ts | 14 ++- frontend/src/pages/_app.tsx | 2 +- widget/src/UiChatWidget.tsx | 2 +- widget/src/hooks/useBroadcastChannel.ts | 104 ---------------- widget/src/hooks/useTabUuid.ts | 14 ++- .../providers/BroadcastChannelProvider.tsx | 110 +++++++++++++---- widget/src/providers/ChatProvider.tsx | 10 +- 11 files changed, 211 insertions(+), 284 deletions(-) delete mode 100644 frontend/src/hooks/useBroadcastChannel.ts delete mode 100644 widget/src/hooks/useBroadcastChannel.ts diff --git a/frontend/src/contexts/auth.context.tsx b/frontend/src/contexts/auth.context.tsx index e2ac9227..eca0700f 100644 --- a/frontend/src/contexts/auth.context.tsx +++ b/frontend/src/contexts/auth.context.tsx @@ -21,13 +21,13 @@ import { Progress } from "@/app-components/displays/Progress"; import { useLogout } from "@/hooks/entities/auth-hooks"; import { useApiClient } from "@/hooks/useApiClient"; import { CURRENT_USER_KEY, PUBLIC_PATHS } from "@/hooks/useAuth"; -import { useBroadcastChannel } from "@/hooks/useBroadcastChannel"; -import { useTabUuid } from "@/hooks/useTabUuid"; import { useTranslate } from "@/hooks/useTranslate"; import { RouterType } from "@/services/types"; import { IUser } from "@/types/user.types"; import { getFromQuery } from "@/utils/URL"; +import { useBroadcastChannel } from "./broadcast-channel.context"; + export interface AuthContextValue { user: IUser | undefined; isAuthenticated: boolean; @@ -109,11 +109,10 @@ export const AuthProvider = ({ children }: AuthProviderProps): JSX.Element => { setIsReady(true); }, []); - const tabUuidRef = useTabUuid(); - const { useBroadcast } = useBroadcastChannel(); + const { subscribe } = useBroadcastChannel(); - useBroadcast("session", (e) => { - if (e.data.value === "logout" && e.data.uuid !== tabUuidRef.current) { + subscribe((message) => { + if (message.data === "logout") { router.reload(); } }); diff --git a/frontend/src/contexts/broadcast-channel.context.tsx b/frontend/src/contexts/broadcast-channel.context.tsx index b11fd2df..e6b8e588 100644 --- a/frontend/src/contexts/broadcast-channel.context.tsx +++ b/frontend/src/contexts/broadcast-channel.context.tsx @@ -6,43 +6,112 @@ * 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file). */ -import { createContext } from "react"; +import { + createContext, + FC, + ReactNode, + useContext, + useEffect, + useMemo, + useRef, +} from "react"; -import { useBroadcast } from "@/hooks/useBroadcastChannel"; - -export interface IBroadcastChannelContext { - useBroadcast: ( - channelName: string, - handleMessage?: (event: MessageEvent) => void, - handleMessageError?: (event: MessageEvent) => void, - ) => (data: BroadcastChannelData) => void; -} +import { useTabUuid } from "@/hooks/useTabUuid"; export type BroadcastChannelData = { - uuid: string; - value: string | number | boolean | Record | undefined | null; + tabId: string; + data: string | number | boolean | Record | undefined | null; }; export interface IBroadcastChannelProps { - children?: React.ReactNode; + channelName: string; + children?: ReactNode; } -export const BroadcastChannelContext = createContext({ - useBroadcast: () => () => {}, +export const BroadcastChannelContext = createContext<{ + subscribers: ((message: BroadcastChannelData) => void)[]; + subscribe: (callback: (message: BroadcastChannelData) => void) => () => void; + postMessage: (message: BroadcastChannelData) => void; +}>({ + subscribers: [], + subscribe: () => () => {}, + postMessage: () => {}, }); -export const BroadcastChannelProvider: React.FC = ({ +export const BroadcastChannelProvider: FC = ({ + channelName, children, }) => { + const channelRef = useRef(null); + const subscribersRef = useRef void>>( + [], + ); + const tabUuidRef = useTabUuid(); + + useEffect(() => { + const channel = new BroadcastChannel(channelName); + + channelRef.current = channel; + + const handleMessage = (event: MessageEvent) => { + const { tabId, data } = event.data; + + if (tabId === tabUuidRef.current) return; + + subscribersRef.current.forEach((callback) => callback(data)); + }; + + channel.addEventListener("message", handleMessage); + + return () => { + channel.removeEventListener("message", handleMessage); + channel.close(); + }; + }, [channelName, tabUuidRef]); + + const postMessage = (message: BroadcastChannelData) => { + channelRef.current?.postMessage({ + tabId: tabUuidRef.current, + data: message, + }); + }; + const subscribe = (callback: (message: BroadcastChannelData) => void) => { + subscribersRef.current.push(callback); + + return () => { + const index = subscribersRef.current.indexOf(callback); + + if (index !== -1) { + subscribersRef.current.splice(index, 1); + } + }; + }; + const contextValue = useMemo( + () => ({ + subscribers: subscribersRef.current, + subscribe, + postMessage, + }), + [], + ); + return ( - + {children} ); }; export default BroadcastChannelProvider; + +export const useBroadcastChannel = () => { + const context = useContext(BroadcastChannelContext); + + if (context === undefined) { + throw new Error( + "useBroadcastChannel must be used within a BroadcastChannelProvider", + ); + } + + return context; +}; diff --git a/frontend/src/hooks/entities/auth-hooks.ts b/frontend/src/hooks/entities/auth-hooks.ts index f3687549..105718c9 100755 --- a/frontend/src/hooks/entities/auth-hooks.ts +++ b/frontend/src/hooks/entities/auth-hooks.ts @@ -9,6 +9,7 @@ import { useEffect } from "react"; import { useMutation, useQuery, useQueryClient } from "react-query"; +import { useBroadcastChannel } from "@/contexts/broadcast-channel.context"; import { EntityType, TMutationOptions } from "@/services/types"; import { ILoginAttributes } from "@/types/auth/login.types"; import { @@ -22,7 +23,6 @@ import { useSocket } from "@/websocket/socket-hooks"; import { useFind } from "../crud/useFind"; import { useApiClient } from "../useApiClient"; import { CURRENT_USER_KEY, useAuth, useLogoutRedirection } from "../useAuth"; -import { useBroadcastChannel } from "../useBroadcastChannel"; import { useTabUuid } from "../useTabUuid"; import { useToast } from "../useToast"; import { useTranslate } from "../useTranslate"; @@ -60,10 +60,8 @@ export const useLogout = ( const { logoutRedirection } = useLogoutRedirection(); const { toast } = useToast(); const { t } = useTranslate(); - const { useBroadcast } = useBroadcastChannel(); - const broadcastLogoutAcrossTabs = useBroadcast("session"); - const tabUuidRef = useTabUuid(); - const tabUuid = tabUuidRef.current; + const { postMessage } = useBroadcastChannel(); + const uuid = useTabUuid(); return useMutation({ ...options, @@ -74,10 +72,7 @@ export const useLogout = ( }, onSuccess: async () => { queryClient.removeQueries([CURRENT_USER_KEY]); - broadcastLogoutAcrossTabs({ - value: "logout", - uuid: tabUuid || "", - }); + postMessage({ data: "logout", tabId: uuid.current || "" }); await logoutRedirection(); toast.success(t("message.logout_success")); }, diff --git a/frontend/src/hooks/useBroadcastChannel.ts b/frontend/src/hooks/useBroadcastChannel.ts deleted file mode 100644 index 81ec012c..00000000 --- a/frontend/src/hooks/useBroadcastChannel.ts +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright © 2024 Hexastack. All rights reserved. - * - * Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms: - * 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission. - * 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file). - */ - -import * as React from "react"; -import { useContext } from "react"; - -import { - BroadcastChannelContext, - BroadcastChannelData, - IBroadcastChannelContext, -} from "@/contexts/broadcast-channel.context"; - -export const useBroadcast = < - T extends BroadcastChannelData = BroadcastChannelData, ->( - channelName: string, - handleMessage?: (event: MessageEvent) => void, - handleMessageError?: (event: MessageEvent) => void, -): ((data: T) => void) => { - const channelRef = React.useRef( - typeof window !== "undefined" && "BroadcastChannel" in window - ? new BroadcastChannel(channelName + "-channel") - : null, - ); - - useChannelEventListener(channelRef.current, "message", handleMessage); - useChannelEventListener( - channelRef.current, - "messageerror", - handleMessageError, - ); - - return (data: T) => channelRef.current?.postMessage(data); -}; - -export const useBroadcastState = < - T extends BroadcastChannelData = BroadcastChannelData, ->( - channelName: string, - initialState: T, -): [T, React.Dispatch>, boolean] => { - const [isPending, startTransition] = React.useTransition(); - const [state, setState] = React.useState(initialState); - const broadcast = useBroadcast(channelName, (ev) => setState(ev.data)); - const updateState: React.Dispatch> = - React.useCallback( - (input) => { - setState((prev) => { - const newState = typeof input === "function" ? input(prev) : input; - - startTransition(() => broadcast(newState)); - - return newState; - }); - }, - [broadcast], - ); - - return [state, updateState, isPending]; -}; - -const useChannelEventListener = ( - channel: BroadcastChannel | null, - event: K, - handler?: (e: BroadcastChannelEventMap[K]) => void, -) => { - const callbackRef = React.useRef(handler); - - if (callbackRef.current !== handler) { - callbackRef.current = handler; - } - - React.useEffect(() => { - const callback = callbackRef.current; - - if (!channel || !callback) { - return; - } - - channel.addEventListener(event, callback); - - return () => { - channel.close(); - channel.removeEventListener(event, callback); - }; - }, [channel, event]); -}; - -export const useBroadcastChannel = (): IBroadcastChannelContext => { - const context = useContext(BroadcastChannelContext); - - if (!context) { - throw new Error( - "useBroadcastChannel must be used within an BroadcastChannelContext", - ); - } - - return context; -}; diff --git a/frontend/src/hooks/useTabUuid.ts b/frontend/src/hooks/useTabUuid.ts index 2a8fdeb4..5f86619f 100644 --- a/frontend/src/hooks/useTabUuid.ts +++ b/frontend/src/hooks/useTabUuid.ts @@ -11,18 +11,20 @@ import { useRef } from "react"; import { generateId } from "@/utils/generateId"; const getOrCreateTabId = () => { - let tabId = sessionStorage.getItem("tab_uuid"); + let storedTabId = sessionStorage.getItem("tab_uuid"); - if (!tabId) { - tabId = generateId(); - sessionStorage.setItem("tab_uuid", tabId); + if (storedTabId) { + return storedTabId; } - return tabId; + storedTabId = generateId(); + sessionStorage.setItem("tab_uuid", storedTabId); + + return storedTabId; }; export const useTabUuid = () => { - const tabUuidRef = useRef(getOrCreateTabId()); + const tabUuidRef = useRef(getOrCreateTabId()); return tabUuidRef; }; diff --git a/frontend/src/pages/_app.tsx b/frontend/src/pages/_app.tsx index 21c31c6e..583f91f1 100644 --- a/frontend/src/pages/_app.tsx +++ b/frontend/src/pages/_app.tsx @@ -84,7 +84,7 @@ const App = ({ Component, pageProps }: TAppPropsWithLayout) => { - + diff --git a/widget/src/UiChatWidget.tsx b/widget/src/UiChatWidget.tsx index 0e636a19..9dab8432 100644 --- a/widget/src/UiChatWidget.tsx +++ b/widget/src/UiChatWidget.tsx @@ -42,7 +42,7 @@ function UiChatWidget({ - + ( - channelName: string, - handleMessage?: (event: MessageEvent) => void, - handleMessageError?: (event: MessageEvent) => void, -): ((data: T) => void) => { - const channelRef = React.useRef( - typeof window !== "undefined" && "BroadcastChannel" in window - ? new BroadcastChannel(channelName + "-channel") - : null, - ); - - useChannelEventListener(channelRef.current, "message", handleMessage); - useChannelEventListener( - channelRef.current, - "messageerror", - handleMessageError, - ); - - return (data: T) => channelRef.current?.postMessage(data); -}; - -export const useBroadcastState = < - T extends BroadcastChannelData = BroadcastChannelData, ->( - channelName: string, - initialState: T, -): [T, React.Dispatch>, boolean] => { - const [isPending, startTransition] = React.useTransition(); - const [state, setState] = React.useState(initialState); - const broadcast = useBroadcast(channelName, (ev) => setState(ev.data)); - const updateState: React.Dispatch> = - React.useCallback( - (input) => { - setState((prev) => { - const newState = typeof input === "function" ? input(prev) : input; - - startTransition(() => broadcast(newState)); - - return newState; - }); - }, - [broadcast], - ); - - return [state, updateState, isPending]; -}; - -const useChannelEventListener = ( - channel: BroadcastChannel | null, - event: K, - handler?: (e: BroadcastChannelEventMap[K]) => void, -) => { - const callbackRef = React.useRef(handler); - - if (callbackRef.current !== handler) { - callbackRef.current = handler; - } - - React.useEffect(() => { - const callback = callbackRef.current; - - if (!channel || !callback) { - return; - } - - channel.addEventListener(event, callback); - - return () => { - channel.close(); - channel.removeEventListener(event, callback); - }; - }, [channel, event]); -}; - -export const useBroadcastChannel = (): IBroadcastChannelContext => { - const context = useContext(BroadcastChannelContext); - - if (!context) { - throw new Error( - "useBroadcastChannel must be used within an BroadcastChannelContext", - ); - } - - return context; -}; diff --git a/widget/src/hooks/useTabUuid.ts b/widget/src/hooks/useTabUuid.ts index 759db158..3f0b4018 100644 --- a/widget/src/hooks/useTabUuid.ts +++ b/widget/src/hooks/useTabUuid.ts @@ -11,18 +11,20 @@ import { useRef } from "react"; import { generateId } from "../utils/generateId"; const getOrCreateTabId = () => { - let tabId = sessionStorage.getItem("tab_uuid"); + let storedTabId = sessionStorage.getItem("tab_uuid"); - if (!tabId) { - tabId = generateId(); - sessionStorage.setItem("tab_uuid", tabId); + if (storedTabId) { + return storedTabId; } - return tabId; + storedTabId = generateId(); + sessionStorage.setItem("tab_uuid", storedTabId); + + return storedTabId; }; export const useTabUuid = () => { - const tabUuidRef = useRef(getOrCreateTabId()); + const tabUuidRef = useRef(getOrCreateTabId()); return tabUuidRef; }; diff --git a/widget/src/providers/BroadcastChannelProvider.tsx b/widget/src/providers/BroadcastChannelProvider.tsx index 21af88c8..c6d3fce7 100644 --- a/widget/src/providers/BroadcastChannelProvider.tsx +++ b/widget/src/providers/BroadcastChannelProvider.tsx @@ -6,44 +6,114 @@ * 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file). */ -import { createContext, ReactNode } from "react"; +import { + createContext, + FC, + ReactNode, + useContext, + useEffect, + useMemo, + useRef, +} from "react"; -import { useBroadcast } from "../hooks/useBroadcastChannel"; - -export interface IBroadcastChannelContext { - useBroadcast: ( - channelName: string, - handleMessage?: (event: MessageEvent) => void, - handleMessageError?: (event: MessageEvent) => void, - ) => (data: BroadcastChannelData) => void; -} +import { useTabUuid } from "../hooks/useTabUuid"; export type BroadcastChannelData = { - uuid: string; - value: string | number | boolean | Record | undefined | null; + tabId: string; + data: string | number | boolean | Record | undefined | null; }; export interface IBroadcastChannelProps { + channelName: string; children?: ReactNode; } -export const BroadcastChannelContext = createContext({ - useBroadcast: () => () => {}, +export const BroadcastChannelContext = createContext<{ + subscribers: ((message: BroadcastChannelData) => void)[]; + subscribe: (callback: (message: BroadcastChannelData) => void) => () => void; + postMessage: (message: BroadcastChannelData) => void; +}>({ + subscribers: [], + subscribe: () => () => {}, + postMessage: () => {}, }); -export const BroadcastChannelProvider: React.FC = ({ +export const BroadcastChannelProvider: FC = ({ + // eslint-disable-next-line react/prop-types + channelName, // eslint-disable-next-line react/prop-types children, }) => { + const channelRef = useRef(null); + const subscribersRef = useRef void>>( + [], + ); + const tabUuidRef = useTabUuid(); + + useEffect(() => { + const channel = new BroadcastChannel(channelName); + + channelRef.current = channel; + + const handleMessage = (event: MessageEvent) => { + const { tabId, data } = event.data; + + if (tabId === tabUuidRef.current) return; + + subscribersRef.current.forEach((callback) => callback(data)); + }; + + channel.addEventListener("message", handleMessage); + + return () => { + channel.removeEventListener("message", handleMessage); + channel.close(); + }; + }, [channelName, tabUuidRef]); + + const postMessage = (message: BroadcastChannelData) => { + channelRef.current?.postMessage({ + tabId: tabUuidRef.current, + data: message, + }); + }; + const subscribe = (callback: (message: BroadcastChannelData) => void) => { + subscribersRef.current.push(callback); + + return () => { + const index = subscribersRef.current.indexOf(callback); + + if (index !== -1) { + subscribersRef.current.splice(index, 1); + } + }; + }; + const contextValue = useMemo( + () => ({ + subscribers: subscribersRef.current, + subscribe, + postMessage, + }), + [], + ); + return ( - + {children} ); }; export default BroadcastChannelProvider; + +export const useBroadcastChannel = () => { + const context = useContext(BroadcastChannelContext); + + if (context === undefined) { + throw new Error( + "useBroadcastChannel must be used within a BroadcastChannelProvider", + ); + } + + return context; +}; diff --git a/widget/src/providers/ChatProvider.tsx b/widget/src/providers/ChatProvider.tsx index ff408791..9c4b952f 100644 --- a/widget/src/providers/ChatProvider.tsx +++ b/widget/src/providers/ChatProvider.tsx @@ -16,8 +16,6 @@ import React, { useState, } from "react"; -import { useBroadcastChannel } from "../hooks/useBroadcastChannel"; -import { useTabUuid } from "../hooks/useTabUuid"; import { StdEventType } from "../types/chat-io-messages.types"; import { Direction, @@ -31,6 +29,7 @@ import { } from "../types/message.types"; import { ConnectionState, OutgoingMessageState } from "../types/state.types"; +import { useBroadcastChannel } from "./BroadcastChannelProvider"; import { useConfig } from "./ConfigProvider"; import { useSettings } from "./SettingsProvider"; import { useSocket, useSubscribe } from "./SocketProvider"; @@ -453,11 +452,10 @@ const ChatProvider: React.FC<{ setMessage, handleSubscription, }; - const tabUuidRef = useTabUuid(); - const { useBroadcast } = useBroadcastChannel(); + const { subscribe } = useBroadcastChannel(); - useBroadcast("session", ({ data }) => { - if (data.value === "logout" && data.uuid !== tabUuidRef.current) { + subscribe(({ data }) => { + if (data === "logout") { socketCtx.socket.disconnect(); } }); From 859add934181d6ab2eb72bbb4180b8a060f80197 Mon Sep 17 00:00:00 2001 From: yassinedorbozgithub Date: Wed, 29 Jan 2025 19:44:30 +0100 Subject: [PATCH 29/49] fix(widget): resolve lint issue --- widget/src/providers/BroadcastChannelProvider.tsx | 1 + 1 file changed, 1 insertion(+) diff --git a/widget/src/providers/BroadcastChannelProvider.tsx b/widget/src/providers/BroadcastChannelProvider.tsx index c6d3fce7..fc3e7f1a 100644 --- a/widget/src/providers/BroadcastChannelProvider.tsx +++ b/widget/src/providers/BroadcastChannelProvider.tsx @@ -94,6 +94,7 @@ export const BroadcastChannelProvider: FC = ({ subscribe, postMessage, }), + // eslint-disable-next-line react-hooks/exhaustive-deps [], ); From b5d72761e49ce3abd4e22188fa932afe72971099 Mon Sep 17 00:00:00 2001 From: yassinedorbozgithub Date: Wed, 29 Jan 2025 19:47:31 +0100 Subject: [PATCH 30/49] fix(widget): resolve lint issue --- widget/src/providers/BroadcastChannelProvider.tsx | 2 -- 1 file changed, 2 deletions(-) diff --git a/widget/src/providers/BroadcastChannelProvider.tsx b/widget/src/providers/BroadcastChannelProvider.tsx index fc3e7f1a..f4e23d03 100644 --- a/widget/src/providers/BroadcastChannelProvider.tsx +++ b/widget/src/providers/BroadcastChannelProvider.tsx @@ -39,9 +39,7 @@ export const BroadcastChannelContext = createContext<{ }); export const BroadcastChannelProvider: FC = ({ - // eslint-disable-next-line react/prop-types channelName, - // eslint-disable-next-line react/prop-types children, }) => { const channelRef = useRef(null); From 9cc272567416000e234d38d0e3409fad033942f1 Mon Sep 17 00:00:00 2001 From: yassinedorbozgithub Date: Thu, 30 Jan 2025 08:23:56 +0100 Subject: [PATCH 31/49] fix: enhance logic --- frontend/src/contexts/auth.context.tsx | 11 +- .../contexts/broadcast-channel.context.tsx | 123 ++++++++++------- frontend/src/hooks/entities/auth-hooks.ts | 4 +- frontend/src/hooks/useTabUuid.ts | 30 ----- widget/src/hooks/useTabUuid.ts | 30 ----- .../providers/BroadcastChannelProvider.tsx | 126 +++++++++++------- widget/src/providers/ChatProvider.tsx | 13 +- 7 files changed, 163 insertions(+), 174 deletions(-) delete mode 100644 frontend/src/hooks/useTabUuid.ts delete mode 100644 widget/src/hooks/useTabUuid.ts diff --git a/frontend/src/contexts/auth.context.tsx b/frontend/src/contexts/auth.context.tsx index eca0700f..030c4269 100644 --- a/frontend/src/contexts/auth.context.tsx +++ b/frontend/src/contexts/auth.context.tsx @@ -101,21 +101,18 @@ export const AuthProvider = ({ children }: AuthProviderProps): JSX.Element => { setUser(user); }; const isAuthenticated = !!user; + const { subscribe } = useBroadcastChannel(); useEffect(() => { const search = location.search; setSearch(search); setIsReady(true); - }, []); - const { subscribe } = useBroadcastChannel(); - - subscribe((message) => { - if (message.data === "logout") { + subscribe("logout", () => { router.reload(); - } - }); + }); + }, []); if (!isReady || isLoading) return ; diff --git a/frontend/src/contexts/broadcast-channel.context.tsx b/frontend/src/contexts/broadcast-channel.context.tsx index e6b8e588..5363ab18 100644 --- a/frontend/src/contexts/broadcast-channel.context.tsx +++ b/frontend/src/contexts/broadcast-channel.context.tsx @@ -12,98 +12,123 @@ import { ReactNode, useContext, useEffect, - useMemo, useRef, } from "react"; -import { useTabUuid } from "@/hooks/useTabUuid"; +import { generateId } from "@/utils/generateId"; + +export enum EBCEvent { + LOGOUT = "logout", +} + +type BroadcastChannelPayload = { + event: `${EBCEvent}`; + data?: string | number | boolean | Record | undefined | null; +}; export type BroadcastChannelData = { tabId: string; - data: string | number | boolean | Record | undefined | null; + payload: BroadcastChannelPayload; }; export interface IBroadcastChannelProps { channelName: string; - children?: ReactNode; + children: ReactNode; } -export const BroadcastChannelContext = createContext<{ - subscribers: ((message: BroadcastChannelData) => void)[]; - subscribe: (callback: (message: BroadcastChannelData) => void) => () => void; - postMessage: (message: BroadcastChannelData) => void; -}>({ - subscribers: [], +const getOrCreateTabId = () => { + let storedTabId = sessionStorage.getItem("tab_uuid"); + + if (storedTabId) { + return storedTabId; + } + + storedTabId = generateId(); + sessionStorage.setItem("tab_uuid", storedTabId); + + return storedTabId; +}; + +interface IBroadcastChannelContext { + subscribe: ( + event: `${EBCEvent}`, + callback: (message: BroadcastChannelData) => void, + ) => () => void; + postMessage: (payload: BroadcastChannelPayload) => void; +} + +export const BroadcastChannelContext = createContext({ subscribe: () => () => {}, postMessage: () => {}, }); export const BroadcastChannelProvider: FC = ({ - channelName, children, + channelName, }) => { - const channelRef = useRef(null); - const subscribersRef = useRef void>>( - [], + const channelRef = useRef( + new BroadcastChannel(channelName), ); - const tabUuidRef = useTabUuid(); + const subscribersRef = useRef< + Record void>> + >({}); + const tabUuid = getOrCreateTabId(); useEffect(() => { - const channel = new BroadcastChannel(channelName); + const handleMessage = ({ data }: MessageEvent) => { + const { tabId, payload } = data; - channelRef.current = channel; + if (tabId === tabUuid) { + return; + } - const handleMessage = (event: MessageEvent) => { - const { tabId, data } = event.data; - - if (tabId === tabUuidRef.current) return; - - subscribersRef.current.forEach((callback) => callback(data)); + subscribersRef.current[payload.event]?.forEach((callback) => + callback(data), + ); }; - channel.addEventListener("message", handleMessage); + channelRef.current.addEventListener("message", handleMessage); return () => { - channel.removeEventListener("message", handleMessage); - channel.close(); + channelRef.current.removeEventListener("message", handleMessage); + channelRef.current.close(); }; - }, [channelName, tabUuidRef]); + }, []); - const postMessage = (message: BroadcastChannelData) => { - channelRef.current?.postMessage({ - tabId: tabUuidRef.current, - data: message, - }); - }; - const subscribe = (callback: (message: BroadcastChannelData) => void) => { - subscribersRef.current.push(callback); + const subscribe: IBroadcastChannelContext["subscribe"] = ( + event, + callback, + ) => { + subscribersRef.current[event] ??= []; + subscribersRef.current[event]?.push(callback); return () => { - const index = subscribersRef.current.indexOf(callback); + const index = subscribersRef.current[event]?.indexOf(callback) ?? -1; if (index !== -1) { - subscribersRef.current.splice(index, 1); + subscribersRef.current[event]?.splice(index, 1); } }; }; - const contextValue = useMemo( - () => ({ - subscribers: subscribersRef.current, - subscribe, - postMessage, - }), - [], - ); + const postMessage: IBroadcastChannelContext["postMessage"] = (payload) => { + channelRef.current?.postMessage({ + tabId: tabUuid, + payload, + }); + }; return ( - + {children} ); }; -export default BroadcastChannelProvider; - export const useBroadcastChannel = () => { const context = useContext(BroadcastChannelContext); @@ -115,3 +140,5 @@ export const useBroadcastChannel = () => { return context; }; + +export default BroadcastChannelProvider; diff --git a/frontend/src/hooks/entities/auth-hooks.ts b/frontend/src/hooks/entities/auth-hooks.ts index 105718c9..e6df15b3 100755 --- a/frontend/src/hooks/entities/auth-hooks.ts +++ b/frontend/src/hooks/entities/auth-hooks.ts @@ -23,7 +23,6 @@ import { useSocket } from "@/websocket/socket-hooks"; import { useFind } from "../crud/useFind"; import { useApiClient } from "../useApiClient"; import { CURRENT_USER_KEY, useAuth, useLogoutRedirection } from "../useAuth"; -import { useTabUuid } from "../useTabUuid"; import { useToast } from "../useToast"; import { useTranslate } from "../useTranslate"; @@ -61,7 +60,6 @@ export const useLogout = ( const { toast } = useToast(); const { t } = useTranslate(); const { postMessage } = useBroadcastChannel(); - const uuid = useTabUuid(); return useMutation({ ...options, @@ -72,7 +70,7 @@ export const useLogout = ( }, onSuccess: async () => { queryClient.removeQueries([CURRENT_USER_KEY]); - postMessage({ data: "logout", tabId: uuid.current || "" }); + postMessage({ event: "logout" }); await logoutRedirection(); toast.success(t("message.logout_success")); }, diff --git a/frontend/src/hooks/useTabUuid.ts b/frontend/src/hooks/useTabUuid.ts deleted file mode 100644 index 5f86619f..00000000 --- a/frontend/src/hooks/useTabUuid.ts +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright © 2025 Hexastack. All rights reserved. - * - * Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms: - * 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission. - * 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file). - */ - -import { useRef } from "react"; - -import { generateId } from "@/utils/generateId"; - -const getOrCreateTabId = () => { - let storedTabId = sessionStorage.getItem("tab_uuid"); - - if (storedTabId) { - return storedTabId; - } - - storedTabId = generateId(); - sessionStorage.setItem("tab_uuid", storedTabId); - - return storedTabId; -}; - -export const useTabUuid = () => { - const tabUuidRef = useRef(getOrCreateTabId()); - - return tabUuidRef; -}; diff --git a/widget/src/hooks/useTabUuid.ts b/widget/src/hooks/useTabUuid.ts deleted file mode 100644 index 3f0b4018..00000000 --- a/widget/src/hooks/useTabUuid.ts +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright © 2025 Hexastack. All rights reserved. - * - * Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms: - * 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission. - * 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file). - */ - -import { useRef } from "react"; - -import { generateId } from "../utils/generateId"; - -const getOrCreateTabId = () => { - let storedTabId = sessionStorage.getItem("tab_uuid"); - - if (storedTabId) { - return storedTabId; - } - - storedTabId = generateId(); - sessionStorage.setItem("tab_uuid", storedTabId); - - return storedTabId; -}; - -export const useTabUuid = () => { - const tabUuidRef = useRef(getOrCreateTabId()); - - return tabUuidRef; -}; diff --git a/widget/src/providers/BroadcastChannelProvider.tsx b/widget/src/providers/BroadcastChannelProvider.tsx index f4e23d03..b900c1df 100644 --- a/widget/src/providers/BroadcastChannelProvider.tsx +++ b/widget/src/providers/BroadcastChannelProvider.tsx @@ -12,99 +12,125 @@ import { ReactNode, useContext, useEffect, - useMemo, useRef, } from "react"; -import { useTabUuid } from "../hooks/useTabUuid"; +import { generateId } from "../utils/generateId"; + +export enum EBCEvent { + LOGOUT = "logout", +} + +type BroadcastChannelPayload = { + event: `${EBCEvent}`; + data?: string | number | boolean | Record | undefined | null; +}; export type BroadcastChannelData = { tabId: string; - data: string | number | boolean | Record | undefined | null; + payload: BroadcastChannelPayload; }; export interface IBroadcastChannelProps { channelName: string; - children?: ReactNode; + children: ReactNode; } -export const BroadcastChannelContext = createContext<{ - subscribers: ((message: BroadcastChannelData) => void)[]; - subscribe: (callback: (message: BroadcastChannelData) => void) => () => void; - postMessage: (message: BroadcastChannelData) => void; -}>({ - subscribers: [], +const getOrCreateTabId = () => { + let storedTabId = sessionStorage.getItem("tab_uuid"); + + if (storedTabId) { + return storedTabId; + } + + storedTabId = generateId(); + sessionStorage.setItem("tab_uuid", storedTabId); + + return storedTabId; +}; + +interface IBroadcastChannelContext { + subscribe: ( + event: `${EBCEvent}`, + callback: (message: BroadcastChannelData) => void, + ) => () => void; + postMessage: (payload: BroadcastChannelPayload) => void; +} + +export const BroadcastChannelContext = createContext({ subscribe: () => () => {}, postMessage: () => {}, }); export const BroadcastChannelProvider: FC = ({ - channelName, children, + channelName, }) => { - const channelRef = useRef(null); - const subscribersRef = useRef void>>( - [], + const channelRef = useRef( + new BroadcastChannel(channelName), ); - const tabUuidRef = useTabUuid(); + const subscribersRef = useRef< + Record void>> + >({}); + const tabUuid = getOrCreateTabId(); useEffect(() => { - const channel = new BroadcastChannel(channelName); + const handleMessage = ({ data }: MessageEvent) => { + const { tabId, payload } = data; - channelRef.current = channel; + if (tabId === tabUuid) { + return; + } - const handleMessage = (event: MessageEvent) => { - const { tabId, data } = event.data; - - if (tabId === tabUuidRef.current) return; - - subscribersRef.current.forEach((callback) => callback(data)); + subscribersRef.current[payload.event]?.forEach((callback) => + callback(data), + ); }; - channel.addEventListener("message", handleMessage); + channelRef.current.addEventListener("message", handleMessage); return () => { - channel.removeEventListener("message", handleMessage); - channel.close(); + channelRef.current.removeEventListener("message", handleMessage); + // eslint-disable-next-line react-hooks/exhaustive-deps + channelRef.current.close(); }; - }, [channelName, tabUuidRef]); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); - const postMessage = (message: BroadcastChannelData) => { - channelRef.current?.postMessage({ - tabId: tabUuidRef.current, - data: message, - }); - }; - const subscribe = (callback: (message: BroadcastChannelData) => void) => { - subscribersRef.current.push(callback); + const subscribe: IBroadcastChannelContext["subscribe"] = ( + event, + callback, + ) => { + subscribersRef.current[event] ??= []; + subscribersRef.current[event]?.push(callback); return () => { - const index = subscribersRef.current.indexOf(callback); + const index = subscribersRef.current[event]?.indexOf(callback) ?? -1; if (index !== -1) { - subscribersRef.current.splice(index, 1); + subscribersRef.current[event]?.splice(index, 1); } }; }; - const contextValue = useMemo( - () => ({ - subscribers: subscribersRef.current, - subscribe, - postMessage, - }), - // eslint-disable-next-line react-hooks/exhaustive-deps - [], - ); + const postMessage: IBroadcastChannelContext["postMessage"] = (payload) => { + channelRef.current?.postMessage({ + tabId: tabUuid, + payload, + }); + }; return ( - + {children} ); }; -export default BroadcastChannelProvider; - export const useBroadcastChannel = () => { const context = useContext(BroadcastChannelContext); @@ -116,3 +142,5 @@ export const useBroadcastChannel = () => { return context; }; + +export default BroadcastChannelProvider; diff --git a/widget/src/providers/ChatProvider.tsx b/widget/src/providers/ChatProvider.tsx index 9c4b952f..9a8ba246 100644 --- a/widget/src/providers/ChatProvider.tsx +++ b/widget/src/providers/ChatProvider.tsx @@ -385,6 +385,8 @@ const ChatProvider: React.FC<{ } }, [syncState, isOpen]); + const { subscribe } = useBroadcastChannel(); + useEffect(() => { if (screen === "chat" && connectionState === ConnectionState.connected) { handleSubscription(); @@ -404,6 +406,10 @@ const ChatProvider: React.FC<{ socketCtx.socket.io.on("reconnect", reSubscribe); + subscribe("logout", () => { + socketCtx.socket.disconnect(); + }); + return () => { socketCtx.socket.io.off("reconnect", reSubscribe); }; @@ -452,13 +458,6 @@ const ChatProvider: React.FC<{ setMessage, handleSubscription, }; - const { subscribe } = useBroadcastChannel(); - - subscribe(({ data }) => { - if (data === "logout") { - socketCtx.socket.disconnect(); - } - }); return ( {children} From 6e026830c890d0be972fe4ca4312adadb16665fe Mon Sep 17 00:00:00 2001 From: yassinedorbozgithub Date: Thu, 30 Jan 2025 08:51:08 +0100 Subject: [PATCH 32/49] fix: add useSubscribeBroadcastChannel --- .../src/hooks/useSubscribeBroadcastChannel.ts | 24 +++++++++++++++++++ .../providers/BroadcastChannelProvider.tsx | 4 ++-- widget/src/providers/ChatProvider.tsx | 10 ++++---- 3 files changed, 30 insertions(+), 8 deletions(-) create mode 100644 widget/src/hooks/useSubscribeBroadcastChannel.ts diff --git a/widget/src/hooks/useSubscribeBroadcastChannel.ts b/widget/src/hooks/useSubscribeBroadcastChannel.ts new file mode 100644 index 00000000..fd48c071 --- /dev/null +++ b/widget/src/hooks/useSubscribeBroadcastChannel.ts @@ -0,0 +1,24 @@ +/* + * Copyright © 2025 Hexastack. All rights reserved. + * + * Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms: + * 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission. + * 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file). + */ + +import { useEffect } from "react"; + +import { + IBroadcastChannelContext, + useBroadcastChannel, +} from "../providers/BroadcastChannelProvider"; + +export const useSubscribeBroadcastChannel: IBroadcastChannelContext["subscribe"] = + (...props) => { + const { subscribe } = useBroadcastChannel(); + + useEffect(() => { + subscribe(...props); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [subscribe, ...props]); + }; diff --git a/widget/src/providers/BroadcastChannelProvider.tsx b/widget/src/providers/BroadcastChannelProvider.tsx index b900c1df..f542943c 100644 --- a/widget/src/providers/BroadcastChannelProvider.tsx +++ b/widget/src/providers/BroadcastChannelProvider.tsx @@ -49,11 +49,11 @@ const getOrCreateTabId = () => { return storedTabId; }; -interface IBroadcastChannelContext { +export interface IBroadcastChannelContext { subscribe: ( event: `${EBCEvent}`, callback: (message: BroadcastChannelData) => void, - ) => () => void; + ) => void; postMessage: (payload: BroadcastChannelPayload) => void; } diff --git a/widget/src/providers/ChatProvider.tsx b/widget/src/providers/ChatProvider.tsx index 9a8ba246..77f51bb0 100644 --- a/widget/src/providers/ChatProvider.tsx +++ b/widget/src/providers/ChatProvider.tsx @@ -16,6 +16,7 @@ import React, { useState, } from "react"; +import { useSubscribeBroadcastChannel } from "../hooks/useSubscribeBroadcastChannel"; import { StdEventType } from "../types/chat-io-messages.types"; import { Direction, @@ -29,7 +30,6 @@ import { } from "../types/message.types"; import { ConnectionState, OutgoingMessageState } from "../types/state.types"; -import { useBroadcastChannel } from "./BroadcastChannelProvider"; import { useConfig } from "./ConfigProvider"; import { useSettings } from "./SettingsProvider"; import { useSocket, useSubscribe } from "./SocketProvider"; @@ -385,7 +385,9 @@ const ChatProvider: React.FC<{ } }, [syncState, isOpen]); - const { subscribe } = useBroadcastChannel(); + useSubscribeBroadcastChannel("logout", () => { + socketCtx.socket.disconnect(); + }); useEffect(() => { if (screen === "chat" && connectionState === ConnectionState.connected) { @@ -406,10 +408,6 @@ const ChatProvider: React.FC<{ socketCtx.socket.io.on("reconnect", reSubscribe); - subscribe("logout", () => { - socketCtx.socket.disconnect(); - }); - return () => { socketCtx.socket.io.off("reconnect", reSubscribe); }; From 736ca9bc07eca00af6dedefea50a3dffe76c6601 Mon Sep 17 00:00:00 2001 From: yassinedorbozgithub Date: Thu, 30 Jan 2025 08:53:41 +0100 Subject: [PATCH 33/49] fix(frontend): add useSubscribeBroadcastChannel --- frontend/src/contexts/auth.context.tsx | 12 ++++------ .../contexts/broadcast-channel.context.tsx | 4 ++-- .../src/hooks/useSubscribeBroadcastChannel.ts | 23 +++++++++++++++++++ 3 files changed, 30 insertions(+), 9 deletions(-) create mode 100644 frontend/src/hooks/useSubscribeBroadcastChannel.ts diff --git a/frontend/src/contexts/auth.context.tsx b/frontend/src/contexts/auth.context.tsx index 030c4269..2d238f62 100644 --- a/frontend/src/contexts/auth.context.tsx +++ b/frontend/src/contexts/auth.context.tsx @@ -21,13 +21,12 @@ import { Progress } from "@/app-components/displays/Progress"; import { useLogout } from "@/hooks/entities/auth-hooks"; import { useApiClient } from "@/hooks/useApiClient"; import { CURRENT_USER_KEY, PUBLIC_PATHS } from "@/hooks/useAuth"; +import { useSubscribeBroadcastChannel } from "@/hooks/useSubscribeBroadcastChannel"; import { useTranslate } from "@/hooks/useTranslate"; import { RouterType } from "@/services/types"; import { IUser } from "@/types/user.types"; import { getFromQuery } from "@/utils/URL"; -import { useBroadcastChannel } from "./broadcast-channel.context"; - export interface AuthContextValue { user: IUser | undefined; isAuthenticated: boolean; @@ -101,17 +100,16 @@ export const AuthProvider = ({ children }: AuthProviderProps): JSX.Element => { setUser(user); }; const isAuthenticated = !!user; - const { subscribe } = useBroadcastChannel(); + + useSubscribeBroadcastChannel("logout", () => { + router.reload(); + }); useEffect(() => { const search = location.search; setSearch(search); setIsReady(true); - - subscribe("logout", () => { - router.reload(); - }); }, []); if (!isReady || isLoading) return ; diff --git a/frontend/src/contexts/broadcast-channel.context.tsx b/frontend/src/contexts/broadcast-channel.context.tsx index 5363ab18..97823e6b 100644 --- a/frontend/src/contexts/broadcast-channel.context.tsx +++ b/frontend/src/contexts/broadcast-channel.context.tsx @@ -49,11 +49,11 @@ const getOrCreateTabId = () => { return storedTabId; }; -interface IBroadcastChannelContext { +export interface IBroadcastChannelContext { subscribe: ( event: `${EBCEvent}`, callback: (message: BroadcastChannelData) => void, - ) => () => void; + ) => void; postMessage: (payload: BroadcastChannelPayload) => void; } diff --git a/frontend/src/hooks/useSubscribeBroadcastChannel.ts b/frontend/src/hooks/useSubscribeBroadcastChannel.ts new file mode 100644 index 00000000..d8c4eaa9 --- /dev/null +++ b/frontend/src/hooks/useSubscribeBroadcastChannel.ts @@ -0,0 +1,23 @@ +/* + * Copyright © 2025 Hexastack. All rights reserved. + * + * Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms: + * 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission. + * 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file). + */ + +import { useEffect } from "react"; + +import { + IBroadcastChannelContext, + useBroadcastChannel, +} from "@/contexts/broadcast-channel.context"; + +export const useSubscribeBroadcastChannel: IBroadcastChannelContext["subscribe"] = + (...props) => { + const { subscribe } = useBroadcastChannel(); + + useEffect(() => { + subscribe(...props); + }, [subscribe, ...props]); + }; From a87dd32568ad17be626519c3cd948234d7da3b28 Mon Sep 17 00:00:00 2001 From: yassinedorbozgithub Date: Thu, 30 Jan 2025 08:57:41 +0100 Subject: [PATCH 34/49] fix: remove unused pptional chaining --- frontend/src/contexts/broadcast-channel.context.tsx | 10 +++++----- widget/src/providers/BroadcastChannelProvider.tsx | 10 +++++----- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/frontend/src/contexts/broadcast-channel.context.tsx b/frontend/src/contexts/broadcast-channel.context.tsx index 97823e6b..3cdfdf8a 100644 --- a/frontend/src/contexts/broadcast-channel.context.tsx +++ b/frontend/src/contexts/broadcast-channel.context.tsx @@ -82,7 +82,7 @@ export const BroadcastChannelProvider: FC = ({ return; } - subscribersRef.current[payload.event]?.forEach((callback) => + subscribersRef.current[payload.event].forEach((callback) => callback(data), ); }; @@ -100,18 +100,18 @@ export const BroadcastChannelProvider: FC = ({ callback, ) => { subscribersRef.current[event] ??= []; - subscribersRef.current[event]?.push(callback); + subscribersRef.current[event].push(callback); return () => { - const index = subscribersRef.current[event]?.indexOf(callback) ?? -1; + const index = subscribersRef.current[event].indexOf(callback) ?? -1; if (index !== -1) { - subscribersRef.current[event]?.splice(index, 1); + subscribersRef.current[event].splice(index, 1); } }; }; const postMessage: IBroadcastChannelContext["postMessage"] = (payload) => { - channelRef.current?.postMessage({ + channelRef.current.postMessage({ tabId: tabUuid, payload, }); diff --git a/widget/src/providers/BroadcastChannelProvider.tsx b/widget/src/providers/BroadcastChannelProvider.tsx index f542943c..5206f643 100644 --- a/widget/src/providers/BroadcastChannelProvider.tsx +++ b/widget/src/providers/BroadcastChannelProvider.tsx @@ -82,7 +82,7 @@ export const BroadcastChannelProvider: FC = ({ return; } - subscribersRef.current[payload.event]?.forEach((callback) => + subscribersRef.current[payload.event].forEach((callback) => callback(data), ); }; @@ -102,18 +102,18 @@ export const BroadcastChannelProvider: FC = ({ callback, ) => { subscribersRef.current[event] ??= []; - subscribersRef.current[event]?.push(callback); + subscribersRef.current[event].push(callback); return () => { - const index = subscribersRef.current[event]?.indexOf(callback) ?? -1; + const index = subscribersRef.current[event].indexOf(callback) ?? -1; if (index !== -1) { - subscribersRef.current[event]?.splice(index, 1); + subscribersRef.current[event].splice(index, 1); } }; }; const postMessage: IBroadcastChannelContext["postMessage"] = (payload) => { - channelRef.current?.postMessage({ + channelRef.current.postMessage({ tabId: tabUuid, payload, }); From d44d7075ab6e890f28ffc0457ec51b2001219c30 Mon Sep 17 00:00:00 2001 From: yassinedorbozgithub Date: Thu, 30 Jan 2025 08:59:32 +0100 Subject: [PATCH 35/49] fix: remove nullish coalescing operator --- frontend/src/contexts/broadcast-channel.context.tsx | 2 +- widget/src/providers/BroadcastChannelProvider.tsx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/frontend/src/contexts/broadcast-channel.context.tsx b/frontend/src/contexts/broadcast-channel.context.tsx index 3cdfdf8a..885e6030 100644 --- a/frontend/src/contexts/broadcast-channel.context.tsx +++ b/frontend/src/contexts/broadcast-channel.context.tsx @@ -103,7 +103,7 @@ export const BroadcastChannelProvider: FC = ({ subscribersRef.current[event].push(callback); return () => { - const index = subscribersRef.current[event].indexOf(callback) ?? -1; + const index = subscribersRef.current[event].indexOf(callback); if (index !== -1) { subscribersRef.current[event].splice(index, 1); diff --git a/widget/src/providers/BroadcastChannelProvider.tsx b/widget/src/providers/BroadcastChannelProvider.tsx index 5206f643..12907889 100644 --- a/widget/src/providers/BroadcastChannelProvider.tsx +++ b/widget/src/providers/BroadcastChannelProvider.tsx @@ -105,7 +105,7 @@ export const BroadcastChannelProvider: FC = ({ subscribersRef.current[event].push(callback); return () => { - const index = subscribersRef.current[event].indexOf(callback) ?? -1; + const index = subscribersRef.current[event].indexOf(callback); if (index !== -1) { subscribersRef.current[event].splice(index, 1); From 763ed8251245803123cd3db789aa801412eafcba Mon Sep 17 00:00:00 2001 From: yassinedorbozgithub Date: Thu, 30 Jan 2025 09:06:44 +0100 Subject: [PATCH 36/49] fix: update createContext defaultVlaue --- frontend/src/contexts/broadcast-channel.context.tsx | 7 +++---- widget/src/providers/BroadcastChannelProvider.tsx | 7 +++---- 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/frontend/src/contexts/broadcast-channel.context.tsx b/frontend/src/contexts/broadcast-channel.context.tsx index 885e6030..5dd4cb22 100644 --- a/frontend/src/contexts/broadcast-channel.context.tsx +++ b/frontend/src/contexts/broadcast-channel.context.tsx @@ -57,10 +57,9 @@ export interface IBroadcastChannelContext { postMessage: (payload: BroadcastChannelPayload) => void; } -export const BroadcastChannelContext = createContext({ - subscribe: () => () => {}, - postMessage: () => {}, -}); +export const BroadcastChannelContext = createContext< + IBroadcastChannelContext | undefined +>(undefined); export const BroadcastChannelProvider: FC = ({ children, diff --git a/widget/src/providers/BroadcastChannelProvider.tsx b/widget/src/providers/BroadcastChannelProvider.tsx index 12907889..7114127d 100644 --- a/widget/src/providers/BroadcastChannelProvider.tsx +++ b/widget/src/providers/BroadcastChannelProvider.tsx @@ -57,10 +57,9 @@ export interface IBroadcastChannelContext { postMessage: (payload: BroadcastChannelPayload) => void; } -export const BroadcastChannelContext = createContext({ - subscribe: () => () => {}, - postMessage: () => {}, -}); +export const BroadcastChannelContext = createContext< + IBroadcastChannelContext | undefined +>(undefined); export const BroadcastChannelProvider: FC = ({ children, From 8ea4251bcf0ae5d55f5fde191dbe7783e804058a Mon Sep 17 00:00:00 2001 From: yassinedorbozgithub Date: Thu, 30 Jan 2025 10:47:37 +0100 Subject: [PATCH 37/49] fix: remove IBroadcastChannelContext export --- .../contexts/broadcast-channel.context.tsx | 2 +- .../src/hooks/useSubscribeBroadcastChannel.ts | 20 ++++++++--------- .../src/hooks/useSubscribeBroadcastChannel.ts | 22 +++++++++---------- .../providers/BroadcastChannelProvider.tsx | 2 +- 4 files changed, 21 insertions(+), 25 deletions(-) diff --git a/frontend/src/contexts/broadcast-channel.context.tsx b/frontend/src/contexts/broadcast-channel.context.tsx index 5dd4cb22..2879089a 100644 --- a/frontend/src/contexts/broadcast-channel.context.tsx +++ b/frontend/src/contexts/broadcast-channel.context.tsx @@ -49,7 +49,7 @@ const getOrCreateTabId = () => { return storedTabId; }; -export interface IBroadcastChannelContext { +interface IBroadcastChannelContext { subscribe: ( event: `${EBCEvent}`, callback: (message: BroadcastChannelData) => void, diff --git a/frontend/src/hooks/useSubscribeBroadcastChannel.ts b/frontend/src/hooks/useSubscribeBroadcastChannel.ts index d8c4eaa9..cb43d5a2 100644 --- a/frontend/src/hooks/useSubscribeBroadcastChannel.ts +++ b/frontend/src/hooks/useSubscribeBroadcastChannel.ts @@ -8,16 +8,14 @@ import { useEffect } from "react"; -import { - IBroadcastChannelContext, - useBroadcastChannel, -} from "@/contexts/broadcast-channel.context"; +import { useBroadcastChannel } from "@/contexts/broadcast-channel.context"; -export const useSubscribeBroadcastChannel: IBroadcastChannelContext["subscribe"] = - (...props) => { - const { subscribe } = useBroadcastChannel(); +export const useSubscribeBroadcastChannel: ReturnType< + typeof useBroadcastChannel +>["subscribe"] = (...props) => { + const { subscribe } = useBroadcastChannel(); - useEffect(() => { - subscribe(...props); - }, [subscribe, ...props]); - }; + useEffect(() => { + subscribe(...props); + }, [subscribe, ...props]); +}; diff --git a/widget/src/hooks/useSubscribeBroadcastChannel.ts b/widget/src/hooks/useSubscribeBroadcastChannel.ts index fd48c071..5193b09b 100644 --- a/widget/src/hooks/useSubscribeBroadcastChannel.ts +++ b/widget/src/hooks/useSubscribeBroadcastChannel.ts @@ -8,17 +8,15 @@ import { useEffect } from "react"; -import { - IBroadcastChannelContext, - useBroadcastChannel, -} from "../providers/BroadcastChannelProvider"; +import { useBroadcastChannel } from "../providers/BroadcastChannelProvider"; -export const useSubscribeBroadcastChannel: IBroadcastChannelContext["subscribe"] = - (...props) => { - const { subscribe } = useBroadcastChannel(); +export const useSubscribeBroadcastChannel: ReturnType< + typeof useBroadcastChannel +>["subscribe"] = (...props) => { + const { subscribe } = useBroadcastChannel(); - useEffect(() => { - subscribe(...props); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [subscribe, ...props]); - }; + useEffect(() => { + subscribe(...props); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [subscribe, ...props]); +}; diff --git a/widget/src/providers/BroadcastChannelProvider.tsx b/widget/src/providers/BroadcastChannelProvider.tsx index 7114127d..7e4a7257 100644 --- a/widget/src/providers/BroadcastChannelProvider.tsx +++ b/widget/src/providers/BroadcastChannelProvider.tsx @@ -49,7 +49,7 @@ const getOrCreateTabId = () => { return storedTabId; }; -export interface IBroadcastChannelContext { +interface IBroadcastChannelContext { subscribe: ( event: `${EBCEvent}`, callback: (message: BroadcastChannelData) => void, From aebeeb1f5903fa9dbd4943a36129d134a2f599b3 Mon Sep 17 00:00:00 2001 From: yassinedorbozgithub Date: Thu, 30 Jan 2025 11:07:14 +0100 Subject: [PATCH 38/49] fix: enhance typing --- .../contexts/broadcast-channel.context.tsx | 25 +++++++++++-------- .../providers/BroadcastChannelProvider.tsx | 25 +++++++++++-------- 2 files changed, 28 insertions(+), 22 deletions(-) diff --git a/frontend/src/contexts/broadcast-channel.context.tsx b/frontend/src/contexts/broadcast-channel.context.tsx index 2879089a..330db77f 100644 --- a/frontend/src/contexts/broadcast-channel.context.tsx +++ b/frontend/src/contexts/broadcast-channel.context.tsx @@ -26,16 +26,24 @@ type BroadcastChannelPayload = { data?: string | number | boolean | Record | undefined | null; }; -export type BroadcastChannelData = { +type BroadcastChannelData = { tabId: string; payload: BroadcastChannelPayload; }; -export interface IBroadcastChannelProps { +interface IBroadcastChannelProps { channelName: string; children: ReactNode; } +interface IBroadcastChannelContext { + subscribe: ( + event: `${EBCEvent}`, + callback: (message: BroadcastChannelData) => void, + ) => void; + postMessage: (payload: BroadcastChannelPayload) => void; +} + const getOrCreateTabId = () => { let storedTabId = sessionStorage.getItem("tab_uuid"); @@ -49,14 +57,6 @@ const getOrCreateTabId = () => { return storedTabId; }; -interface IBroadcastChannelContext { - subscribe: ( - event: `${EBCEvent}`, - callback: (message: BroadcastChannelData) => void, - ) => void; - postMessage: (payload: BroadcastChannelPayload) => void; -} - export const BroadcastChannelContext = createContext< IBroadcastChannelContext | undefined >(undefined); @@ -69,7 +69,10 @@ export const BroadcastChannelProvider: FC = ({ new BroadcastChannel(channelName), ); const subscribersRef = useRef< - Record void>> + Record< + string, + Array["1"]> + > >({}); const tabUuid = getOrCreateTabId(); diff --git a/widget/src/providers/BroadcastChannelProvider.tsx b/widget/src/providers/BroadcastChannelProvider.tsx index 7e4a7257..7f8cb529 100644 --- a/widget/src/providers/BroadcastChannelProvider.tsx +++ b/widget/src/providers/BroadcastChannelProvider.tsx @@ -26,16 +26,24 @@ type BroadcastChannelPayload = { data?: string | number | boolean | Record | undefined | null; }; -export type BroadcastChannelData = { +type BroadcastChannelData = { tabId: string; payload: BroadcastChannelPayload; }; -export interface IBroadcastChannelProps { +interface IBroadcastChannelProps { channelName: string; children: ReactNode; } +interface IBroadcastChannelContext { + subscribe: ( + event: `${EBCEvent}`, + callback: (message: BroadcastChannelData) => void, + ) => void; + postMessage: (payload: BroadcastChannelPayload) => void; +} + const getOrCreateTabId = () => { let storedTabId = sessionStorage.getItem("tab_uuid"); @@ -49,14 +57,6 @@ const getOrCreateTabId = () => { return storedTabId; }; -interface IBroadcastChannelContext { - subscribe: ( - event: `${EBCEvent}`, - callback: (message: BroadcastChannelData) => void, - ) => void; - postMessage: (payload: BroadcastChannelPayload) => void; -} - export const BroadcastChannelContext = createContext< IBroadcastChannelContext | undefined >(undefined); @@ -69,7 +69,10 @@ export const BroadcastChannelProvider: FC = ({ new BroadcastChannel(channelName), ); const subscribersRef = useRef< - Record void>> + Record< + string, + Array["1"]> + > >({}); const tabUuid = getOrCreateTabId(); From a1b9bfcba047c658ff063b002eca3ca54438ff44 Mon Sep 17 00:00:00 2001 From: yassinedorbozgithub Date: Thu, 30 Jan 2025 11:24:19 +0100 Subject: [PATCH 39/49] fix: add login event actions --- frontend/src/contexts/auth.context.tsx | 4 ++++ frontend/src/contexts/broadcast-channel.context.tsx | 1 + frontend/src/hooks/entities/auth-hooks.ts | 5 +++++ 3 files changed, 10 insertions(+) diff --git a/frontend/src/contexts/auth.context.tsx b/frontend/src/contexts/auth.context.tsx index 2d238f62..99978f15 100644 --- a/frontend/src/contexts/auth.context.tsx +++ b/frontend/src/contexts/auth.context.tsx @@ -101,6 +101,10 @@ export const AuthProvider = ({ children }: AuthProviderProps): JSX.Element => { }; const isAuthenticated = !!user; + useSubscribeBroadcastChannel("login", () => { + router.reload(); + }); + useSubscribeBroadcastChannel("logout", () => { router.reload(); }); diff --git a/frontend/src/contexts/broadcast-channel.context.tsx b/frontend/src/contexts/broadcast-channel.context.tsx index 330db77f..a0046bf8 100644 --- a/frontend/src/contexts/broadcast-channel.context.tsx +++ b/frontend/src/contexts/broadcast-channel.context.tsx @@ -18,6 +18,7 @@ import { import { generateId } from "@/utils/generateId"; export enum EBCEvent { + LOGIN = "login", LOGOUT = "logout", } diff --git a/frontend/src/hooks/entities/auth-hooks.ts b/frontend/src/hooks/entities/auth-hooks.ts index e6df15b3..2e829206 100755 --- a/frontend/src/hooks/entities/auth-hooks.ts +++ b/frontend/src/hooks/entities/auth-hooks.ts @@ -33,12 +33,17 @@ export const useLogin = ( >, ) => { const { apiClient } = useApiClient(); + const { postMessage } = useBroadcastChannel(); return useMutation({ ...options, async mutationFn(credentials) { return await apiClient.login(credentials); }, + onSuccess: (data, variables, context) => { + options?.onSuccess?.(data, variables, context); + postMessage({ event: "login" }); + }, }); }; From c5f61d1d3ad3ba2d5f635cf3c41dddc72b9a0e1d Mon Sep 17 00:00:00 2001 From: Med Marrouchi Date: Thu, 30 Jan 2025 11:50:29 +0100 Subject: [PATCH 40/49] Update widget/src/providers/BroadcastChannelProvider.tsx --- widget/src/providers/BroadcastChannelProvider.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/widget/src/providers/BroadcastChannelProvider.tsx b/widget/src/providers/BroadcastChannelProvider.tsx index 7f8cb529..73933e54 100644 --- a/widget/src/providers/BroadcastChannelProvider.tsx +++ b/widget/src/providers/BroadcastChannelProvider.tsx @@ -136,7 +136,7 @@ export const BroadcastChannelProvider: FC = ({ export const useBroadcastChannel = () => { const context = useContext(BroadcastChannelContext); - if (context === undefined) { + if (!context) { throw new Error( "useBroadcastChannel must be used within a BroadcastChannelProvider", ); From 294c075867dfaf90af846cc3296fed2aca90dcbf Mon Sep 17 00:00:00 2001 From: abdou6666 Date: Thu, 30 Jan 2025 12:45:54 +0100 Subject: [PATCH 41/49] fix: updated attachments mime types --- frontend/src/utils/attachment.ts | 38 +++++++++++++++++++++++++------- 1 file changed, 30 insertions(+), 8 deletions(-) diff --git a/frontend/src/utils/attachment.ts b/frontend/src/utils/attachment.ts index 93254491..b68cfd59 100644 --- a/frontend/src/utils/attachment.ts +++ b/frontend/src/utils/attachment.ts @@ -6,24 +6,46 @@ * 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file). */ - import { IAttachment } from "@/types/attachment.types"; import { FileType, TAttachmentForeignKey } from "@/types/message.types"; import { buildURL } from "./URL"; export const MIME_TYPES = { - images: ["image/jpeg", "image/png", "image/gif", "image/webp"], - videos: ["video/mp4", "video/webm", "video/ogg"], - audios: ["audio/mpeg", "audio/ogg", "audio/wav"], + images: ["image/jpeg", "image/png", "image/webp", "image/bmp"], + videos: [ + "video/mp4", + "video/webm", + "video/ogg", + "video/quicktime", // common in apple devices + "video/x-msvideo", // AVI + "video/x-matroska", // MKV + ], + audios: [ + "audio/mpeg", // MP3 + "audio/mp3", // Explicit MP3 type + "audio/ogg", + "audio/wav", + "audio/aac", // common in apple devices + "audio/x-wav", + ], documents: [ "application/pdf", - "application/msword", + "application/msword", // older ms Word format + "application/vnd.openxmlformats-officedocument.wordprocessingml.document", // newer ms word format "application/vnd.openxmlformats-officedocument.wordprocessingml.document", - "application/vnd.ms-excel", - "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + "application/vnd.ms-excel", // older excel format + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", // newer excel format "application/vnd.ms-powerpoint", "application/vnd.openxmlformats-officedocument.presentationml.presentation", + "text/plain", + "application/rtf", + "application/epub", // do we want to support epub? + "application/x-7z-compressed", // do we want to support 7z? + "application/zip", // do we want to support zip? + "application/x-rar-compressed", // do we want to support winrar? + "application/json", + "text/csv", ], }; @@ -68,4 +90,4 @@ export function extractFilenameFromUrl(url: string) { // If the URL is invalid, return the input as-is return url; } -} \ No newline at end of file +} From 0f5a67c2cecd26387607d2111181878582fa5655 Mon Sep 17 00:00:00 2001 From: abdou6666 Date: Thu, 30 Jan 2025 12:50:15 +0100 Subject: [PATCH 42/49] fix: avatar/nlu import to use accepted mime type props --- frontend/src/app-components/inputs/FileInput.tsx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/frontend/src/app-components/inputs/FileInput.tsx b/frontend/src/app-components/inputs/FileInput.tsx index f6d52d58..c6da510b 100644 --- a/frontend/src/app-components/inputs/FileInput.tsx +++ b/frontend/src/app-components/inputs/FileInput.tsx @@ -1,11 +1,12 @@ /* - * Copyright © 2024 Hexastack. All rights reserved. + * Copyright © 2025 Hexastack. All rights reserved. * * Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms: * 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission. * 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file). */ + import UploadIcon from "@mui/icons-material/Upload"; import { Button, CircularProgress } from "@mui/material"; import { ChangeEvent, forwardRef } from "react"; @@ -71,6 +72,7 @@ const FileUploadButton = forwardRef( value="" // to trigger an automatic reset to allow the same file to be selected multiple times sx={{ display: "none" }} onChange={handleImportChange} + inputProps={{ accept }} /> ); From b534e47edd1653e08734b05005be9b9fa24ff7f3 Mon Sep 17 00:00:00 2001 From: abdou6666 Date: Thu, 30 Jan 2025 12:51:42 +0100 Subject: [PATCH 43/49] fix: widget FileButton to use mime types --- widget/src/components/buttons/FileButton.tsx | 11 +++++- widget/src/utils/attachment.ts | 41 +++++++++++++++++++- 2 files changed, 49 insertions(+), 3 deletions(-) diff --git a/widget/src/components/buttons/FileButton.tsx b/widget/src/components/buttons/FileButton.tsx index 22aa0117..f04e79ad 100644 --- a/widget/src/components/buttons/FileButton.tsx +++ b/widget/src/components/buttons/FileButton.tsx @@ -1,14 +1,16 @@ /* - * Copyright © 2024 Hexastack. All rights reserved. + * Copyright © 2025 Hexastack. All rights reserved. * * Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms: * 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission. * 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file). */ -import React, { ChangeEvent } from "react"; + +import React, { ChangeEvent, useMemo } from "react"; import { useChat } from "../../providers/ChatProvider"; +import { MIME_TYPES } from "../../utils/attachment"; import FileInputIcon from "../icons/FileInputIcon"; import "./FileButton.scss"; @@ -23,12 +25,17 @@ const FileButton: React.FC = () => { setFile && setFile(e.target.files[0]); } }; + const acceptedMimeTypes = useMemo( + () => Object.values(MIME_TYPES).flat().join(""), + [], + ); return (