from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException, NoSuchElementException import time import os import sys # Import from utils module instead of test_ai_coach from utils import save_screenshot class AICoachPage: """Page Object Model for the AI Coach page.""" # URL URL_PATH = "/ai-coach" # Locators CHAT_CONTAINER = (By.CSS_SELECTOR, ".flex.flex-col.flex-1") CHAT_INPUT = (By.CSS_SELECTOR, "input[placeholder='Type your response...']") SEND_BUTTON = (By.CSS_SELECTOR, "button[type='submit']") CHAT_MESSAGES = (By.CSS_SELECTOR, "div.whitespace-pre-line") ASSISTANT_MESSAGES = (By.CSS_SELECTOR, "div.flex div.whitespace-pre-line") USER_MESSAGES = (By.CSS_SELECTOR, "div.text-white") CHOICE_BUTTONS = (By.CSS_SELECTOR, "div.flex.flex-wrap button") GENERATE_ROADMAP_BUTTON = (By.XPATH, "//button[contains(text(), 'Generate') and contains(@class, 'w-full')]") LOADING_SCREEN = (By.CSS_SELECTOR, "div.fixed") BRAIN_ICON = (By.CSS_SELECTOR, "svg") LOADING_INDICATOR = (By.CSS_SELECTOR, ".animate-spin") LOADING_PROGRESS = (By.CSS_SELECTOR, "p.text-white") ROADMAP_HEADING = (By.XPATH, "//h1[contains(text(), 'AI Roadmap') or contains(text(), 'Your Roadmap')]") def __init__(self, driver, base_url): """Initialize with WebDriver instance and base URL.""" self.driver = driver self.base_url = base_url self.wait = WebDriverWait(driver, 10) def open(self): """Navigate to the AI Coach page.""" self.driver.get(f"{self.base_url}{self.URL_PATH}") return self def is_loaded(self): """Check if the page is loaded by verifying initial message is displayed.""" try: # Reduce standard wait to 5 seconds for initial page load WebDriverWait(self.driver, 5).until(EC.presence_of_element_located(self.ASSISTANT_MESSAGES)) return True except TimeoutException: return False def send_message(self, message): """Type and send a message in the chat input.""" try: # Wait for input field to be visible and clickable with reduced timeout input_field = WebDriverWait(self.driver, 10).until( EC.element_to_be_clickable(self.CHAT_INPUT) ) # Clear any existing text and type the message input_field.clear() input_field.send_keys(message) # Find and click send button send_button = WebDriverWait(self.driver, 5).until( EC.element_to_be_clickable(self.SEND_BUTTON) ) send_button.click() return True except Exception as e: print(f"Error sending message: {e}") return False def get_latest_assistant_message(self): """Get the latest message from the assistant.""" try: # Wait for assistant response with a shorter timeout WebDriverWait(self.driver, 3).until(lambda d: len(d.find_elements(*self.ASSISTANT_MESSAGES)) > 0) # Get all assistant messages messages = self.driver.find_elements(*self.ASSISTANT_MESSAGES) if messages: # Return the text of the latest message return messages[-1].text return None except (TimeoutException, NoSuchElementException): return None def click_choice(self, choice_text): """ Click a multiple choice button with the given text. Will try to find a button that contains the specified text (case-insensitive, partial match). """ try: # Wait for choices to be displayed with a reduced timeout WebDriverWait(self.driver, 10).until(EC.presence_of_element_located(self.CHOICE_BUTTONS)) # Special handling for budget selection which often causes issues if "$" in choice_text or "budget" in choice_text.lower(): print("Special handling for budget selection") # Try specific XPath for budget buttons budget_xpath = "//button[contains(text(), '$') or contains(text(), 'budget') or contains(text(), 'Budget')]" budget_buttons = self.driver.find_elements(By.XPATH, budget_xpath) if budget_buttons: # Log all budget buttons found button_texts = [btn.text.strip() for btn in budget_buttons if btn.text.strip()] print(f"Budget buttons found: {button_texts}") # Find the best matching button for the user's choice selected_button = None # First try exact match for button in budget_buttons: if button.text.strip().lower() == choice_text.lower(): selected_button = button print(f"Found exact match for budget: '{button.text.strip()}'") break # If no exact match, try partial match with $ amount if not selected_button and "$50" in choice_text: for button in budget_buttons: if "$50" in button.text: selected_button = button print(f"Found partial match for $50 budget: '{button.text.strip()}'") break # If still no match, try any button that contains the word "budget" if not selected_button: for button in budget_buttons: if "$" in button.text: selected_button = button print(f"Found budget button with $ sign: '{button.text.strip()}'") break # If we found a button, click it if selected_button: # Scroll the button into view first self.driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", selected_button) time.sleep(1) # Give time for scrolling to complete # Take screenshot before clicking save_screenshot(self.driver, "before_budget_click.png") # Click using JavaScript self.driver.execute_script("arguments[0].click();", selected_button) print(f"Clicked budget button: '{selected_button.text.strip()}'") # Take screenshot after clicking time.sleep(1) save_screenshot(self.driver, "after_budget_click.png") return True # Find all choice buttons (standard approach if not budget) choices = self.driver.find_elements(*self.CHOICE_BUTTONS) # Print available choices for debugging choice_texts = [btn.text.strip() for btn in choices] print(f"Available choices: {choice_texts}") # First try exact match for button in choices: button_text = button.text.strip() if button_text.lower() == choice_text.lower(): print(f"Found exact match button: '{button_text}'") # Scroll the button into view first self.driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", button) time.sleep(0.5) # Give time for scrolling # Click using JavaScript self.driver.execute_script("arguments[0].click();", button) print(f"Clicked button: '{button_text}'") time.sleep(0.5) # Give time for UI to update return True # If no exact match, try partial match for button in choices: button_text = button.text.strip() if choice_text.lower() in button_text.lower() or button_text.lower() in choice_text.lower(): print(f"Found partial match button: '{button_text}'") # Scroll the button into view first self.driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", button) time.sleep(0.5) # Give time for scrolling # Click using JavaScript self.driver.execute_script("arguments[0].click();", button) print(f"Clicked button: '{button_text}'") time.sleep(0.5) # Give time for UI to update return True # If still no match but buttons exist, try to find a button containing key terms if choices: # Terms to look for in buttons based on the user's input key_terms = [] if "$" in choice_text: key_terms.append("$") if "beginner" in choice_text.lower(): key_terms.append("beginner") if "hour" in choice_text.lower(): key_terms.append("hour") # Check for buttons containing key terms for term in key_terms: for button in choices: button_text = button.text.strip() if term.lower() in button_text.lower(): print(f"Found button matching term '{term}': '{button_text}'") # Scroll the button into view first self.driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", button) time.sleep(0.5) # Give time for scrolling # Click using JavaScript self.driver.execute_script("arguments[0].click();", button) print(f"Clicked button: '{button_text}'") time.sleep(0.5) # Give time for UI to update return True # Last resort: click the first button as fallback button = choices[0] button_text = button.text.strip() print(f"No match found, clicking first button as fallback: '{button_text}'") # Scroll the button into view first self.driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", button) time.sleep(0.5) # Give time for scrolling # Click using JavaScript self.driver.execute_script("arguments[0].click();", button) print(f"Clicked button: '{button_text}'") time.sleep(0.5) # Give time for UI to update return True print(f"No buttons found that match: '{choice_text}'") return False # No buttons found except Exception as e: print(f"Error clicking choice: {e}") import traceback traceback.print_exc() save_screenshot(self.driver, "error_clicking_choice.png") return False def generate_roadmap(self): """Click the Generate Roadmap button.""" try: print("Looking for the Generate Roadmap button...") # Scroll to bottom of page self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") # Try direct xpath first for better matching generate_button_xpath = "//button[contains(text(), 'Generate') and contains(text(), 'Roadmap')]" buttons = self.driver.find_elements(By.XPATH, generate_button_xpath) if buttons: print(f"Found Generate Roadmap button via XPath ({len(buttons)} matches)") # Ensure button is in view self.driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", buttons[0]) # Click the first matching button self.driver.execute_script("arguments[0].click();", buttons[0]) print("Clicked Generate Roadmap button via XPath") return True # Try our class-based selector if the text-based selector fails button = None try: # Try the specific button with our defined selector button = WebDriverWait(self.driver, 5).until( EC.element_to_be_clickable(self.GENERATE_ROADMAP_BUTTON) ) print("Found button with Generate Roadmap class selector") except (TimeoutException, NoSuchElementException): # Fallback to finding any button that appears to be a submit/action button print("Specific button not found, looking for any action button...") buttons = self.driver.find_elements(By.CSS_SELECTOR, "button.w-full, button.bg-primary, button.bg-purple-600") if buttons: print(f"Found {len(buttons)} potential action buttons") # Use the last one, as it's likely the generate button at the end of the chat button = buttons[-1] # Print button text for debugging button_text = button.text.strip() print(f"Using button with text: '{button_text}'") # Ensure it's clickable self.driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", button) else: print("No potential action buttons found") return False # Scroll to the button to ensure it's in view self.driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", button) # Click using JavaScript for reliability self.driver.execute_script("arguments[0].click();", button) print("Generate Roadmap button clicked") # Wait for loading screen to appear with short timeout try: WebDriverWait(self.driver, 3).until(EC.presence_of_element_located(self.LOADING_SCREEN)) print("Loading screen appeared") return True except (TimeoutException, NoSuchElementException): print("Loading screen did not appear, but button was clicked") # Return true anyway, as the button was clicked return True except Exception as e: print(f"Error generating roadmap: {e}") import traceback traceback.print_exc() return False def wait_for_loading_complete(self, timeout=60): """Wait for the loading screen to complete and verify roadmap is displayed.""" try: start_time = time.time() print("Waiting for loading to start and complete...") # Check if we're already on the roadmap page try: if self.driver.find_elements(*self.ROADMAP_HEADING): print("Roadmap already loaded, no loading indicator detected") return True except: pass # Wait for loading screen or indicator to appear try: # Try to find either the loading screen or the loading indicator with short timeout WebDriverWait(self.driver, 5).until( lambda d: d.find_elements(*self.LOADING_SCREEN) or d.find_elements(*self.LOADING_INDICATOR) ) print("Loading started") # Take a screenshot of the loading screen save_screenshot(self.driver, "loading_screen_animated.png") print("Screenshot taken of the loading animation") except: print("No loading screen or indicator found - checking if roadmap is already visible") # If neither loading screen nor indicator is found, check again for roadmap try: WebDriverWait(self.driver, 2).until( EC.visibility_of_element_located(self.ROADMAP_HEADING) ) print("Roadmap already loaded, no loading detected") return True except: print("Neither loading elements nor roadmap heading found") # Wait for loading screen and loading indicator to disappear # Use polling to check status periodically rather than waiting the full timeout poll_interval = 2 # Check every 2 seconds poll_count = int(timeout / poll_interval) for i in range(poll_count): if not self.driver.find_elements(*self.LOADING_SCREEN) and not self.driver.find_elements(*self.LOADING_INDICATOR): print(f"Loading elements disappeared after {i * poll_interval} seconds") break # Check if progress has reached 100% (if progress element exists) try: progress_element = self.driver.find_element(*self.LOADING_PROGRESS) progress_text = progress_element.text if progress_element else "" if any(text in progress_text for text in ["100%", "Complete", "Done"]): print(f"Progress reached 100% after {i * poll_interval} seconds") break # Take a mid-loading screenshot to capture progress indicators # Only take one screenshot during the middle of loading (around 40-60% complete) if progress_text and any(text in progress_text for text in ["40%", "50%", "60%"]): save_screenshot(self.driver, "loading_screen_progress.png") print(f"Screenshot taken of loading progress: {progress_text}") except: pass # Check if URL changed to roadmap URL if "/roadmap" in self.driver.current_url: print(f"URL changed to roadmap after {i * poll_interval} seconds") return True time.sleep(poll_interval) # Check for roadmap elements roadmap_candidates = [ # Original roadmap heading selector self.ROADMAP_HEADING, # Alternative selectors that might indicate the roadmap is present (By.XPATH, "//h1[contains(text(), 'Roadmap')]"), (By.XPATH, "//div[contains(@class, 'roadmap')]"), (By.XPATH, "//section[contains(@class, 'roadmap')]"), (By.CSS_SELECTOR, ".roadmap-container"), (By.CSS_SELECTOR, ".roadmap-section"), # Any heading containing roadmap (By.XPATH, "//*[self::h1 or self::h2 or self::h3][contains(text(), 'roadmap') or contains(text(), 'Roadmap')]") ] # Check URL first if "/roadmap" in self.driver.current_url: print(f"URL contains '/roadmap', assuming roadmap generated successfully: {self.driver.current_url}") return True # Try all selectors found_selector = None for selector in roadmap_candidates: try: elements = self.driver.find_elements(*selector) if elements: found_selector = selector print(f"Found roadmap indicator with selector: {selector}") break except: continue if found_selector: end_time = time.time() print(f"Roadmap found after {end_time - start_time:.2f} seconds - roadmap generation successful!") return True # Final fallback - check page content try: body_text = self.driver.find_element(By.TAG_NAME, "body").text.lower() if "roadmap" in body_text: print("Found 'roadmap' in page content, assuming roadmap was generated") return True except: pass print("Could not find any roadmap indicators") return False except Exception as e: print(f"Error waiting for loading to complete: {e}") import traceback traceback.print_exc() return False def get_all_messages(self): """Get all messages in the chat (both user and assistant).""" messages = self.driver.find_elements(*self.CHAT_CONTAINER) return [msg.text for msg in messages] def has_multiple_choice_buttons(self): """Check if multiple choice buttons are currently displayed.""" try: # First try with our defined selector choices = self.driver.find_elements(*self.CHOICE_BUTTONS) if choices and len(choices) > 0: return True # If no buttons found with the default selector, try alternative selectors # Try any buttons that might be part of a multiple choice UI alt_choices = self.driver.find_elements(By.CSS_SELECTOR, "button.bg-blue-gradient, button.bg-primary, button.rounded-lg") if alt_choices and len(alt_choices) > 0: # Check if these are likely choice buttons (not just random buttons) visible_buttons = [btn for btn in alt_choices if btn.is_displayed()] if len(visible_buttons) >= 2: # Multiple choice usually has at least 2 options print(f"Found {len(visible_buttons)} potential choice buttons with alternative selector") return True # Special handling for budget buttons which sometimes have different classes budget_buttons = self.driver.find_elements(By.XPATH, "//button[contains(text(), '$')]") if budget_buttons and len(budget_buttons) > 0: print(f"Found {len(budget_buttons)} budget buttons") return True return False except (TimeoutException, NoSuchElementException): return False def send_response(self, message, fast_mode=True): """ Send a response to the AI, either by clicking a choice button or typing a message. This is a smart method that detects if multiple choice buttons are available. Args: message: Text to send or button text to click fast_mode: If True, use faster testing mode with minimal waits and screenshots Returns: bool: True if message was sent successfully """ # First check if multiple choice buttons are present print("Checking for multiple choice buttons...") # Take a screenshot only in debug mode if not fast_mode: save_screenshot(self.driver, "ui_state_before_response.png") if self.has_multiple_choice_buttons(): print(f"Multiple choice buttons found, trying to click '{message}'") return self.click_choice(message) else: print(f"No multiple choice buttons found, sending text message: '{message}'") return self.send_message(message)