diff --git a/src/components/FolderTree.tsx b/src/components/FolderTree.tsx index 2e99812a..f62104b6 100755 --- a/src/components/FolderTree.tsx +++ b/src/components/FolderTree.tsx @@ -177,19 +177,12 @@ const FolderTree = ({ const handleDragStart = (event: DragStartEvent) => { const draggedFolderId = event.active.id as string; setActiveId(draggedFolderId); - console.log('๐Ÿ–ฑ๏ธ Drag started:', draggedFolderId); }; const handleDragEnd = (event: DragEndEvent) => { const { active, over } = event; setActiveId(null); - console.log('๐Ÿ–ฑ๏ธ Drag ended:', { - activeId: active.id, - overId: over?.id, - overType: over?.data.current?.type, - }); - if (!over || active.id === over.id) return; const draggedFolder = folders.find(f => f._id === active.id); @@ -203,7 +196,6 @@ const FolderTree = ({ // Special case: All Personas folder (move to root level) if (targetFolder._id === 'all-personas-root') { - console.log('๐Ÿ–ฑ๏ธ Dropping to root level via All Personas'); newParentId = null; parentName = null; } else { @@ -277,13 +269,6 @@ const FolderTree = ({ sensors={sensors} collisionDetection={rectIntersection} onDragStart={handleDragStart} - onDragOver={(event) => { - console.log('๐Ÿ–ฑ๏ธ Drag over:', { - activeId: event.active.id, - overId: event.over?.id, - overData: event.over?.data.current, - }); - }} onDragEnd={handleDragEnd} >
diff --git a/src/components/ProtectedRoute.tsx b/src/components/ProtectedRoute.tsx index 1b4a3b7a..9507eec4 100755 --- a/src/components/ProtectedRoute.tsx +++ b/src/components/ProtectedRoute.tsx @@ -9,12 +9,6 @@ export default function ProtectedRoute({ children }: ProtectedRouteProps) { const { isAuthenticated, isLoading } = useAuth(); const location = useLocation(); - console.log('ProtectedRoute check:', { - isAuthenticated, - isLoading, - path: location.pathname - }); - if (isLoading) { // Show a loading spinner while authentication state is being determined return ( @@ -25,11 +19,9 @@ export default function ProtectedRoute({ children }: ProtectedRouteProps) { } if (!isAuthenticated) { - console.log('Not authenticated, redirecting to login'); // Redirect to the login page, but save the current location they were trying to access return ; } - console.log('User is authenticated, showing protected content'); return <>{children}; } \ No newline at end of file diff --git a/src/components/UserCreator.tsx b/src/components/UserCreator.tsx index 1e5b52d9..418ffdf5 100755 --- a/src/components/UserCreator.tsx +++ b/src/components/UserCreator.tsx @@ -147,14 +147,11 @@ export default function UserCreator({ targetFolderId, targetFolderName }: UserCr setIsAutoLoginInProgress(true); try { - console.log('Attempting auto login with default credentials'); await login('user', 'pass'); - console.log('Auto login successful'); - + // Verify the token was stored const storedToken = localStorage.getItem('auth_token'); if (storedToken) { - console.log('Token successfully stored:', storedToken.substring(0, 10) + '...'); toastService.success('Logged in automatically with default account'); } else { console.error('Token not stored after successful login'); @@ -322,7 +319,6 @@ export default function UserCreator({ targetFolderId, targetFolderName }: UserCr async function onSubmit(values: z.infer, isRetry = false) { // Prevent infinite loops by limiting retries if (isRetry && retryCount >= 1) { - console.log('Max retry attempts reached, stopping retry loop'); toastService.error("Authentication failed after multiple attempts", { description: "Please try logging in manually (user/pass)" }); @@ -333,7 +329,6 @@ export default function UserCreator({ targetFolderId, targetFolderName }: UserCr if (isRetry) { setRetryCount(prevCount => prevCount + 1); - console.log(`Retry attempt ${retryCount + 1}`); } else { setRetryCount(0); // Reset retry count for new submissions } @@ -344,9 +339,7 @@ export default function UserCreator({ targetFolderId, targetFolderName }: UserCr // If not authenticated, try to log in with default credentials if (!isAuthenticated) { try { - console.log('Not authenticated, attempting login with default credentials before submission'); await login('user', 'pass'); - console.log('Login successful before persona creation'); } catch (loginError) { console.error('Login failed before persona creation:', loginError); toastService.error("Authentication required", { @@ -362,8 +355,7 @@ export default function UserCreator({ targetFolderId, targetFolderName }: UserCr const generationToastId = `persona-generation-${Date.now()}`; const folderText = targetFolderId && targetFolderName ? ` in "${targetFolderName}" folder` : ''; const personaText = userCount > 1 ? `${userCount} personas` : 'persona'; - - console.log(`UserCreator - Creating ${personaText}${folderText}`); + toastService.createPersistent({ id: generationToastId, title: `Generating ${personaText}...`, @@ -408,24 +400,20 @@ export default function UserCreator({ targetFolderId, targetFolderName }: UserCr const token = localStorage.getItem('auth_token'); if (!token) { console.error("No authentication token found"); - toastService.error("Authentication required", { - description: "No valid token found. Please log in again." + toastService.error("Authentication required", { + description: "No valid token found. Please log in again." }); - + // Force a new login try { - console.log('No token found, attempting new login'); await login('user', 'pass'); - console.log('Login successful, token:', localStorage.getItem('auth_token')?.substring(0, 10) + '...'); } catch (loginError) { console.error('Login retry failed:', loginError); throw new Error('Authentication failed after retry'); } } - - console.log("Sending persona creation request to API with auth token"); + const result = await personasApi.create(personaData); - console.log("Persona created successfully:", result); // Update persistent toast with success toastService.updatePersistent(generationToastId, { @@ -473,24 +461,20 @@ export default function UserCreator({ targetFolderId, targetFolderName }: UserCr const token = localStorage.getItem('auth_token'); if (!token) { console.error("No authentication token found"); - toastService.error("Authentication required", { - description: "No valid token found. Please log in again." + toastService.error("Authentication required", { + description: "No valid token found. Please log in again." }); - + // Force a new login try { - console.log('No token found, attempting new login'); await login('user', 'pass'); - console.log('Login successful, token:', localStorage.getItem('auth_token')?.substring(0, 10) + '...'); } catch (loginError) { console.error('Login retry failed:', loginError); throw new Error('Authentication failed after retry'); } } - - console.log("Sending batch persona creation request to API with auth token"); + const result = await personasApi.createBatch(batch); - console.log("Batch personas created successfully:", result); // Update persistent toast with success toastService.updatePersistent(generationToastId, { @@ -513,7 +497,6 @@ export default function UserCreator({ targetFolderId, targetFolderName }: UserCr } } - console.log("Persona creation successful (database storage)"); form.reset(); // Remove temp data since we succeeded @@ -532,15 +515,13 @@ export default function UserCreator({ targetFolderId, targetFolderName }: UserCr retryCount < 1) { // Try to log in again with default credentials try { - console.log('Got auth error, attempting login retry with default credentials'); // Force clear any existing tokens that might be invalid localStorage.removeItem('auth_token'); - + const response = await authApi.login('user', 'pass'); if (response?.data?.access_token) { localStorage.setItem('auth_token', response.data.access_token); localStorage.setItem('user', JSON.stringify(response.data.user)); - console.log('Manual login successful, got new token:', response.data.access_token.substring(0, 10) + '...'); // If login succeeds, retry submission with retry flag toastService.info("Logged in with default account, retrying submission..."); diff --git a/src/components/focus-group-session/AutonomousDashboard.tsx b/src/components/focus-group-session/AutonomousDashboard.tsx index 369c43c1..0402ba17 100755 --- a/src/components/focus-group-session/AutonomousDashboard.tsx +++ b/src/components/focus-group-session/AutonomousDashboard.tsx @@ -112,25 +112,20 @@ const AutonomousDashboard = ({ fetchAllData(); if (useWebSocketEnabled && wsConnected) { - console.log('๐Ÿ“Š Setting up STABLE WebSocket event listeners for dashboard'); - // Handle analytics updates const handleAnalyticsUpdate = (data: any) => { - console.log('๐Ÿ“Š Received analytics update:', data); setAnalytics(data.analytics); setLastUpdated(new Date()); }; // Handle conversation state updates const handleStateUpdate = (data: any) => { - console.log('๐Ÿ“Š Received conversation state update:', data); setConversationState(data.state); setLastUpdated(new Date()); }; // Handle AI status updates for autonomous dashboard const handleAiStatusUpdate = (data: any) => { - console.log('๐Ÿ“Š Received AI status update in dashboard:', data); setAutonomousStatus(data.status); setLastUpdated(new Date()); }; @@ -138,16 +133,13 @@ const AutonomousDashboard = ({ // GPT-5 FIX: Would need window event listeners here like in FocusGroupSession // For now, just commenting out to avoid the error // const cleanupFunctions = [...]; - console.log('๐Ÿ“Š Dashboard WebSocket listeners temporarily disabled for GPT-5 fix'); // Cleanup using returned functions return () => { - console.log('๐Ÿ“Š Cleaning up STABLE dashboard WebSocket listeners'); // cleanupFunctions.forEach(cleanup => cleanup?.()); }; } else { // Fallback to polling when WebSocket is not available - console.log('๐Ÿ“Š Using polling for dashboard updates (WebSocket not available)'); const interval = setInterval(fetchAllData, 30000); return () => clearInterval(interval); } diff --git a/src/components/focus-group-session/DiscussionPanel.tsx b/src/components/focus-group-session/DiscussionPanel.tsx index aba0f4c4..8894bc88 100755 --- a/src/components/focus-group-session/DiscussionPanel.tsx +++ b/src/components/focus-group-session/DiscussionPanel.tsx @@ -289,15 +289,12 @@ const DiscussionPanel = ({ formData.append('assets', selectedFile); const uploadResponse = await focusGroupsApi.uploadAssets(focusGroupId, formData); - - console.log('Upload response:', uploadResponse?.data); - + // Parse the actual backend response structure const responseData = uploadResponse?.data; if (responseData && responseData.assets && responseData.assets.length > 0) { // Backend returns: { assets: [{ filename: 'fg-...', original_name: '...', ... }] } uploadedFilename = responseData.assets[0].filename; - console.log('Successfully got filename from upload response:', uploadedFilename); } else { console.error('Invalid upload response structure:', responseData); } @@ -331,9 +328,7 @@ const DiscussionPanel = ({ // Format message text to include the display reference instead of filename finalMessageText = `Please review ${displayReference}. ${userInput}`; - - console.log('Using display reference in message:', displayReference); - + } catch (assetError) { console.error('Error fetching asset metadata:', assetError); // Fallback to generic reference @@ -383,8 +378,6 @@ const DiscussionPanel = ({ const response = await focusGroupsApi.sendMessage(focusGroupId, messageData); - console.log('Message sent to API:', response); - // Message will be handled by WebSocket system with correct server timestamp // No need to manually create and add message here @@ -724,11 +717,8 @@ const DiscussionPanel = ({ const startAutonomousConversation = async () => { if (!focusGroupId) return; - console.log('Starting AI Mode: setting autonomousLoading to true'); setAutonomousLoading(true); try { - console.log('Starting AI Mode: calling API...'); - // Add a timeout wrapper to the API call const apiCallWithTimeout = Promise.race([ focusGroupAiApi.startAutonomousConversation(focusGroupId), // No initial prompt - let AI generate based on discussion guide @@ -738,8 +728,7 @@ const DiscussionPanel = ({ ]); const response = await apiCallWithTimeout; - console.log('Starting AI Mode: API response received:', response); - + if (response.data.error) { toast.error('Failed to start autonomous conversation', { description: response.data.error @@ -757,17 +746,14 @@ const DiscussionPanel = ({ // Notify parent component of status change and wait for it to complete try { - console.log('Starting AI Mode: calling onStatusChange...'); if (onStatusChange) { await onStatusChange(); - console.log('Starting AI Mode: onStatusChange completed successfully'); } } catch (statusError) { console.error('Starting AI Mode: onStatusChange failed:', statusError); } - + // Reset loading state after status has been updated - console.log('Starting AI Mode: resetting autonomousLoading to false'); setAutonomousLoading(false); // GPT-5 FIX: Don't clear AI mode state - this was tearing down WebSocket listeners @@ -801,7 +787,6 @@ const DiscussionPanel = ({ const stopAutonomousConversation = async () => { if (!focusGroupId) return; - console.log('Stopping AI Mode: setting autonomousLoading to true'); setAutonomousLoading(true); try { const response = await focusGroupAiApi.stopAutonomousConversation(focusGroupId, 'manual_stop'); @@ -825,17 +810,14 @@ const DiscussionPanel = ({ // Notify parent component of status change and wait for it to complete try { - console.log('Stopping AI Mode: calling onStatusChange...'); if (onStatusChange) { await onStatusChange(); - console.log('Stopping AI Mode: onStatusChange completed successfully'); } } catch (statusError) { console.error('Stopping AI Mode: onStatusChange failed:', statusError); } - + // Reset loading state after status has been updated - console.log('Stopping AI Mode: resetting autonomousLoading to false'); setAutonomousLoading(false); // GPT-5 FIX: Don't clear AI mode state - this was tearing down WebSocket listeners @@ -946,8 +928,6 @@ const DiscussionPanel = ({ ); if (response?.data?.response) { - console.log('Generated response from mentioned participant:', response.data); - const aiMessage: Message = { id: response.data.message_id || `msg-${Date.now()}-${participantId}`, senderId: participantId, @@ -1074,8 +1054,6 @@ const DiscussionPanel = ({ } } else { // AI decided on a different action - handle or fall back to round-robin - console.log("AI suggested different action:", decision.action); - if (decision.action === 'moderator_speak') { toast.info("AI suggests moderator intervention", { description: `AI reasoning: ${decision.reasoning.substring(0, 100)}${decision.reasoning.length > 100 ? '...' : ''}` diff --git a/src/components/persona/PersonaEditor.tsx b/src/components/persona/PersonaEditor.tsx index 95561e45..8c87bc92 100755 --- a/src/components/persona/PersonaEditor.tsx +++ b/src/components/persona/PersonaEditor.tsx @@ -282,7 +282,6 @@ export default function PersonaEditor({ persona, onSave, onCancel }: PersonaEdit // Save to backend - handle local IDs specially if (personaId && typeof personaId === 'string' && personaId.startsWith('local-')) { - console.log('Creating new persona instead of updating local ID'); response = await personasApi.create(personaToSave); toast.success("Persona saved to database"); @@ -333,7 +332,6 @@ export default function PersonaEditor({ persona, onSave, onCancel }: PersonaEdit if (error.response && error.response.status === 401) { // Check if we're already authenticated according to context if (isAuthenticated && token) { - console.log("Auth error despite having token - token likely invalid"); toast.error("Authentication error - saving locally instead"); // Just save locally without showing login onSave(editedPersona); diff --git a/src/components/persona/PersonaProfile.tsx b/src/components/persona/PersonaProfile.tsx index 6aad1d53..d4d9e366 100755 --- a/src/components/persona/PersonaProfile.tsx +++ b/src/components/persona/PersonaProfile.tsx @@ -104,8 +104,6 @@ export default function PersonaProfile() { // Use the persona's MongoDB _id or fallback to id const personaId = currentPersona._id || currentPersona.id; - console.log(`๐Ÿ”ฝ Frontend: Exporting profile for persona ${currentPersona.name} (ID: ${personaId})`); - // Call the export API with GPT-4.1 const response = await personasApi.exportProfile(personaId, { llm_model: 'gpt-4.1', diff --git a/src/config/msalConfig.ts b/src/config/msalConfig.ts index bc6f053a..6a4b5766 100755 --- a/src/config/msalConfig.ts +++ b/src/config/msalConfig.ts @@ -16,7 +16,6 @@ export const msalConfig: Configuration = { loggerOptions: { loggerCallback: (level, message, containsPii) => { if (containsPii) return; - console.log(message); }, logLevel: LogLevel.Error, piiLoggingEnabled: false, diff --git a/src/contexts/AuthContext.tsx b/src/contexts/AuthContext.tsx index c5e21468..4a43906a 100755 --- a/src/contexts/AuthContext.tsx +++ b/src/contexts/AuthContext.tsx @@ -73,7 +73,6 @@ export function AuthProvider({ children }: { children: ReactNode }) { // For persona creation errors, don't clear session or redirect if (details.isPersonaCreation) { - import.meta.env.DEV && console.log('Ignoring auth error from persona creation', details); return; } @@ -87,9 +86,7 @@ export function AuthProvider({ children }: { children: ReactNode }) { const handleWebSocketAuthError = (event: Event) => { const customEvent = event as CustomEvent; const errorData = customEvent.detail || {}; - - import.meta.env.DEV && console.log('WebSocket authentication error:', errorData); - + // Clear auth data and redirect to login clearAuthData(); toast.error('Session expired', { @@ -132,30 +129,21 @@ export function AuthProvider({ children }: { children: ReactNode }) { // Check if user is already logged in const storedToken = localStorage.getItem('auth_token'); const storedUser = localStorage.getItem('user'); - - import.meta.env.DEV && console.log('AuthContext initializing - stored data check:', { - hasToken: !!storedToken, - hasUser: !!storedUser - }); - + if (storedToken && storedUser) { // Check if token is expired if (isTokenExpired(storedToken)) { - import.meta.env.DEV && console.log('Stored token is expired, clearing authentication data'); clearAuthData(); toast.error('Session expired', { description: 'Please log in again' }); } else { try { setToken(storedToken); setUser(JSON.parse(storedUser)); - import.meta.env.DEV && console.log('User session restored from localStorage'); } catch (error) { console.error('Failed to parse stored user data:', error); clearAuthData(); } } - } else { - import.meta.env.DEV && console.log('No stored authentication data found'); } setIsLoading(false); @@ -164,21 +152,17 @@ export function AuthProvider({ children }: { children: ReactNode }) { // Verify token is valid by fetching user profile useEffect(() => { if (token) { - import.meta.env.DEV && console.log('Verifying token...'); - // Set a flag to avoid unnecessary token validation on every render const validationKey = `token_validated_${token.substring(0, 10)}`; const alreadyValidated = sessionStorage.getItem(validationKey); - + if (alreadyValidated === 'true' && user) { - import.meta.env.DEV && console.log('Token already validated this session, skipping validation'); return; } - + authApi.getProfile() .then(response => { if (response && 'data' in response) { - import.meta.env.DEV && console.log('Profile verified successfully'); setUser(response.data); // Mark this token as validated for this session sessionStorage.setItem(validationKey, 'true'); @@ -196,19 +180,15 @@ export function AuthProvider({ children }: { children: ReactNode }) { // Do not mark as validated on non-401 errors; allow retry on next render } }); - } else { - import.meta.env.DEV && console.log('No token available, not validating profile'); } }, [token, user]); const login = async (username: string, password: string) => { setIsLoading(true); - import.meta.env.DEV && console.log('Attempting login for user:', username); - + try { const response = await authApi.login(username, password); - import.meta.env.DEV && console.log('Login API response received'); - + if (!response.data.access_token) { throw new Error('No access token received from server'); } @@ -220,8 +200,7 @@ export function AuthProvider({ children }: { children: ReactNode }) { // Update state setToken(response.data.access_token); setUser(response.data.user); - - import.meta.env.DEV && console.log('Authentication state updated'); + toast.success('Login successful!'); // Return the token to indicate successful login @@ -240,7 +219,6 @@ export function AuthProvider({ children }: { children: ReactNode }) { const loginWithMicrosoft = async () => { setIsMsalLoading(true); try { - import.meta.env.DEV && console.log('Starting Microsoft authentication (redirect)...'); await instance.loginRedirect(loginRequest); // Page navigates away โ€” execution stops here } catch (error: any) { diff --git a/src/hooks/usePersonaDetails.ts b/src/hooks/usePersonaDetails.ts index d672bc2c..47016934 100755 --- a/src/hooks/usePersonaDetails.ts +++ b/src/hooks/usePersonaDetails.ts @@ -585,7 +585,6 @@ export function usePersonaDetails() { const data = response.data; if (isMounted) { - console.log('Found persona in database:', data); // If we get a valid response, use it setCurrentPersona({ ...data, @@ -687,8 +686,7 @@ export function usePersonaDetails() { if (isExistingDbPersona && id && id.length === 24 && /^[0-9a-f]{24}$/i.test(id)) { // Update existing database persona const updateResult = await personasApi.update(id, personaToSend); - console.log('Updated persona in database:', updateResult); - + // Update the local state with the edited persona const updatedDbPersona = { ...updatedPersona, @@ -700,8 +698,7 @@ export function usePersonaDetails() { } else { // Create new persona in database const createResponse = await personasApi.create(personaToSend); - console.log('Created new persona in database:', createResponse.data); - + // Update the persona with database ID const dbPersona = { ...updatedPersona, diff --git a/src/hooks/usePersonaStorage.ts b/src/hooks/usePersonaStorage.ts index 861bb0b6..18c64f7c 100755 --- a/src/hooks/usePersonaStorage.ts +++ b/src/hooks/usePersonaStorage.ts @@ -20,8 +20,7 @@ export function usePersonaStorage() { } const result = await personasApi.create(personaToSave); - console.log('Persona saved to database:', result.data); - + // Add the database ID to the persona savedPersonas.push({ ...persona, @@ -37,7 +36,6 @@ export function usePersonaStorage() { const loadPersonas = async (): Promise => { const response = await personasApi.getAll(); if (response && response.data && Array.isArray(response.data)) { - console.log('Personas loaded from database:', response.data.length); return response.data.map(p => ({ ...p, id: p._id || p.id, diff --git a/src/hooks/useWebSocket.ts b/src/hooks/useWebSocket.ts index 15c9b05c..45296cb9 100755 --- a/src/hooks/useWebSocket.ts +++ b/src/hooks/useWebSocket.ts @@ -33,7 +33,6 @@ export function useWebSocket( ): UseWebSocketReturn { const instanceId = useRef(Math.random().toString(36).substr(2, 9)); - console.log(`[WebSocket-${instanceId.current}] Hook initialized`); const { autoConnect = true, maxReconnectAttempts = 5, @@ -52,10 +51,7 @@ export function useWebSocket( const reconnectTimeoutRef = useRef(); const currentFocusGroupRef = useRef(null); - const log = useCallback((message: string, ...args: any[]) => { - if (enableLogging) { - console.log(`[WebSocket-${instanceId.current}] ${message}`, ...args); - } + const log = useCallback((_message: string, ..._args: any[]) => { }, [enableLogging]); const updateState = useCallback((updates: Partial) => { @@ -175,14 +171,6 @@ export function useWebSocket( // Disconnection socket.on('disconnect', (reason) => { log('Disconnected:', reason); - console.log(`๐Ÿ”Œ [WebSocket-${instanceId.current}] DISCONNECT DEBUG:`, { - reason, - wasIntentional: reason === 'io client disconnect', - reconnectAttempts: state.reconnectAttempts, - maxAttempts: maxReconnectAttempts, - timestamp: new Date().toISOString() - }); - updateState({ isConnected: false, isConnecting: false, @@ -217,13 +205,6 @@ export function useWebSocket( updateState({ error: error.message || 'WebSocket error occurred' }); }); - // DEBUG: Listen for ALL events - const originalEmit = socket.onevent; - socket.onevent = function(packet) { - console.log(`๐Ÿ”ฅ [WebSocket-${instanceId.current}] RAW EVENT RECEIVED:`, packet); - return originalEmit.call(this, packet); - }; - }, [token, log, updateState, maxReconnectAttempts, reconnectDelay, state.reconnectAttempts]); const disconnect = useCallback(() => { diff --git a/src/lib/api.ts b/src/lib/api.ts index 2fa38a48..d72b0cbd 100755 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -33,7 +33,6 @@ api.interceptors.request.use( if (token) { // Check if token is expired before making request if (isTokenExpired(token)) { - import.meta.env.DEV && console.log('Token expired, clearing auth data before request'); localStorage.removeItem('auth_token'); localStorage.removeItem('user'); localStorage.removeItem('auth_type'); @@ -48,27 +47,6 @@ api.interceptors.request.use( config.headers.Authorization = `Bearer ${token}`; } - if (import.meta.env.DEV) { - if (config.method === 'put' && config.url?.includes('/focus-groups/')) { - import.meta.env.DEV && console.log('๐ŸŒ API Request:', { - method: config.method, - url: config.url, - baseURL: config.baseURL, - fullURL: `${config.baseURL}${config.url}`, - data: config.data - }); - } - if (config.url?.includes('/folders/')) { - import.meta.env.DEV && console.log('๐ŸŒ API Folder Request:', { - method: config.method, - url: config.url, - baseURL: config.baseURL, - fullURL: `${config.baseURL}${config.url}`, - data: config.data - }); - } - } - return config; }, (error) => Promise.reject(error) @@ -112,11 +90,6 @@ api.interceptors.response.use( error.config.url?.includes('/personas/batch') || (error.config.method && error.config.url?.startsWith('/personas'))); - import.meta.env.DEV && console.log('API Error:', { - url: error.config?.url, - method: error.config?.method, - isPersonaRequest: isPersonaRequest - }); // For persona-related requests, don't automatically log out // Let the component handle the auth error @@ -163,7 +136,6 @@ export const personasApi = { update: (id: string, personaData: any) => { // Don't try to update with local-prefixed IDs - they won't work if (id && id.startsWith('local-')) { - import.meta.env.DEV && console.log('Cannot update with local ID, creating new instead:', id); return api.post('/personas', personaData); } return api.put(`/personas/${id}`, personaData); @@ -171,8 +143,6 @@ export const personasApi = { modifyWithAI: (id: string, modificationData: any) => { const personaId = typeof id === 'object' && id !== null ? (id as any)._id || id : id; - const mode = modificationData.preview_only ? 'Previewing' : 'Modifying'; - import.meta.env.DEV && console.log(`${mode} persona with AI, ID: ${personaId}`); return api.post(`/personas/${personaId}/modify-with-ai`, modificationData); }, @@ -181,7 +151,6 @@ export const personasApi = { // If the ID is an object with an _id property, use that // Otherwise, use the provided ID string const personaId = typeof id === 'object' && id !== null ? (id as any)._id || id : id; - import.meta.env.DEV && console.log(`Deleting persona with ID: ${personaId}`); return api.delete(`/personas/${personaId}`); }, @@ -295,10 +264,6 @@ export const aiPersonasApi = { onTaskIdReceived?: (taskId: string) => void ) => { try { - // Log the API call with model information - import.meta.env.DEV && console.log(`๐Ÿ“ก API call to generate-basic-profiles with model: ${llmModel || 'gemini-2.5-pro'}`); - import.meta.env.DEV && console.log('๐Ÿ”ฅ onTaskIdReceived callback provided:', !!onTaskIdReceived); - // First stage: Generate basic profiles const basicProfilesResponse = await api.post('/ai-personas/generate-basic-profiles', { audience_brief: audienceBrief, @@ -311,26 +276,18 @@ export const aiPersonasApi = { timeout: 180000 // 3 minutes for basic profile generation }); - import.meta.env.DEV && console.log('๐Ÿ”ฅ First stage response:', basicProfilesResponse.data); const basicProfiles = basicProfilesResponse.data.profiles; const taskId = basicProfilesResponse.data.task_id; // Extract task_id from first call - import.meta.env.DEV && console.log('๐Ÿ”ฅ Extracted taskId:', taskId); - + // Call the callback immediately with the task ID if (taskId && onTaskIdReceived) { - import.meta.env.DEV && console.log('๐Ÿ”ฅ Calling onTaskIdReceived with taskId:', taskId); onTaskIdReceived(taskId); - } else { - import.meta.env.DEV && console.log('๐Ÿ”ฅ Not calling callback - taskId:', taskId, 'callback:', !!onTaskIdReceived); } const personas = []; const personaIds = []; const errors = []; - // Log the second stage API calls with model information - import.meta.env.DEV && console.log(`๐Ÿ“ก API call to complete-and-save-persona with model: ${llmModel || 'gemini-2.5-pro'}`); - // Second stage: Complete each profile in parallel const completeRequests = basicProfiles.map(profile => api.post('/ai-personas/complete-and-save-persona', { @@ -401,9 +358,6 @@ export const aiPersonasApi = { // Batch generate summaries for download batchGenerateSummaries: (personaIds: string[], temperature: number = 0.7, llmModel?: string) => { - // Log the API call with model information - import.meta.env.DEV && console.log(`๐Ÿ“ก Frontend: API call to batch-generate-summaries with model: ${llmModel || 'gemini-2.5-pro'}`); - return api.post('/ai-personas/batch-generate-summaries', { persona_ids: personaIds, temperature, @@ -442,8 +396,6 @@ export const aiPersonasApi = { llmModel?: string, targetFolderId?: string ) => { - import.meta.env.DEV && console.log(`๐Ÿ“ก API call to generate-personas-full with model: ${llmModel || 'gemini-2.5-pro'}`); - return api.post('/ai-personas/generate-personas-full', { audience_brief: audienceBrief, research_objective: researchObjective, @@ -717,8 +669,7 @@ export const foldersApi = { api.post(`/folders/${folderId}/personas/batch`, { persona_ids: personaIds }), removePersonasBatch: (folderId: string, personaIds: string[]) => { - import.meta.env.DEV && console.log(`๐ŸŒ API removePersonasBatch: Sending POST to /folders/${folderId}/personas/remove-batch with persona_ids:`, personaIds); - return api.post(`/folders/${folderId}/personas/remove-batch`, { + return api.post(`/folders/${folderId}/personas/remove-batch`, { persona_ids: personaIds }); }, diff --git a/src/pages/FocusGroupSession.tsx b/src/pages/FocusGroupSession.tsx index 976a07f3..6d014cd1 100755 --- a/src/pages/FocusGroupSession.tsx +++ b/src/pages/FocusGroupSession.tsx @@ -142,7 +142,6 @@ const FocusGroupSession = () => { // Initialize singleton socket (GPT-5 fix: avoid useMemo issues) useEffect(() => { if (useWebSocketEnabled) { - console.log('๐Ÿ”ง [GPT-5 Session] Initializing WebSocket'); initSocket(getAccessToken); } }, [useWebSocketEnabled, getAccessToken]); @@ -152,7 +151,6 @@ const FocusGroupSession = () => { if (!useWebSocketEnabled || !id) return; const tryJoin = () => { - console.log('๐Ÿ”ง [GPT-5 Session] Joining focus group:', id); joinFocusGroup(id); }; @@ -184,19 +182,9 @@ const FocusGroupSession = () => { useEffect(() => { if (!useWebSocketEnabled) return; - console.log('๐Ÿ”ง [GPT-5 Session] Setting up window event listeners'); - // Handle message updates const onMessageUpdate = (e: CustomEvent) => { const data = e.detail; - console.log('๐Ÿ”ง [GPT-5 Session] message_update:', data); - - // Debug focus group filtering - if (data.focus_group_id) { - console.log('๐Ÿ”ง [GPT-5] Message focus_group_id:', data.focus_group_id); - console.log('๐Ÿ”ง [GPT-5] Current focus group from URL:', id); - } - const newMessage = convertWebSocketMessage(data.message); if (!newMessage) { console.error('๐Ÿ”ง [GPT-5] convertWebSocketMessage returned null'); @@ -207,11 +195,9 @@ const FocusGroupSession = () => { // Check for duplicates const exists = prev.find(m => m.id === newMessage.id); if (exists) { - console.log('๐Ÿ”ง [GPT-5] Message already exists, skipping'); return prev; } - - console.log('๐Ÿ”ง [GPT-5] Adding new message, count:', prev.length + 1); + return [...prev, newMessage]; }); }; @@ -219,9 +205,7 @@ const FocusGroupSession = () => { // Handle AI status updates - GPT-5 fix: functional state updates const onAiStatusUpdate = (e: CustomEvent) => { const data = e.detail; - console.log('๐Ÿ”ง [GPT-5 Session] ai_status_update:', data); - - // GPT-5 fix: Use functional updates to prevent stale closures during AI mode + // GPT-5 fix: Use functional updates to prevent stale closures during AI mode setIsAiModeActive(prev => data.status.status === 'ai_mode'); setSessionStatus(prev => data.status.status); }; @@ -229,14 +213,12 @@ const FocusGroupSession = () => { // Handle moderator status updates const onModeratorStatusUpdate = (e: CustomEvent) => { const data = e.detail; - console.log('๐Ÿ”ง [GPT-5 Session] moderator_status_update:', data); setModeratorStatus(data.moderator_status); }; // Handle theme updates const onThemeUpdate = (e: CustomEvent) => { const data = e.detail; - console.log('๐Ÿ”ง [GPT-5 Session] theme_update:', data); const theme = convertWebSocketTheme(data.theme); setThemes(prev => { @@ -254,14 +236,12 @@ const FocusGroupSession = () => { // Handle focus group updates const onFocusGroupUpdate = (e: CustomEvent) => { const data = e.detail; - console.log('๐Ÿ”ง [GPT-5 Session] focus_group_update:', data); setFocusGroup(prev => prev ? { ...prev, ...data } : null); }; // Handle mode event updates const onModeEventUpdate = (e: CustomEvent) => { const data = e.detail; - console.log('๐Ÿ”ง [GPT-5 Session] mode_event_update:', data); // Convert timestamp to Date object const modeEvent = { @@ -274,22 +254,17 @@ const FocusGroupSession = () => { setModeEvents(prev => { const existingIndex = prev.findIndex(event => event.id === modeEvent.id); if (existingIndex >= 0) { - console.log('๐Ÿ”ง [GPT-5 Session] Mode event already exists, skipping:', modeEvent.id); return prev; // Don't add duplicate } - console.log('๐Ÿ”ง [GPT-5 Session] Adding new mode event:', modeEvent.id); return [...prev, modeEvent]; }); }; // Handle room join confirmations - const onJoinedFocusGroup = (e: CustomEvent) => { - const data = e.detail; - console.log('๐Ÿ”ง [GPT-5 Session] joined_focus_group:', data); + const onJoinedFocusGroup = (_e: CustomEvent) => { }; // Add window event listeners - console.log('๐Ÿ”ง [GPT-5 Session] ADDING window event listeners'); window.addEventListener('ws:message_update', onMessageUpdate as any); window.addEventListener('ws:ai_status_update', onAiStatusUpdate as any); window.addEventListener('ws:moderator_status_update', onModeratorStatusUpdate as any); @@ -297,11 +272,9 @@ const FocusGroupSession = () => { window.addEventListener('ws:focus_group_update', onFocusGroupUpdate as any); window.addEventListener('ws:mode_event_update', onModeEventUpdate as any); window.addEventListener('ws:joined_focus_group', onJoinedFocusGroup as any); - console.log('๐Ÿ”ง [GPT-5 Session] ADDED all window event listeners'); // Cleanup window event listeners return () => { - console.log('๐Ÿ”ง [GPT-5 Session] Cleaning up window event listeners'); window.removeEventListener('ws:message_update', onMessageUpdate as any); window.removeEventListener('ws:ai_status_update', onAiStatusUpdate as any); window.removeEventListener('ws:moderator_status_update', onModeratorStatusUpdate as any); @@ -564,7 +537,6 @@ const FocusGroupSession = () => { try { const response = await focusGroupsApi.getMessages(id); - console.log('๐Ÿ” [FetchMessages] Raw API response:', response?.data); // Handle both old (array) and new (object with messages/mode_events) response formats let messagesData: any[] = []; @@ -597,15 +569,6 @@ const FocusGroupSession = () => { visualAsset: msg.visualAsset // Include visual asset metadata for image display })); - console.log('๐Ÿ” [FetchMessages] Formatted messages with visual assets:', - formattedMessages.filter(m => m.visualAsset).map(m => ({ - id: m.id, - senderId: m.senderId, - hasVisualAsset: !!m.visualAsset, - visualAsset: m.visualAsset - })) - ); - // Convert dates and format mode events const formattedModeEvents = modeEventsData.map((event: any) => ({ id: event._id || event.id || `event-${Date.now()}`, @@ -719,8 +682,7 @@ const FocusGroupSession = () => { if (response && response.data) { const data = response.data; - console.log("Focus group data from API:", data); - + // Process focus group data const focusGroupData = { id: data._id || data.id, @@ -747,18 +709,12 @@ const FocusGroupSession = () => { id: p._id || p.id }))); } else if (focusGroupData.participants && Array.isArray(focusGroupData.participants)) { - console.log("Matching participants from DB:", { - focusGroupParticipants: focusGroupData.participants, - allPersonas: allPersonas.map(p => ({ id: p._id || p.id, name: p.name })) - }); - // Otherwise use real personas from the database const groupParticipants = allPersonas.filter(persona => { const personaId = persona._id || persona.id; return focusGroupData.participants.includes(personaId); }); - - console.log("Matched participants:", groupParticipants.map(p => p.name)); + setParticipants(groupParticipants); } @@ -786,10 +742,7 @@ const FocusGroupSession = () => { // Function to update the LLM model for this focus group const updateFocusGroupModel = async (newModel: string, reasoningEffort?: string, verbosity?: string) => { - console.log('๐Ÿ”ง updateFocusGroupModel called with:', { id, focusGroup: !!focusGroup, newModel, reasoningEffort, verbosity }); - if (!id || !focusGroup) { - console.log('โŒ updateFocusGroupModel: Missing id or focusGroup', { id, focusGroup: !!focusGroup }); return; } @@ -803,11 +756,8 @@ const FocusGroupSession = () => { updateData.verbosity = verbosity || selectedVerbosity; } - console.log('๐Ÿ”ง Making API call to update focus group model:', { id, updateData }); const response = await focusGroupsApi.update(id, updateData); - - console.log('๐Ÿ”ง API response:', response); - + if (response && response.data) { setFocusGroup(prev => prev ? { ...prev, @@ -823,9 +773,6 @@ const FocusGroupSession = () => { } for AI responses` }); setShowModelSettings(false); - console.log('โœ… Model update successful'); - } else { - console.log('โŒ API response missing data:', response); } } catch (error) { console.error('โŒ Error updating focus group model:', error); @@ -838,8 +785,6 @@ const FocusGroupSession = () => { }; useEffect(() => { - console.log("Looking for focus group with ID:", id); - // Fetch all personas from the database first const fetchAllPersonas = async () => { try { @@ -858,8 +803,7 @@ const FocusGroupSession = () => { if (response && response.data) { const data = response.data; - console.log("Focus group data from API:", data); - + // Process focus group data const focusGroupData = { id: data._id || data.id, @@ -886,18 +830,12 @@ const FocusGroupSession = () => { id: p._id || p.id }))); } else if (focusGroupData.participants && Array.isArray(focusGroupData.participants)) { - console.log("Matching participants from DB:", { - focusGroupParticipants: focusGroupData.participants, - allPersonas: allPersonas.map(p => ({ id: p._id || p.id, name: p.name })) - }); - // Otherwise use real personas from the database const groupParticipants = allPersonas.filter(persona => { const personaId = persona._id || persona.id; return focusGroupData.participants.includes(personaId); }); - - console.log("Matched participants:", groupParticipants.map(p => p.name)); + setParticipants(groupParticipants); } @@ -928,7 +866,6 @@ const FocusGroupSession = () => { const shouldUsePolling = !useWebSocketEnabled || (useWebSocketEnabled && wsConnectionFailed); if (shouldUsePolling) { - console.log(useWebSocketEnabled ? '๐Ÿ“ก WebSocket connection failed, falling back to polling' : '๐Ÿ“ก WebSocket disabled, using polling for updates'); const startDynamicPolling = () => { const pollMessages = () => { fetchMessages(); @@ -944,22 +881,12 @@ const FocusGroupSession = () => { // Set new interval based on current AI mode status const interval = isAiModeActive ? 3000 : 10000; // 3s when AI active, 10s when inactive - - // DEBUG: Log polling setup - console.log('๐Ÿ“ก Setting up message polling:', { - aiModeActive: isAiModeActive, - pollInterval: interval, - timestamp: new Date().toISOString() - }); - + messageRefreshInterval = window.setInterval(() => { // Skip polling when editing discussion guide to prevent focus loss if (!isEditingDiscussionGuideRef.current) { - console.log('๐Ÿ“ก Polling for messages...', new Date().toISOString()); fetchMessages(); fetchModeratorStatus(); - } else { - console.log('๐Ÿ“ก Skipping poll - editing discussion guide'); } }, interval); }; @@ -1003,8 +930,6 @@ const FocusGroupSession = () => { }; startDynamicPolling(); - } else { - console.log('๐Ÿ“ก WebSocket enabled, skipping polling setup'); } } else { console.error("Focus group not found with ID:", id); @@ -1114,12 +1039,9 @@ const FocusGroupSession = () => { const hasExistingPosition = currentStatus?.data?.status?.moderator_position; if (!hasExistingPosition) { - await focusGroupAiApi.setModeratorPosition(id, + await focusGroupAiApi.setModeratorPosition(id, focusGroup?.discussionGuide?.sections?.[0]?.id || 'welcome' ); - console.log('๐Ÿš€ Moderator position initialized to start of discussion guide (first time)'); - } else { - console.log('๐Ÿ“ Preserving existing moderator position:', hasExistingPosition); } } catch (error) { console.warn('Failed to check/initialize moderator position:', error); @@ -1141,12 +1063,6 @@ const FocusGroupSession = () => { type: 'question' }); - console.log('๐Ÿš€ Initial moderator message created:', { - content: firstDiscussionItem.content, - sectionId: firstDiscussionItem.sectionId, - itemId: firstDiscussionItem.itemId - }); - } catch (messageError) { console.warn('Failed to create initial moderator message:', messageError); // Don't fail the entire session start if message creation fails @@ -1196,11 +1112,9 @@ const FocusGroupSession = () => { // Check for duplicates const exists = prevMessages.find(m => m.id === message.id); if (exists) { - console.log('๐Ÿ”ง [handleNewMessage] Message already exists, skipping:', message.id); return prevMessages; } - - console.log('๐Ÿ”ง [handleNewMessage] Adding new message:', message.id); + return [...prevMessages, message]; }); }; @@ -1227,8 +1141,6 @@ const FocusGroupSession = () => { // Don't attempt to update local test messages in the database if (!messageId.startsWith('local-') && !messageId.startsWith('msg-')) { await focusGroupsApi.updateMessageHighlight(id, messageId, newHighlightState); - } else { - console.log('Skipping database update for local message:', messageId); } } catch (error) { console.error('Error updating message highlight state:', error); @@ -1401,16 +1313,6 @@ const FocusGroupSession = () => { } if (matchingMessage) { - // Log successful match for debugging - console.log(`Quote match found using strategy: ${matchReason}`, { - quoteType: isQuoteData ? 'QuoteData' : 'string', - providedMessageId: messageId, - extractedText: quoteText, - matchedMessage: matchingMessage.text.substring(0, 100), - matchedMessageId: matchingMessage.id, - originalQuote: originalQuote.substring(0, 100) - }); - // Switch to discussion tab setActiveTab('chat'); @@ -1509,12 +1411,6 @@ const FocusGroupSession = () => { // Handler for saving discussion guide changes const handleDiscussionGuideSave = useCallback(async (updatedGuide: any) => { - console.log('๐Ÿ’พ handleDiscussionGuideSave called:', { - hasId: !!id, - isEditingGuideContent, - timestamp: new Date().toISOString() - }); - if (!id) return; try { @@ -1524,7 +1420,6 @@ const FocusGroupSession = () => { // Only update local state if we're not currently editing to prevent focus loss if (!isEditingGuideContent) { - console.log('๐Ÿ”„ Updating focus group state (not editing)'); setFocusGroup(prev => prev ? { ...prev, discussionGuide: updatedGuide @@ -1537,7 +1432,6 @@ const FocusGroupSession = () => { discussionGuide: updatedGuide }; } - console.log('โš ๏ธ Skipping focus group state update during editing to preserve focus'); } } catch (error) { @@ -1548,19 +1442,12 @@ const FocusGroupSession = () => { // Handle editing state changes from DiscussionGuideViewer const handleGuideEditingStateChange = useCallback((editing: boolean) => { - console.log('๐Ÿ”„ handleGuideEditingStateChange called:', { - editing, - timestamp: new Date().toISOString(), - currentIsEditingGuideContent: isEditingGuideContent - }); - // Update both editing states setIsEditingDiscussionGuide(editing); // For scroll prevention setIsEditingGuideContent(editing); // For focus preservation // When editing ends, update the focus group state with the latest version if (!editing && focusGroupRef.current) { - console.log('๐Ÿ“ Updating focus group state after editing ended'); setFocusGroup(focusGroupRef.current); } }, [isEditingGuideContent]); @@ -1586,8 +1473,6 @@ const FocusGroupSession = () => { // Helper function to extract asset filename from creative review content const extractAssetFilename = (content: string): string | null => { - console.log('๐Ÿ” EXTRACT ASSET FILENAME DEBUG - Input content:', content); - // Look for patterns like "titled 'filename.jpg'" or similar const patterns = [ /'([^']*\.[a-zA-Z]{3,4})'/g, // 'filename.ext' @@ -1601,24 +1486,18 @@ const FocusGroupSession = () => { for (let i = 0; i < patterns.length; i++) { const pattern = patterns[i]; - console.log(`๐Ÿ” Testing pattern ${i + 1}:`, pattern.source); - const matches = Array.from(content.matchAll(pattern)); - console.log(`๐Ÿ” Pattern ${i + 1} matches:`, matches.length, matches); - + if (matches.length > 0) { // Get the first capture group from the first match const filename = matches[0][1]; - console.log(`๐Ÿ” Pattern ${i + 1} extracted filename:`, filename); - + if (filename && filename.includes('.')) { - console.log('โœ… EXTRACT ASSET FILENAME - Found:', filename); return filename; } } } - - console.warn('โŒ EXTRACT ASSET FILENAME - No filename found in content'); + return null; }; @@ -2161,34 +2040,13 @@ const FocusGroupSession = () => { const hasImageAttached = !!visualAsset?.filename; const assetFilename = visualAsset?.filename; - console.log('๐Ÿ” MANUAL POSITION DEBUG:', { - itemType: setPositionDialog.itemType, - hasImageAttached, - visualAsset, - assetFilename, - content: setPositionDialog.content, - sectionTitle: setPositionDialog.sectionTitle, - itemTitle: setPositionDialog.itemTitle, - contentLength: setPositionDialog.content?.length - }); - if (hasImageAttached && setPositionDialog.content && assetFilename) { - console.log('๐Ÿ” VISUAL ASSET DEBUG:', { - originalContent: setPositionDialog.content, - visualAsset, - displayReference: visualAsset?.display_reference, - filename: assetFilename, - contentLength: setPositionDialog.content.length - }); - if (assetFilename) { attachedAssets = [assetFilename]; activatesVisualContext = true; - console.log('๐ŸŽจ MANUAL POSITION: Creative review detected, will activate visual context for:', assetFilename); - + // Generate AI description and enhance the question try { - console.log('๐ŸŽจ MANUAL MODE: Requesting AI description for', assetFilename); const descriptionResponse = await focusGroupsApi.describeAsset(id, assetFilename); @@ -2200,9 +2058,6 @@ const FocusGroupSession = () => { `${displayRef} - ${descriptionResponse.data.description}` ); - console.log('โœ… MANUAL MODE: Enhanced question with AI description'); - console.log('๐Ÿ” Original:', setPositionDialog.content); - console.log('๐Ÿ” Enhanced:', enhancedMessageText); } } catch (descError) { @@ -2224,18 +2079,10 @@ const FocusGroupSession = () => { description: 'Using original question text. Image will still be available to participants.' }); } - } else { - console.warn('โš ๏ธ MANUAL POSITION: Creative review detected but no asset filename extracted from content'); } } // Send the moderator message to API - it will be added back via websocket/polling with server timestamp - console.log('๐Ÿ“ค Sending moderator message to API:', { - text: enhancedMessageText, - attachedAssets, - activatesVisualContext - }); - try { const msgResponse = await focusGroupsApi.sendMessage(id, { senderId: 'moderator', @@ -2249,7 +2096,6 @@ const FocusGroupSession = () => { } : undefined }); - console.log('โœ… Message API call successful:', msgResponse?.data); } catch (msgError) { console.error('โŒ Failed to save message to API:', msgError); toastService.warning('Message not saved', { @@ -2260,10 +2106,6 @@ const FocusGroupSession = () => { // Close dialog first for immediate feedback setSetPositionDialog({ isOpen: false }); - // Don't fetch moderator status immediately to avoid race condition - // The status will update via WebSocket or next polling cycle - console.log('โœ… Set position complete, moderator message added to UI'); - toastService.success('Moderator position set', { description: `Position set to "${setPositionDialog.itemTitle}" in "${setPositionDialog.sectionTitle}"` }); @@ -2310,7 +2152,6 @@ const FocusGroupSession = () => {