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
feat: enhance chat API with authentication and parameter fetching
Salman-Ahamed01a7765b2a74
diff --git a/packages/app/src/backend/routes/api/page/chat.ts b/packages/app/src/backend/routes/api/page/chat.tsindex ceee1129..1468ba1a 100644--- a/packages/app/src/backend/routes/api/page/chat.ts+++ b/packages/app/src/backend/routes/api/page/chat.ts@@ -63,13 +63,18 @@ router.post('/stream', async (req, res) => {const userId = req._user?.id;const teamId = req._team?.id;const token = req.user.accessToken;- const agentId = req.headers['x-agent-id'];+ 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;+try {const result = await axios.post(- getAgentServerURL(agentId as string, isUsingLocalServer) + '/v1/emb/chat/stream',+ getAgentServerURL(agentId, isUsingLocalServer) + '/v1/emb/chat/stream',{ ...req.body },{headers: {@@ -80,6 +85,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},responseType: 'stream',},@@ -99,8 +105,8 @@ router.post('/stream', async (req, res) => {});} catch (error) {return res- .status(500)- .json({ error: error.message || 'Something went wrong while fetching chatbot stream' });+ .status(error.response?.status || 500)+ .json({ error: error.response?.data?.message || error.message || 'Something went wrong while fetching chatbot stream' });}});@@ -119,6 +125,94 @@ router.get('/list', async (req, res) => {}});+router.get('/params', async (req, res) => {+ const userId = req._user?.id;+ const teamId = req._team?.id;+ const token = req.user.accessToken;+ const agentId = req.headers['x-agent-id'] as string;++ try {+ const result = await axios.get(+ getAgentServerURL(agentId, isUsingLocalServer) + '/v1/emb/chat/params',+ {+ headers: {+ ...includeAxiosAuth(token).headers,+ 'x-user-id': userId,+ 'x-team-id': teamId,+ 'x-agent-id': agentId,+ },+ },+ );++ 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+ .status(500)+ .json({ error: error.message || 'Something went wrong while fetching chat params' });+ }+});++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 103a2ab1..ddc486e1 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@@ -7,6 +7,7 @@ import {IStreamCallbacks,TAPIConfig,TChatError,+ TChatParams,TStreamChunk,TStreamConfig,} from '@react/features/ai-chat/types';@@ -97,8 +98,11 @@ export class ChatAPIClient {// Notify stream startif (onStart) onStart();+ // Get auth token from localStorage+ const authToken = localStorage.getItem('authToken');+// Prepare request headers with optional model override- const requestHeaders = {+ const requestHeaders: Record<string, string> = {...this.config.defaultHeaders,'X-AGENT-ID': agentId,'x-conversation-id': chatId,@@ -106,6 +110,11 @@ 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 };// Make streaming request@@ -114,6 +123,7 @@ export class ChatAPIClient {headers: requestHeaders,body: JSON.stringify(requestBody),signal,+ credentials: 'include', // Required for session cookie});// Handle HTTP errors@@ -354,6 +364,7 @@ export class ChatAPIClient {method: 'POST',headers: this.config.defaultHeaders,body: JSON.stringify(data),+ credentials: 'include', // Required for session cookie});if (!response.ok) {@@ -363,4 +374,35 @@ export class ChatAPIClient {return response.json() as Promise<CreateChatsResponse>;}++ /**+ * Fetches chat configuration parameters for an agent+ *+ * @param agentId - The agent ID to fetch params for+ * @returns Promise resolving to chat params+ * @throws {Error} If the request fails+ *+ * @example+ * ```typescript+ * const params = await client.getChatParams('agent-123');+ * console.log(params.chatbotEnabled);+ * ```+ */+ async getChatParams(agentId: string): Promise<TChatParams> {+ const response = await fetch(`${this.config.baseUrl}/params`, {+ method: 'GET',+ headers: {+ ...this.config.defaultHeaders,+ 'X-AGENT-ID': agentId,+ },+ credentials: 'include', // Required for session cookie+ });++ if (!response.ok) {+ const errorData = await this.parseErrorResponse(response);+ throw new Error(errorData.message || `Failed to fetch chat params: ${response.statusText}`);+ }++ return response.json() as Promise<TChatParams>;+ }}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.tsxnew file mode 100644index 00000000..ed21dbf3--- /dev/null+++ b/packages/app/src/react/features/ai-chat/components/auth/api-key-overlay.tsx@@ -0,0 +1,111 @@+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.tsxnew file mode 100644index 00000000..461d3b10--- /dev/null+++ b/packages/app/src/react/features/ai-chat/components/auth/auth-overlay.tsx@@ -0,0 +1,42 @@+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.tsnew file mode 100644index 00000000..3dcc3212--- /dev/null+++ b/packages/app/src/react/features/ai-chat/components/auth/index.ts@@ -0,0 +1,3 @@+export * from './auth-overlay';+export * from './oauth-overlay';+export * from './api-key-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.tsxnew file mode 100644index 00000000..05f4f081--- /dev/null+++ b/packages/app/src/react/features/ai-chat/components/auth/oauth-overlay.tsx@@ -0,0 +1,97 @@+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, 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 { authorizationUrl, onAuthSuccess } = auth;++ 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 (!authorizationUrl) return;++ setPopupBlocked(false);+ const popup = window.open(authorizationUrl, '_blank', 'width=500,height=600');++ if (!popup || popup.closed) {+ setPopupBlocked(true);+ return;+ }++ popupRef.current = popup;+ setIsLoading(true);+ }, [authorizationUrl]);++ 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={authorizationUrl}+ 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/index.ts b/packages/app/src/react/features/ai-chat/components/index.tsindex bbddda1f..8deab5ba 100644--- a/packages/app/src/react/features/ai-chat/components/index.ts+++ b/packages/app/src/react/features/ai-chat/components/index.ts@@ -1,3 +1,4 @@+export * from './auth';export * from './chat';export * from './common';export * from './container';diff --git a/packages/app/src/react/features/ai-chat/constants/index.ts b/packages/app/src/react/features/ai-chat/constants/index.tsindex 7848f49a..c01824c9 100644--- a/packages/app/src/react/features/ai-chat/constants/index.ts+++ b/packages/app/src/react/features/ai-chat/constants/index.ts@@ -5,6 +5,11 @@ export const CHAT_ACCEPTED_FILE_TYPES = {input: '*/*',} as const;+export const AUTH_METHODS = {+ OAUTH: 'oauth-oidc',+ API_KEY: 'api-key-bearer',+} as const;+/** Maximum allowed file size in bytes (5MB) */export const ALLOWED_FILE_SIZE = 5 * 1024 * 1024;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 0e94eca1..823cc0d1 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@@ -1,6 +1,7 @@-import { ChatContext, IChatContext } from '@react/features/ai-chat/contexts/chat';+import { ChatContext, IChatContext, TPageState } from '@react/features/ai-chat/contexts/chat';import {useAgentSettings,+ useChatParams,useChatState,useCreateChat,useFileUpload,@@ -23,6 +24,7 @@ export const ChatContextProvider: FC<TChildren> = ({ children }) => {const hasInitializedChatRef = useRef(false);const [modelOverride, setModelOverride] = useState<string | null>(null);+ const [isAuthOverridden, setIsAuthOverridden] = useState(false);const { data: agent, isLoading: isAgentLoading } = useAgent(agentId, {refetchOnWindowFocus: false,@@ -34,6 +36,8 @@ export const ChatContextProvider: FC<TChildren> = ({ children }) => {const { data: settingsData, isLoading: isAgentSettingsLoading } = useAgentSettings(agentId);const agentSettings = settingsData?.settings;+ const { data: chatParams, isLoading: isChatParamsLoading } = useChatParams(agentId || null);+const { mutateAsync: createChat, isPending: isChatCreating } = useCreateChat();const { mutateAsync: updateAgentSettings } = useSaveAgentSettings();const fileUpload = useFileUpload({@@ -120,19 +124,37 @@ export const ChatContextProvider: FC<TChildren> = ({ children }) => {Observability.observeInteraction(EVENTS.CHAT_EVENTS.SESSION_START);}, [createSession, setMessages, fileUpload, stopStreaming, scroll]);- // Display informational message when chatbot is disabled- useEffect(() => {- if (agentSettings?.chatbot === 'false') {- setMessages([- {- id: new Date().getTime(),- content:- 'This feature is disabled for your SmythOS Agent. \n\n To enable it, go to ***Agent Settings > Deployments*** and turn on ***"Chatbot"***',- type: 'info',- },- ]);+ /**+ * Computes the current page state based on loading, auth, and chatbot status+ */+ const pageState: TPageState = useMemo(() => {+ if (isAgentLoading || isAgentSettingsLoading || isChatParamsLoading) {+ return 'loading';+ }+ if (agentSettings?.chatbot === 'false' || chatParams?.chatbotEnabled === false) {+ return 'disabled';}- }, [agentSettings?.chatbot, setMessages]);+ // Check auth - if overridden locally, skip auth requirement+ if (chatParams?.authRequired && !isAuthOverridden) {+ return 'auth-required';+ }+ return 'ready';+ }, [+ isAgentLoading,+ isAgentSettingsLoading,+ isChatParamsLoading,+ agentSettings?.chatbot,+ chatParams,+ isAuthOverridden,+ ]);++ /**+ * Handler called after successful authentication+ * Directly sets auth as complete (like chatbot does)+ */+ const handleAuthSuccess = useCallback(async () => {+ setIsAuthOverridden(true);+ }, []);// Session trackinguseEffect(() => {@@ -140,13 +162,13 @@ export const ChatContextProvider: FC<TChildren> = ({ children }) => {return () => Observability.observeInteraction(EVENTS.CHAT_EVENTS.SESSION_END);}, []);- // Initialize chat session+ // Initialize chat session when page is readyuseEffect(() => {- if (agentSettings && agent && !hasInitializedChatRef.current) {+ if (pageState === 'ready' && !hasInitializedChatRef.current) {hasInitializedChatRef.current = true;createSession().then(() => inputRef.current?.focus());}- }, [agentSettings, agent, createSession]);+ }, [pageState, createSession]);// Auto-focus inputuseEffect(() => {@@ -175,17 +197,28 @@ export const ChatContextProvider: FC<TChildren> = ({ children }) => {scroll,modelOverride,setModelOverride,+ auth: {+ isRequired: (chatParams?.authRequired && !isAuthOverridden) || false,+ method: chatParams?.auth?.method,+ authorizationUrl: chatParams?.auth?.authorizationUrl,+ onAuthSuccess: handleAuthSuccess,+ },+ pageState,}),[agent,agentSettings,+ chatParams,fileUpload,+ handleAuthSuccess,isAgentLoading,isAgentSettingsLoading,+ isAuthOverridden,isChatCreating,isStreaming,messages,modelOverride,+ pageState,resetSession,retryLastMessage,scroll,diff --git a/packages/app/src/react/features/ai-chat/contexts/chat.ts b/packages/app/src/react/features/ai-chat/contexts/chat.tsindex a8b10d35..7f67217b 100644--- a/packages/app/src/react/features/ai-chat/contexts/chat.ts+++ b/packages/app/src/react/features/ai-chat/contexts/chat.ts@@ -1,15 +1,17 @@/* eslint-disable no-unused-vars */import type { IFileUpload, TChatMessage } from '@react/features/ai-chat/types';-import type { AgentDetails, AgentSettings } from '@react/shared/types/agent-data.types';+import type { Agent, AgentSettings } from '@react/shared/types/agent-data.types';import { createContext, RefObject } from 'react';+export type TPageState = 'loading' | 'error' | 'auth-required' | 'disabled' | 'ready';+export interface IChatContext {refs: {input?: RefObject<HTMLTextAreaElement | null>;container?: RefObject<HTMLDivElement | null>;};agent: {- data?: AgentDetails;+ data?: Agent;settings?: AgentSettings;isLoading: { agent: boolean; settings: boolean };};@@ -32,6 +34,13 @@ export interface IChatContext {};modelOverride: string | null;setModelOverride: (model: string | null) => void;+ auth: {+ isRequired: boolean;+ method?: string;+ authorizationUrl?: string;+ onAuthSuccess: () => Promise<void>;+ };+ pageState: TPageState;}export const ChatContext = createContext<IChatContext>({@@ -46,6 +55,7 @@ export const ChatContext = createContext<IChatContext>({remove: () => {},clear: () => {},clearError: () => {},+ removeByIds: () => {},},chat: {isChatCreating: false,@@ -65,4 +75,9 @@ export const ChatContext = createContext<IChatContext>({},modelOverride: null,setModelOverride: () => {},+ auth: {+ isRequired: false,+ onAuthSuccess: async () => {},+ },+ pageState: 'loading',});diff --git a/packages/app/src/react/features/ai-chat/hooks/index.ts b/packages/app/src/react/features/ai-chat/hooks/index.tsindex 78e07529..6c379a34 100644--- a/packages/app/src/react/features/ai-chat/hooks/index.ts+++ b/packages/app/src/react/features/ai-chat/hooks/index.ts@@ -1,4 +1,5 @@export * from './use-agent-settings';+export * from './use-chat-params';export * from './use-create-chat';export * from './use-chat-state';export * from './use-clipboard-paste';diff --git a/packages/app/src/react/features/ai-chat/hooks/use-chat-params.ts b/packages/app/src/react/features/ai-chat/hooks/use-chat-params.tsnew file mode 100644index 00000000..209c0a54--- /dev/null+++ b/packages/app/src/react/features/ai-chat/hooks/use-chat-params.ts@@ -0,0 +1,29 @@+import { useQuery } from '@tanstack/react-query';++import { ChatAPIClient } from '@react/features/ai-chat/clients/chat-api.client';+import type { TChatParams } from '@react/features/ai-chat/types';++const CHAT_PARAMS_QUERY = ['get', '/api/page/chat/params'];++const chatClient = new ChatAPIClient();++type TUseChatParams = ReturnType<typeof useQuery<TChatParams, Error>>;++/**+ * Hook to fetch chat configuration parameters for an agent+ *+ * @param agentId - The agent ID to fetch params for+ * @returns Query result with chat params data+ *+ * @example+ * ```typescript+ * const { data: params, isLoading, error } = useChatParams('agent-123');+ * if (params?.chatbotEnabled) {+ * // Chatbot is enabled+ * }+ * ```+ */+export const useChatParams = (agentId: string | null): TUseChatParams =>+ useQuery([...CHAT_PARAMS_QUERY, agentId], () => chatClient.getChatParams(agentId as string), {+ enabled: !!agentId,+ });diff --git a/packages/app/src/react/features/ai-chat/pages/ai-chat.tsx b/packages/app/src/react/features/ai-chat/pages/ai-chat.tsxindex 21400c98..b7949d83 100644--- a/packages/app/src/react/features/ai-chat/pages/ai-chat.tsx+++ b/packages/app/src/react/features/ai-chat/pages/ai-chat.tsx@@ -1,14 +1,95 @@+import { AuthOverlay } from '@react/features/ai-chat/components/auth/auth-overlay';import { Chats, Container, Footer, Header } from '@react/features/ai-chat/components';+import { Skeleton } from '@react/features/ai-chat/components/header/skeleton';import { ChatContextProvider } from '@react/features/ai-chat/contexts';+import { useChatStores } from '@react/features/ai-chat/hooks';import { memo } from 'react';+/**+ * Loading skeleton that mimics the chat UI layout+ */+const LoadingSkeleton = () => (+ <>+ {/* Header skeleton */}+ <div className="w-full max-w-4xl flex items-center gap-3 py-4 px-2">+ <Skeleton className="w-10 h-10 rounded-full" />+ <div className="flex flex-col gap-2">+ <Skeleton className="w-32 h-4 rounded" />+ <Skeleton className="w-20 h-3 rounded" />+ </div>+ </div>++ {/* Chat area skeleton */}+ <div className="w-full h-full flex-1 flex flex-col items-center justify-start pt-8 gap-4 overflow-hidden">+ <div className="w-full max-w-4xl space-y-4 px-2">+ <div className="flex justify-start">+ <Skeleton className="w-3/4 h-16 rounded-2xl" />+ </div>+ <div className="flex justify-end">+ <Skeleton className="w-1/2 h-12 rounded-2xl" />+ </div>+ <div className="flex justify-start">+ <Skeleton className="w-2/3 h-20 rounded-2xl" />+ </div>+ </div>+ </div>++ {/* Footer skeleton */}+ <div className="w-full max-w-4xl py-4 px-2">+ <Skeleton className="w-full h-14 rounded-2xl" />+ </div>+ </>+);++/**+ * Handles conditional rendering based on page state+ */+const ChatContent = () => {+ const { pageState } = useChatStores();++ // Loading state+ if (pageState === 'loading') {+ return <LoadingSkeleton />;+ }++ // Auth required+ if (pageState === 'auth-required') {+ return <AuthOverlay />;+ }++ // Chatbot disabled+ if (pageState === 'disabled') {+ return (+ <>+ <Header />+ <div className="w-full h-full flex items-center justify-center">+ <div className="text-center max-w-md p-8">+ <p className="text-gray-600">This feature is disabled for your SmythOS Agent.</p>+ <p className="text-gray-500 mt-2 text-sm">+ To enable it, go to <strong>Agent Settings → Deployments</strong> and turn on{' '}+ <strong>"Chatbot"</strong>+ </p>+ </div>+ </div>+ </>+ );+ }++ // Ready - show full chat UI+ return (+ <>+ <Header />+ <Chats />+ <Footer />+ </>+ );+};+const AgentChatPage = () => {return (<ChatContextProvider><Container>- <Header />- <Chats />- <Footer />+ <ChatContent /></Container></ChatContextProvider>);diff --git a/packages/app/src/react/features/ai-chat/types/hooks.ts b/packages/app/src/react/features/ai-chat/types/hooks.tsindex fe6b6354..af2d25d5 100644--- a/packages/app/src/react/features/ai-chat/types/hooks.ts+++ b/packages/app/src/react/features/ai-chat/types/hooks.ts@@ -2,6 +2,26 @@import type { Dispatch, RefObject, SetStateAction } from 'react';import type { TAttachment, TChatMessage, TUploadStatus } from '.';+/**+ * Chat configuration parameters returned from SRE server+ * Response from GET /v1/emb/chat/params+ */+export type TChatParams = {+ name?: string;+ domain?: string;+ port?: number;+ chatbotEnabled: boolean;+ authRequired?: boolean;+ auth?: {+ method?: string;+ redirectUri?: string;+ authorizationUrl?: string;+ clientID?: string;+ redirectInternalEndpoint?: string;+ };+ headers?: Record<string, string>;+};+export type TFocusable = { focus: () => void };export type TChatStateConfig = {diff --git a/packages/app/src/react/features/ai-chat/utils/index.ts b/packages/app/src/react/features/ai-chat/utils/index.tsindex 2f630ad4..3ffe4cf2 100644--- a/packages/app/src/react/features/ai-chat/utils/index.ts+++ b/packages/app/src/react/features/ai-chat/utils/index.ts@@ -1,7 +1,7 @@export * from './file';export * from './model';export * from './performance-monitor';-export * from './scroll';export * from './screenshot';+export * from './scroll';export * from './stream';export * from './textarea';diff --git a/packages/app/src/react/shared/hooks/agent.ts b/packages/app/src/react/shared/hooks/agent.tsindex e39a5106..cac99728 100644--- a/packages/app/src/react/shared/hooks/agent.ts+++ b/packages/app/src/react/shared/hooks/agent.ts@@ -6,10 +6,10 @@ const { data, error, isLoading, refetch, invalidate, setData } = useAgent(agent});*/-import { AgentDetails } from '@react/shared/types/agent-data.types';+import { Agent } from '@react/shared/types/agent-data.types';import { useQuery, useQueryClient } from '@tanstack/react-query';-const getAgent = async (agentId: string): Promise<AgentDetails> => {+const getAgent = async (agentId: string): Promise<Agent> => {const res = await fetch(`/api/agent/${agentId}`);if (!res.ok) {throw new Error('Network response was not ok');diff --git a/packages/app/src/react/shared/types/agent-data.types.ts b/packages/app/src/react/shared/types/agent-data.types.tsindex e7bf338e..1b074194 100644--- a/packages/app/src/react/shared/types/agent-data.types.ts+++ b/packages/app/src/react/shared/types/agent-data.types.ts@@ -60,6 +60,7 @@ export interface Agent {};}[];data?: {+ id: string;version: string;components: Component[];connections: Connection[];