/** * Chat Screen - Text Chat with Julia AI * * Clean text chat interface. */ import React, { useState, useCallback, useRef, useEffect } from 'react'; import { View, Text, StyleSheet, FlatList, TextInput, TouchableOpacity, Modal, ActivityIndicator, Keyboard, Platform, Alert, } from 'react-native'; import { KeyboardAvoidingView } from 'react-native-keyboard-controller'; import { Ionicons } from '@expo/vector-icons'; import { SafeAreaView } from 'react-native-safe-area-context'; import { useRouter, useFocusEffect } from 'expo-router'; import { api } from '@/services/api'; import { useBeneficiary } from '@/contexts/BeneficiaryContext'; import { useVoiceTranscript } from '@/contexts/VoiceTranscriptContext'; import { useVoice } from '@/contexts/VoiceContext'; import { useChat } from '@/contexts/ChatContext'; import { useTextToSpeech } from '@/hooks/useTextToSpeech'; import { AppColors, BorderRadius, FontSizes, Spacing } from '@/constants/theme'; import type { Message, Beneficiary } from '@/types'; const API_URL = 'https://eluxnetworks.net/function/well-api/api'; // WellNuo API credentials (same as julia-agent) const WELLNUO_USER = 'anandk'; const WELLNUO_PASSWORD = 'anandk_8'; // ============================================================================ // SINGLE_DEPLOYMENT_MODE // When true: sends only deployment_id (no beneficiary_names_dict) // When false: sends both deployment_id AND beneficiary_names_dict // // Use true for WellNuo Lite (single beneficiary per user) // Use false for full WellNuo app (multiple beneficiaries) // ============================================================================ const SINGLE_DEPLOYMENT_MODE = true; // Keywords for question normalization (same as julia-agent/julia-ai/src/agent.py) const STATUS_KEYWORDS = [ /\bhow\s+is\b/i, /\bhow'?s\b/i, /\bhow\s+are\b/i, /\btell\s+me\s+about\b/i, /\bwhat'?s\s+up\s+with\b/i, /\bupdate\s+on\b/i, /\bstatus\b/i, /\bdoing\b/i, /\bfeeling\b/i, /\bcheck\s+on\b/i, /\bis\s+\w+\s+okay\b/i, /\bis\s+\w+\s+alright\b/i, /\bis\s+\w+\s+fine\b/i, /\bokay\?\b/i, /\balright\?\b/i, ]; const SUBJECT_KEYWORDS = [ /\bdad\b/i, /\bfather\b/i, /\bferdinand\b/i, /\bhim\b/i, /\bhe\b/i, /\bmy\s+dad\b/i, /\bmy\s+father\b/i, /\bthe\s+patient\b/i, /\bloved\s+one\b/i, /\bparent\b/i, /\bgrandpa\b/i, /\bgrandfather\b/i, ]; /** * Transform user questions into format WellNuo API understands. * WellNuo API only responds with real sensor data for very specific phrases. * This function maps common user questions to those phrases. * (Same logic as julia-agent/julia-ai/src/agent.py normalize_question) */ function normalizeQuestion(userMessage: string): string { const msgLower = userMessage.toLowerCase().trim(); const isStatusQuery = STATUS_KEYWORDS.some(pattern => pattern.test(msgLower)); const isAboutRecipient = SUBJECT_KEYWORDS.some(pattern => pattern.test(msgLower)); // If asking about the care recipient's general status if (isStatusQuery && isAboutRecipient) { console.log(`[Chat] Normalized '${userMessage}' -> 'how is dad doing'`); return 'how is dad doing'; } // Generic status questions without clear subject - assume they mean the care recipient if (isStatusQuery && !isAboutRecipient) { console.log(`[Chat] Normalized '${userMessage}' -> 'how is dad doing' (assumed recipient)`); return 'how is dad doing'; } // If no transformation needed, return original console.log(`[Chat] No normalization applied to: '${userMessage}'`); return userMessage; } export default function ChatScreen() { const router = useRouter(); const { currentBeneficiary, setCurrentBeneficiary } = useBeneficiary(); const { transcript, hasNewTranscript, markTranscriptAsShown, getTranscriptAsMessages } = useVoiceTranscript(); // Voice context for real-time transcript display and checking if voice session is active const { partialTranscript: voicePartial, isListening: voiceIsListening, status: voiceStatus, isActive: voiceIsActive } = useVoice(); // TTS for reading Julia's responses aloud const { speak, stop: stopTTS, isSpeaking } = useTextToSpeech({ language: 'ru-RU', rate: 1.0, }); // Helper to create initial message with beneficiary name const createInitialMessage = useCallback((beneficiaryName?: string | null): Message => ({ id: '1', role: 'assistant', content: `Hello! I'm Julia, your AI wellness companion.${beneficiaryName ? `\n\nI'm here to help you monitor ${beneficiaryName}.` : ''}\n\nType a message below to chat with me.`, timestamp: new Date(), }), []); // Custom deployment ID and name from settings const [customDeploymentId, setCustomDeploymentId] = useState(null); const [deploymentName, setDeploymentName] = useState(null); // Chat state - stored in context to persist across tab navigation const { messages, setMessages } = useChat(); const [sortNewestFirst, setSortNewestFirst] = useState(false); const [input, setInput] = useState(''); const [isSending, setIsSending] = useState(false); const inputRef = useRef(''); const flatListRef = useRef(null); // Keep inputRef in sync with input state useEffect(() => { inputRef.current = input; }, [input]); // Show partial voice transcript in input field in real-time useEffect(() => { if (voiceIsListening && voicePartial) { setInput(voicePartial); } }, [voicePartial, voiceIsListening]); // Track if current message was sent via voice (to decide whether to speak response) const lastMessageWasVoiceRef = useRef(false); // Clear input when voice switches to processing (transcript was sent) const prevVoiceStatusRef = useRef(voiceStatus); useEffect(() => { const prev = prevVoiceStatusRef.current; prevVoiceStatusRef.current = voiceStatus; if (prev === 'listening' && voiceStatus === 'processing') { setInput(''); // Mark that this message was sent via voice lastMessageWasVoiceRef.current = true; } }, [voiceStatus]); // Beneficiary picker const [showBeneficiaryPicker, setShowBeneficiaryPicker] = useState(false); const [beneficiaries, setBeneficiaries] = useState([]); const [loadingBeneficiaries, setLoadingBeneficiaries] = useState(false); // Load custom deployment ID and name from settings // Use useFocusEffect to reload when returning from profile screen useFocusEffect( useCallback(() => { const loadDeploymentData = async () => { const savedId = await api.getDeploymentId(); const savedName = await api.getDeploymentName(); console.log('[Chat] useFocusEffect: loaded deployment ID:', savedId, 'name:', savedName); setCustomDeploymentId(savedId); setDeploymentName(savedName); }; loadDeploymentData(); }, []) ); // When deployment ID changes BY USER ACTION, clear chat // Track previous value to detect actual changes (not just initial load) const previousDeploymentIdRef = useRef(undefined); // Track if we've done initial load (to distinguish from user changing deployment) const initialLoadDoneRef = useRef(false); useEffect(() => { // First render - just store the value, don't clear anything if (previousDeploymentIdRef.current === undefined) { console.log('[Chat] First render, storing deployment:', customDeploymentId); previousDeploymentIdRef.current = customDeploymentId; return; } // Initial async load completed (null → actual value) - don't clear chat! if (!initialLoadDoneRef.current && previousDeploymentIdRef.current === null && customDeploymentId) { console.log('[Chat] Initial deployment load complete:', customDeploymentId, '- NOT clearing chat'); previousDeploymentIdRef.current = customDeploymentId; initialLoadDoneRef.current = true; return; } // Mark initial load as done if (!initialLoadDoneRef.current && customDeploymentId) { initialLoadDoneRef.current = true; } // Only clear chat if deployment ACTUALLY changed by user (after initial load) if (initialLoadDoneRef.current && previousDeploymentIdRef.current !== customDeploymentId) { console.log('[Chat] Deployment CHANGED by user!', { old: previousDeploymentIdRef.current, new: customDeploymentId, name: deploymentName, }); // Clear chat with new initial message setMessages([createInitialMessage(deploymentName)]); previousDeploymentIdRef.current = customDeploymentId; } }, [customDeploymentId, deploymentName, createInitialMessage]); // Update initial message when deploymentName is loaded (but only if chat has just the initial message) useEffect(() => { if (deploymentName && messages.length === 1 && messages[0].id === '1') { setMessages([createInitialMessage(deploymentName)]); } }, [deploymentName, createInitialMessage]); // Add voice transcript messages to chat when new ones arrive useEffect(() => { if (hasNewTranscript && transcript.length > 0) { const voiceMessages = getTranscriptAsMessages(); if (voiceMessages.length > 0) { setMessages(prev => { // Filter out messages that are already in the chat (by id) const existingIds = new Set(prev.map(m => m.id)); const newMessages = voiceMessages.filter(m => !existingIds.has(m.id)); if (newMessages.length > 0) { console.log('[Chat] Adding', newMessages.length, 'voice messages to chat'); return [...prev, ...newMessages]; } return prev; }); } markTranscriptAsShown(); } }, [hasNewTranscript, transcript, getTranscriptAsMessages, markTranscriptAsShown]); // Load beneficiaries const loadBeneficiaries = useCallback(async () => { setLoadingBeneficiaries(true); try { const response = await api.getAllBeneficiaries(); if (response.ok && response.data) { setBeneficiaries(response.data); return response.data; } return []; } catch (error) { console.warn('Failed to load beneficiaries:', error); return []; } finally { setLoadingBeneficiaries(false); } }, []); // Auto-select first beneficiary useEffect(() => { const autoSelect = async () => { if (!currentBeneficiary) { const loaded = await loadBeneficiaries(); if (loaded.length > 0) { setCurrentBeneficiary(loaded[0]); } } }; autoSelect(); }, []); // Helper function to scroll to the latest message based on sort mode const scrollToLatestMessage = useCallback((animated = true) => { if (sortNewestFirst) { // When newest first, latest messages are at top (index 0) flatListRef.current?.scrollToOffset({ offset: 0, animated }); } else { // When oldest first, latest messages are at bottom flatListRef.current?.scrollToEnd({ animated }); } }, [sortNewestFirst]); // Scroll to latest when keyboard shows useEffect(() => { const keyboardShowListener = Keyboard.addListener( Platform.OS === 'ios' ? 'keyboardWillShow' : 'keyboardDidShow', () => { setTimeout(() => { scrollToLatestMessage(true); }, 100); } ); return () => keyboardShowListener.remove(); }, [scrollToLatestMessage]); const openBeneficiaryPicker = useCallback(() => { setShowBeneficiaryPicker(true); loadBeneficiaries(); }, [loadBeneficiaries]); const selectBeneficiary = useCallback((beneficiary: Beneficiary) => { setCurrentBeneficiary(beneficiary); setShowBeneficiaryPicker(false); }, [setCurrentBeneficiary]); // Cached API token for WellNuo const apiTokenRef = useRef(null); // Get WellNuo API token (same credentials as julia-agent) const getWellNuoToken = useCallback(async (): Promise => { if (apiTokenRef.current) { return apiTokenRef.current; } const nonce = Math.floor(Math.random() * 1000000).toString(); const response = await fetch(API_URL, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ function: 'credentials', clientId: 'MA_001', user_name: WELLNUO_USER, ps: WELLNUO_PASSWORD, nonce: nonce, }).toString(), }); const data = await response.json(); if (data.status === '200 OK' && data.access_token) { apiTokenRef.current = data.access_token; console.log('[Chat] WellNuo token obtained'); return data.access_token; } throw new Error('Failed to authenticate with WellNuo API'); }, []); // Text chat - send message via API (same as julia-agent) const sendTextMessage = useCallback(async () => { const trimmedInput = inputRef.current.trim(); if (!trimmedInput || isSending) return; const userMessage: Message = { id: Date.now().toString(), role: 'user', content: trimmedInput, timestamp: new Date(), }; // Clear input immediately before any async operations setInput(''); inputRef.current = ''; // This message was sent via text input (keyboard), not voice // Reset the flag so response won't be spoken lastMessageWasVoiceRef.current = false; setMessages(prev => [...prev, userMessage]); setIsSending(true); Keyboard.dismiss(); try { // Get WellNuo API token (uses anandk credentials like julia-agent) const token = await getWellNuoToken(); // Normalize question to format WellNuo API understands // (same logic as julia-agent/julia-ai/src/agent.py) const normalizedQuestion = normalizeQuestion(trimmedInput); // Build beneficiary_names_dict from all loaded beneficiaries // Format: {"21": "papa", "69": "David"} const beneficiaryNamesDict: Record = {}; beneficiaries.forEach(b => { beneficiaryNamesDict[b.id.toString()] = b.name; }); // Get deployment_id: custom from settings > current beneficiary > first beneficiary > fallback const deploymentId = customDeploymentId || currentBeneficiary?.id?.toString() || beneficiaries[0]?.id?.toString() || '21'; // Call API with EXACT same params as voice agent // SINGLE_DEPLOYMENT_MODE: sends only deployment_id (no beneficiary_names_dict) const requestParams: Record = { function: 'ask_wellnuo_ai', clientId: 'MA_001', user_name: WELLNUO_USER, token: token, question: normalizedQuestion, deployment_id: deploymentId, }; // Only add beneficiary_names_dict if NOT in single deployment mode if (!SINGLE_DEPLOYMENT_MODE) { requestParams.beneficiary_names_dict = JSON.stringify(beneficiaryNamesDict); } const response = await fetch(API_URL, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams(requestParams).toString(), }); const data = await response.json(); if (data.ok && data.response?.body) { const responseText = data.response.body; const assistantMessage: Message = { id: (Date.now() + 1).toString(), role: 'assistant', content: responseText, timestamp: new Date(), }; setMessages(prev => [...prev, assistantMessage]); // Only speak the response if: // 1. Voice session is active (FAB pressed) AND // 2. The user's message was sent via voice (not typed) // This way, typing a message while voice is active won't trigger TTS if (voiceIsActive && lastMessageWasVoiceRef.current) { speak(responseText); } } else { // Token might be expired, clear and retry once if (data.status === '401 Unauthorized') { apiTokenRef.current = null; throw new Error('Session expired, please try again'); } throw new Error('Could not get response'); } } catch (error) { const errorMessage: Message = { id: (Date.now() + 1).toString(), role: 'assistant', content: `Sorry, I encountered an error: ${error instanceof Error ? error.message : 'Unknown error'}`, timestamp: new Date(), }; setMessages(prev => [...prev, errorMessage]); } finally { setIsSending(false); } }, [isSending, getWellNuoToken, customDeploymentId, currentBeneficiary, beneficiaries, speak, voiceIsActive]); // Render message bubble const renderMessage = ({ item }: { item: Message }) => { const isUser = item.role === 'user'; const isVoice = item.isVoice; const isSystem = item.isSystem; // System messages if (isSystem) { return ( {item.content.replace(/---/g, '').trim()} ); } return ( {!isUser && ( J )} {item.content} {item.timestamp.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })} ); }; return ( {/* Header */} router.push('/(tabs)')}> J Julia AI {currentBeneficiary ? `About ${currentBeneficiary.name}` : 'Online'} setSortNewestFirst(prev => !prev)} > { stopTTS(); // Stop TTS when clearing chat Alert.alert( 'Clear Chat', 'Are you sure you want to clear all messages?', [ { text: 'Cancel', style: 'cancel' }, { text: 'Clear', style: 'destructive', onPress: () => { setMessages([ { id: '1', role: 'assistant', content: 'Hello! I\'m Julia, your AI wellness assistant. Type a message below to chat with me.', timestamp: new Date(), }, ]); }, }, ] ); }} > {/* Beneficiary Picker Modal */} setShowBeneficiaryPicker(false)} > Select Beneficiary setShowBeneficiaryPicker(false)}> {loadingBeneficiaries ? ( ) : beneficiaries.length === 0 ? ( No beneficiaries found ) : ( item.id.toString()} renderItem={({ item }) => ( selectBeneficiary(item)} > {item.name.split(' ').map(n => n[0]).join('').slice(0, 2)} {item.name} {currentBeneficiary?.id === item.id && ( )} )} style={styles.beneficiaryList} /> )} {/* Messages */} item.id} renderItem={renderMessage} contentContainerStyle={styles.messagesList} showsVerticalScrollIndicator={false} onContentSizeChange={() => { scrollToLatestMessage(true); }} /> {/* Typing indicator */} {isSending && ( Julia is typing... )} {/* Input */} ); } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: AppColors.surface, }, header: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingHorizontal: Spacing.md, paddingVertical: Spacing.sm, backgroundColor: AppColors.background, borderBottomWidth: 1, borderBottomColor: AppColors.border, }, backButton: { padding: Spacing.xs, marginRight: Spacing.sm, }, headerInfo: { flex: 1, flexDirection: 'row', alignItems: 'center', }, headerAvatar: { width: 40, height: 40, borderRadius: BorderRadius.full, backgroundColor: AppColors.success, justifyContent: 'center', alignItems: 'center', marginRight: Spacing.sm, }, headerAvatarText: { fontSize: FontSizes.lg, fontWeight: '600', color: AppColors.white, }, headerTitle: { fontSize: FontSizes.lg, fontWeight: '600', color: AppColors.textPrimary, }, headerSubtitle: { fontSize: FontSizes.sm, color: AppColors.success, }, headerButton: { padding: Spacing.xs, marginLeft: Spacing.sm, }, speakingButton: { backgroundColor: AppColors.primaryLight || '#E3F2FD', borderRadius: BorderRadius.full, }, chatContainer: { flex: 1, }, messagesList: { padding: Spacing.md, paddingBottom: Spacing.lg, }, messageContainer: { flexDirection: 'row', marginBottom: Spacing.md, alignItems: 'flex-end', }, userMessageContainer: { justifyContent: 'flex-end', }, assistantMessageContainer: { justifyContent: 'flex-start', }, avatarContainer: { width: 32, height: 32, borderRadius: BorderRadius.full, backgroundColor: AppColors.success, justifyContent: 'center', alignItems: 'center', marginRight: Spacing.xs, }, avatarText: { fontSize: FontSizes.sm, fontWeight: '600', color: AppColors.white, }, messageBubble: { maxWidth: '75%', padding: Spacing.sm + 4, borderRadius: BorderRadius.lg, }, userBubble: { backgroundColor: AppColors.primary, borderBottomRightRadius: BorderRadius.sm, }, assistantBubble: { backgroundColor: AppColors.background, borderBottomLeftRadius: BorderRadius.sm, }, messageText: { fontSize: FontSizes.base, lineHeight: 22, }, userMessageText: { color: AppColors.white, }, assistantMessageText: { color: AppColors.textPrimary, }, timestamp: { fontSize: FontSizes.xs, color: AppColors.textMuted, marginTop: Spacing.xs, alignSelf: 'flex-end', }, userTimestamp: { color: 'rgba(255,255,255,0.7)', }, inputContainer: { flexDirection: 'row', alignItems: 'flex-end', padding: Spacing.md, backgroundColor: AppColors.background, borderTopWidth: 1, borderTopColor: AppColors.border, }, input: { flex: 1, backgroundColor: AppColors.surface, borderRadius: BorderRadius.xl, paddingHorizontal: Spacing.md, paddingVertical: Spacing.sm, fontSize: FontSizes.base, color: AppColors.textPrimary, maxHeight: 100, marginRight: Spacing.sm, }, inputListening: { borderWidth: 1.5, borderColor: AppColors.error, }, sendButton: { width: 44, height: 44, borderRadius: BorderRadius.full, backgroundColor: AppColors.primary, justifyContent: 'center', alignItems: 'center', }, sendButtonDisabled: { backgroundColor: AppColors.surface, }, // Typing indicator typingIndicator: { flexDirection: 'row', alignItems: 'center', paddingHorizontal: Spacing.md, paddingVertical: Spacing.sm, gap: 8, }, typingDots: { flexDirection: 'row', alignItems: 'center', gap: 4, }, typingDot: { width: 8, height: 8, borderRadius: 4, backgroundColor: AppColors.primary, opacity: 0.4, }, typingDot1: { opacity: 0.4, }, typingDot2: { opacity: 0.6, }, typingDot3: { opacity: 0.8, }, typingText: { fontSize: 13, color: AppColors.textSecondary, fontStyle: 'italic', }, // Modal styles modalOverlay: { flex: 1, backgroundColor: 'rgba(0, 0, 0, 0.5)', justifyContent: 'flex-end', }, modalContent: { backgroundColor: AppColors.background, borderTopLeftRadius: BorderRadius.xl, borderTopRightRadius: BorderRadius.xl, maxHeight: '70%', paddingBottom: Spacing.xl, }, modalHeader: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', padding: Spacing.md, borderBottomWidth: 1, borderBottomColor: AppColors.border, }, modalTitle: { fontSize: FontSizes.lg, fontWeight: '600', color: AppColors.textPrimary, }, modalLoading: { padding: Spacing.xl, alignItems: 'center', }, modalEmpty: { padding: Spacing.xl, alignItems: 'center', }, emptyText: { fontSize: FontSizes.base, color: AppColors.textSecondary, }, beneficiaryList: { paddingHorizontal: Spacing.md, }, beneficiaryItem: { flexDirection: 'row', alignItems: 'center', padding: Spacing.md, backgroundColor: AppColors.surface, borderRadius: BorderRadius.md, marginTop: Spacing.sm, }, beneficiaryItemSelected: { backgroundColor: AppColors.primaryLight || '#E3F2FD', borderWidth: 1, borderColor: AppColors.primary, }, beneficiaryAvatar: { width: 44, height: 44, borderRadius: BorderRadius.full, backgroundColor: AppColors.primary, justifyContent: 'center', alignItems: 'center', marginRight: Spacing.md, }, beneficiaryAvatarText: { fontSize: FontSizes.base, fontWeight: '600', color: AppColors.white, }, beneficiaryInfo: { flex: 1, }, beneficiaryName: { fontSize: FontSizes.base, fontWeight: '500', color: AppColors.textPrimary, }, // System message styles systemMessageContainer: { flexDirection: 'row', alignItems: 'center', marginVertical: Spacing.md, paddingHorizontal: Spacing.md, }, systemMessageLine: { flex: 1, height: 1, backgroundColor: AppColors.border, }, systemMessageBadge: { flexDirection: 'row', alignItems: 'center', paddingHorizontal: Spacing.sm, paddingVertical: 4, backgroundColor: AppColors.surface, borderRadius: BorderRadius.sm, marginHorizontal: Spacing.sm, }, systemMessageText: { fontSize: FontSizes.xs, color: AppColors.textMuted, marginLeft: 4, }, });