SmythOS Studio: Open-Source Visual AI Agent Builder and deployable runtime stack from SmythOS. Start with an intuitive drag-and-drop workspace, extend with custom code, and deploy your agents anywhere — local, cloud, or edge — with full governance and control.
JavaScript a2aagentic-aiai-agentsdevtoolsmcp-clientn8n-alternativeno-codeopen-sourceorchestrationsmythosvisual-builder
refactor: streamline authentication handling in chat components
Muhammad Hamza Khanf8b6d5cc60c4
diff --git a/packages/app/src/backend/routes/api/page/chat.ts b/packages/app/src/backend/routes/api/page/chat.tsindex 27d748cc..72277586 100644--- a/packages/app/src/backend/routes/api/page/chat.ts+++ b/packages/app/src/backend/routes/api/page/chat.ts@@ -66,11 +66,7 @@ router.post('/stream', async (req, res) => {const agentId = req.headers['x-agent-id'] as string;const conversationId = req.headers['x-conversation-id'];const modelId = req.headers['x-model-id']; // Extract model ID for backend override-- // Get auth token: priority header > session- // const headerAuthToken = req.headers['x-auth-token'] as string | undefined;- // const sessionAuthToken = req.session?.agentTokens?.[agentId];- // const authToken = headerAuthToken || sessionAuthToken;+ const authToken = req.headers['x-agent-chat-token'] as string | undefined;try {const result = await axios.post(@@ -85,7 +81,7 @@ router.post('/stream', async (req, res) => {'x-conversation-id': conversationId,'x-smyth-team-id': teamId,...(modelId ? { 'x-model-id': modelId } : {}), // Forward model ID if provided- // ...(authToken ? { 'X-Auth-Token': authToken } : {}), // Forward auth token if provided+ ...(authToken ? { 'x-agent-chat-token': authToken } : {}), // Forward auth token if provided},responseType: 'stream',},@@ -146,12 +142,6 @@ router.get('/params', async (req, res) => {const responseData = result.data;- // Check if session already has a valid token for this agent (persist auth across page reloads)- // const sessionToken = req.session?.agentTokens?.[agentId];- // if (sessionToken && responseData.authRequired) {- // responseData.authRequired = false;- // }-return res.status(200).json(responseData);} catch (error) {return res@@ -160,59 +150,6 @@ router.get('/params', async (req, res) => {}});-router.post('/verify-token', async (req, res) => {- const agentId = req.headers['x-agent-id'];- const { token: bearerToken } = req.body;- const userId = req._user?.id;- const teamId = req._team?.id;- const accessToken = req.user.accessToken;-- if (!agentId) {- return res.status(400).json({ success: false, message: 'Agent ID required' });- }-- if (!bearerToken) {- return res.status(400).json({ success: false, message: 'Token required' });- }-- try {- const result = await axios.post(- getAgentServerURL(agentId as string, isUsingLocalServer) + '/emb/auth/verify',- { token: bearerToken },- {- headers: {- ...includeAxiosAuth(accessToken).headers,- 'x-user-id': userId,- 'x-team-id': teamId,- 'X-AGENT-ID': agentId,- },- withCredentials: true,- },- );-- // Forward any cookies from SRE response- // const setCookie = result.headers['set-cookie'];- // if (setCookie) {- // res.setHeader('set-cookie', setCookie);- // }-- // Store token in session for subsequent requests (Option B: server-side storage)- // if (result.data.success) {- // if (!req.session.agentTokens) {- // req.session.agentTokens = {};- // }- // req.session.agentTokens[agentId as string] = bearerToken;- // }-- return res.json(result.data);- } catch (error) {- return res.status(401).json({- success: false,- message: error.response?.data?.message || 'Token verification failed',- });- }-});-router.post('/new', async (req, res) => {try {const agentId = req.body.conversation?.aiAgentId;diff --git a/packages/app/src/react/features/ai-chat/clients/chat-api.client.ts b/packages/app/src/react/features/ai-chat/clients/chat-api.client.tsindex bea9f4da..76424329 100644--- a/packages/app/src/react/features/ai-chat/clients/chat-api.client.ts+++ b/packages/app/src/react/features/ai-chat/clients/chat-api.client.ts@@ -98,9 +98,6 @@ export class ChatAPIClient {// Notify stream startif (onStart) onStart();- // Get auth token from localStorage- // const authToken = localStorage.getItem('authToken');-// Prepare request headers with optional model overrideconst requestHeaders: Record<string, string> = {...this.config.defaultHeaders,@@ -110,10 +107,6 @@ export class ChatAPIClient {...headers,};- // Add auth token to headers if it exists- // if (authToken) {- // requestHeaders['X-Auth-Token'] = authToken;- // }const requestBody = { message, attachments, enableMetaMessages: true };diff --git a/packages/app/src/react/features/ai-chat/components/auth/api-key-overlay.tsx b/packages/app/src/react/features/ai-chat/components/auth/api-key-overlay.tsxdeleted file mode 100644index 2a736587..00000000--- a/packages/app/src/react/features/ai-chat/components/auth/api-key-overlay.tsx+++ /dev/null@@ -1,111 +0,0 @@-import { useChatStores } from '@react/features/ai-chat/hooks';-import { Button } from '@react/shared/components/ui/button';-import { Input } from '@react/shared/components/ui/input';-import { Spinner } from '@react/shared/components/ui/spinner';-import { ChangeEvent, KeyboardEvent, useCallback, useState } from 'react';--/**- * API Key authentication overlay component- * Allows users to enter their bearer token for authentication- */-export const ApiKeyOverlay = () => {- const [token, setToken] = useState('');- const [isLoading, setIsLoading] = useState(false);- const [error, setError] = useState('');-- const { auth, agent } = useChatStores();- const { onAuthSuccess } = auth;- const agentId = agent?.data?.data?.id;-- const handleValidateToken = useCallback(async () => {- const trimmedToken = token.trim();-- if (!trimmedToken) {- setError('Please enter your authentication token');- return;- }-- if (!agentId) {- setError('Agent not found');- return;- }-- try {- setIsLoading(true);- setError('');-- const response = await fetch('/api/page/chat/verify-token', {- method: 'POST',- headers: {- 'Content-Type': 'application/json',- 'X-AGENT-ID': agentId,- },- body: JSON.stringify({ token: trimmedToken }),- credentials: 'include',- });-- const data = await response.json();-- if (data.success) {- // Store auth token in localStorage for subsequent requests- // localStorage.setItem('authToken', trimmedToken);- await onAuthSuccess();- } else {- setError(data.message || 'Invalid token. Please check and try again.');- }- } catch {- setError('Failed to verify token. Please try again.');- } finally {- setIsLoading(false);- }- }, [token, agentId, onAuthSuccess]);-- const handleKeyDown = useCallback(- (e: KeyboardEvent<HTMLInputElement>) => {- if (e.key === 'Enter' && !isLoading) {- handleValidateToken();- }- },- [handleValidateToken, isLoading],- );-- const handleInputChange = useCallback(- (e: ChangeEvent<HTMLInputElement>) => {- setToken(e.target.value);- if (error) setError('');- },- [error],- );-- return (- <div className="space-y-4">- <Input- type="password"- value={token}- onChange={handleInputChange}- onKeyDown={handleKeyDown}- placeholder="Enter your API key or token"- error={!!error}- errorMessage={error}- disabled={isLoading}- fullWidth- />-- <Button- onClick={handleValidateToken}- disabled={isLoading || !token.trim()}- variant="blue-primary"- size="lg"- className="w-full"- >- {isLoading ? (- <span className="flex items-center gap-2">- <Spinner size="sm" /> Verifying...- </span>- ) : (- 'Continue'- )}- </Button>- </div>- );-};diff --git a/packages/app/src/react/features/ai-chat/components/auth/auth-overlay.tsx b/packages/app/src/react/features/ai-chat/components/auth/auth-overlay.tsxdeleted file mode 100644index 461d3b10..00000000--- a/packages/app/src/react/features/ai-chat/components/auth/auth-overlay.tsx+++ /dev/null@@ -1,42 +0,0 @@-import { useChatStores } from '@react/features/ai-chat/hooks';-import { AUTH_METHODS } from '@react/features/ai-chat/constants';-import { OAuthOverlay } from './oauth-overlay';-import { ApiKeyOverlay } from './api-key-overlay';--/**- * Main authentication overlay component- * Displays the appropriate auth UI based on the configured auth method- */-export const AuthOverlay = () => {- const { auth, agent } = useChatStores();- const { method } = auth;- const agentName = agent?.data?.name;-- return (- <div className="w-full h-full flex items-center justify-center bg-gray-50">- <div className="bg-white text-center max-w-md w-full p-10 rounded-xl shadow-lg">- {/* Agent Avatar */}- <div className="mb-6">- <div className="w-16 h-16 mx-auto bg-blue-100 rounded-full flex items-center justify-center">- <span className="text-2xl font-bold text-blue-600">- {agentName?.[0]?.toUpperCase() || 'A'}- </span>- </div>- </div>-- {/* Agent Name */}- <h2 className="text-2xl font-semibold text-gray-900 mb-2">{agentName || 'AI Agent'}</h2>-- {/* Powered by */}- <p className="text-gray-400 text-sm mb-4">Powered by SmythOS</p>-- {/* Description */}- <p className="text-gray-600 mb-8">This agent requires authentication to continue.</p>-- {/* Auth Method Specific UI */}- {method === AUTH_METHODS.OAUTH && <OAuthOverlay />}- {method === AUTH_METHODS.API_KEY && <ApiKeyOverlay />}- </div>- </div>- );-};diff --git a/packages/app/src/react/features/ai-chat/components/auth/index.ts b/packages/app/src/react/features/ai-chat/components/auth/index.tsdeleted file mode 100644index 184c4795..00000000--- a/packages/app/src/react/features/ai-chat/components/auth/index.ts+++ /dev/null@@ -1,3 +0,0 @@-export * from './api-key-overlay';-export * from './auth-overlay';-export * from './oauth-overlay';diff --git a/packages/app/src/react/features/ai-chat/components/auth/oauth-overlay.tsx b/packages/app/src/react/features/ai-chat/components/auth/oauth-overlay.tsxdeleted file mode 100644index 257f1bbb..00000000--- a/packages/app/src/react/features/ai-chat/components/auth/oauth-overlay.tsx+++ /dev/null@@ -1,101 +0,0 @@-import { useChatStores } from '@react/features/ai-chat/hooks';-import { Button } from '@react/shared/components/ui/button';-import { Spinner } from '@react/shared/components/ui/spinner';-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';--/**- * OAuth sign-in overlay component- * Opens authorization URL in popup and listens for success message- */-export const OAuthOverlay = () => {- const { auth } = useChatStores();- const { onAuthSuccess, redirectInternalEndpoint, domain } = auth;-- const oAuthUrl = useMemo(() => {- return `https://${domain}${redirectInternalEndpoint}`;- }, [domain, redirectInternalEndpoint]);-- const [isLoading, setIsLoading] = useState(false);- const [popupBlocked, setPopupBlocked] = useState(false);- const popupRef = useRef<Window | null>(null);-- // Listen for OAuth success message from popup- useEffect(() => {- const handleMessage = (event: MessageEvent) => {- if (event?.data?.type === 'oauth-success') {- setIsLoading(true);- onAuthSuccess().finally(() => setIsLoading(false));- } else if (event?.data?.type === 'oauth-error') {- setIsLoading(false);- }- };-- window.addEventListener('message', handleMessage);- return () => window.removeEventListener('message', handleMessage);- }, [onAuthSuccess]);-- // Check if popup was closed without completing auth- useEffect(() => {- if (!popupRef.current) return;-- const checkClosed = setInterval(() => {- if (popupRef.current?.closed) {- setIsLoading(false);- clearInterval(checkClosed);- }- }, 1000);-- return () => clearInterval(checkClosed);- }, [isLoading]);-- const handleSignIn = useCallback(() => {- if (!oAuthUrl) return;-- setPopupBlocked(false);- const popup = window.open(oAuthUrl, '_blank', 'width=500,height=600');-- if (!popup || popup.closed) {- setPopupBlocked(true);- return;- }-- popupRef.current = popup;- setIsLoading(true);- }, [oAuthUrl]);-- return (- <div className="space-y-4">- <Button- onClick={handleSignIn}- disabled={isLoading}- variant="blue-primary"- size="lg"- className="w-full"- >- {isLoading ? (- <span className="flex items-center gap-2">- <Spinner size="sm" /> Signing in...- </span>- ) : (- 'Sign In with SSO'- )}- </Button>-- {popupBlocked && (- <div className="p-4 bg-yellow-50 border border-yellow-200 rounded-lg">- <p className="text-sm text-yellow-800">- Popup was blocked. Please allow popups for this site or{' '}- <a- href={oAuthUrl}- target="_blank"- rel="noopener noreferrer"- className="underline font-medium"- >- click here to sign in- </a>- </p>- </div>- )}- </div>- );-};diff --git a/packages/app/src/react/features/ai-chat/components/chat-content.tsx b/packages/app/src/react/features/ai-chat/components/chat-content.tsxindex 10349fbf..95173bd3 100644--- a/packages/app/src/react/features/ai-chat/components/chat-content.tsx+++ b/packages/app/src/react/features/ai-chat/components/chat-content.tsx@@ -1,10 +1,9 @@import {ArrowLeftIcon,- AuthOverlay,Chats,Footer,Header,- LoadingSkeleton,+ LoadingSkeleton} from '@react/features/ai-chat/components';import { DEFAULT_AVATAR_URL } from '@react/features/ai-chat/constants';import { useChatStores } from '@react/features/ai-chat/hooks';@@ -21,9 +20,6 @@ export const ChatContent = () => {// Loading stateif (pageState === 'loading') return <LoadingSkeleton />;- // Auth required- if (pageState === 'auth-required') return <AuthOverlay />;-// Chatbot disabledif (pageState === 'disabled') {const agentName = agent?.data?.name || 'Agent';diff --git a/packages/app/src/react/features/ai-chat/contexts/chat.provider.tsx b/packages/app/src/react/features/ai-chat/contexts/chat.provider.tsxindex 0a6387ef..3f78f518 100644--- a/packages/app/src/react/features/ai-chat/contexts/chat.provider.tsx+++ b/packages/app/src/react/features/ai-chat/contexts/chat.provider.tsx@@ -22,6 +22,7 @@ export const ChatContextProvider: FC<TChildren> = ({ children }) => {const inputRef = useRef<HTMLTextAreaElement>(null);const containerRef = useRef<HTMLDivElement>(null);const hasInitializedChatRef = useRef(false);+ const authTokenRef = useRef<string | null>(null);const [modelOverride, setModelOverride] = useState<string | null>(null);const [isAuthOverridden, setIsAuthOverridden] = useState(false);@@ -60,6 +61,7 @@ export const ChatContextProvider: FC<TChildren> = ({ children }) => {modelId: modelOverride || agentSettings?.chatGptModel,enableMetaMessages: true,inputRef,+ authTokenRef,});const createSession = useCallback(async () => {@@ -83,6 +85,21 @@ export const ChatContextProvider: FC<TChildren> = ({ children }) => {}}, [agentId, createChat, updateAgentSettings]);+ const generateAuthToken = useCallback(async () => {+ try {+ if (!agentId) return null;+ const response = await fetch(`/oauth/token/${agentId}`);+ const data = await response.json();+ if (data?.success && data?.token) {+ authTokenRef.current = data.token;+ }+ return null;+ } catch (error) {+ console.error('Error generating auth token', error); // eslint-disable-line no-console+ return null;+ }+ }, [agentId]);+const sendMessage = useCallback(async (message: string) => {if (!message.trim() && fileUpload.attachments.length === 0) return;@@ -164,11 +181,14 @@ export const ChatContextProvider: FC<TChildren> = ({ children }) => {// Initialize chat session when page is readyuseEffect(() => {- if (pageState === 'ready' && !hasInitializedChatRef.current) {+ if (!hasInitializedChatRef.current && pageState === 'ready') {hasInitializedChatRef.current = true;createSession().then(() => inputRef.current?.focus());}- }, [pageState, createSession]);+ if (!authTokenRef.current && pageState === 'auth-required') {+ generateAuthToken();+ }+ }, [pageState, createSession, generateAuthToken]);// Auto-focus inputuseEffect(() => {diff --git a/packages/app/src/react/features/ai-chat/hooks/use-chat-state.ts b/packages/app/src/react/features/ai-chat/hooks/use-chat-state.tsindex a9a94644..3779b7b2 100644--- a/packages/app/src/react/features/ai-chat/hooks/use-chat-state.ts+++ b/packages/app/src/react/features/ai-chat/hooks/use-chat-state.ts@@ -12,7 +12,7 @@ import { forceScrollToBottomImmediate } from '@react/features/ai-chat/utils';import { useCallback, useMemo, useRef, useState } from 'react';export const useChatState = (options: TChatStateConfig): IChatState => {- const { agentId, chatId, modelId, enableMetaMessages = false, inputRef } = options;+ const { agentId, chatId, modelId, enableMetaMessages = false, inputRef, authTokenRef } = options;const [messages, setMessages] = useState<TChatMessage[]>([]);const [isStreaming, setIsStreaming] = useState<boolean>(false);@@ -209,23 +209,23 @@ export const useChatState = (options: TChatStateConfig): IChatState => {const userMessage: TChatMessage | null = shouldSetUserMessage? {- id: msgCount + 1,- type: MESSAGE_TYPES.USER,- content: message?.trim() || '',- attachments:- currentAttachments.length > 0- ? currentAttachments.map((a) => ({- id: a.id,- name: a.name,- type: a.type,- size: a.size,- url: a.url,- blobUrl: a.blobUrl,- file: a.file,- }))- : undefined,- updatedAt: now,- }+ id: msgCount + 1,+ type: MESSAGE_TYPES.USER,+ content: message?.trim() || '',+ attachments:+ currentAttachments.length > 0+ ? currentAttachments.map((a) => ({+ id: a.id,+ name: a.name,+ type: a.type,+ size: a.size,+ url: a.url,+ blobUrl: a.blobUrl,+ file: a.file,+ }))+ : undefined,+ updatedAt: now,+ }: null;const loadingMessage: TChatMessage = {@@ -247,21 +247,24 @@ export const useChatState = (options: TChatStateConfig): IChatState => {attachments:currentAttachments.length > 0? currentAttachments- .filter((a) => a.file)- .map((a) => ({- id: `${Date.now()}_${Math.random()}`,- file: a.file as File,- name: a.name,- type: a.type,- size: a.size,- url: a.url || '',- metadata: {},- }))+ .filter((a) => a.file)+ .map((a) => ({+ id: `${Date.now()}_${Math.random()}`,+ file: a.file as File,+ name: a.name,+ type: a.type,+ size: a.size,+ url: a.url || '',+ metadata: {},+ })): undefined,agentId,chatId,modelId,signal: abortRef.current.signal,+ headers: {+ 'x-agent-chat-token': authTokenRef.current || '',+ },},{onContent: onStreamContent,@@ -299,6 +302,7 @@ export const useChatState = (options: TChatStateConfig): IChatState => {onMetaMessage,onStreamError,inputRef,+ authTokenRef,],);diff --git a/packages/app/src/react/features/ai-chat/types/hooks.ts b/packages/app/src/react/features/ai-chat/types/hooks.tsindex af2d25d5..3728d8c7 100644--- a/packages/app/src/react/features/ai-chat/types/hooks.ts+++ b/packages/app/src/react/features/ai-chat/types/hooks.ts@@ -30,6 +30,7 @@ export type TChatStateConfig = {modelId?: string;enableMetaMessages?: boolean;inputRef?: RefObject<TFocusable | null>;+ authTokenRef?: RefObject<string | null>;};export interface IChatState {