async def click(state: AgentState):
    """Handles clicking elements with improved error handling and retry logic."""
    
    click_actions_taken = []
    page = state["page"]
    old_page = page.url
    click_action = state["actions"]["element_actions"]

    element_type = click_action["action_element"]["type"]
      
    xpath = click_action["action_element"]["xpath"]
    bbox_x = click_action["action_element"]["x"]
    bbox_y = click_action["action_element"]["y"]
    inViewport = click_action["action_element"]["inViewport"]

    if inViewport == False:
        # First attempt: Smooth scroll into view
        try:
            await page.evaluate(
                """
                (xpath) => {
                    const result = document.evaluate(
                        xpath, 
                        document, 
                        null, 
                        XPathResult.FIRST_ORDERED_NODE_TYPE, 
                        null
                    );
                    const element = result.singleNodeValue;
                    if (element) {
                        element.scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'nearest' });
                        return true;
                    }
                    return false;
                }
                """,
                xpath
            )
            await asyncio.sleep(1)  # Allow smooth scroll to complete
        except Exception:
            # If smooth scroll fails, try instant scroll
            try:
                await page.evaluate(
                    """
                    (x, y) => {
                        window.scrollTo({
                            top: y - (window.innerHeight / 2),
                            behavior: 'instant'
                        });
                    }
                    """,
                    bbox_x, bbox_y
                )
                await asyncio.sleep(0.5)
            except Exception:
                return {"actions_taken": [f"Failed to scroll to element: {str(e)}"]}

    
    success = False
    attempts = 0
    max_attempts = 3

    while not success and attempts < max_attempts:
        attempts += 1
        try:
            if "link" in element_type:
                # Handle links with existing logic
                async with page.context.expect_page(timeout=10000) as new_page_info:
                    if platform.system() == "Darwin":
                        await page.locator(f'xpath={xpath}').click(
                            modifiers=["Meta"],
                            timeout=5000,
                            force=attempts == max_attempts  # Force click on last attempt
                        )
                    else:
                        await page.locator(f'xpath={xpath}').click(
                            modifiers=["Control"],
                            timeout=5000,
                            force=attempts == max_attempts
                        )
                    
                    new_page = await new_page_info.value
                    await asyncio.sleep(3)
                    await new_page.bring_to_front()
                    state["page"] = new_page
                    success = True
            else:
                # Enhanced button/element clicking
                try:
                    # Try precise click first
                    await page.locator(f'xpath={xpath}').click(
                        timeout=5000,
                        delay=100,  # Add slight delay for stability
                        force=attempts == max_attempts
                    )
                    success = True
                except Exception as e:
                    # If precise click fails, try coordinate click
                    if attempts == max_attempts - 1:
                        # On penultimate attempt, try clicking with JavaScript
                        await page.evaluate(
                            """
                            (xpath) => {
                                const element = document.evaluate(
                                    xpath,
                                    document,
                                    null,
                                    XPathResult.FIRST_ORDERED_NODE_TYPE,
                                    null
                                ).singleNodeValue;
                                if (element) {
                                    element.click();
                                    return true;
                                }
                                return false;
                            }
                            """,
                            xpath
                        )
                        await asyncio.sleep(1)
                    else:
                        # Try coordinate-based click
                        await page.mouse.click(
                            bbox_x,
                            bbox_y,
                            delay=100,
                            force=attempts == max_attempts
                        )
                    
                    # Wait briefly to check if click had an effect
                    await asyncio.sleep(1)
                    
                    # Check if page changed or any visible effect occurred
                    if page.url != old_page:
                        success = True
                    else:
                        # Additional check for button effect (e.g., style changes)
                        changed = await page.evaluate(
                            """
                            (xpath) => {
                                const element = document.evaluate(
                                    xpath,
                                    document,
                                    null,
                                    XPathResult.FIRST_ORDERED_NODE_TYPE,
                                    null
                                ).singleNodeValue;
                                return element && (
                                    element.matches(':active') ||
                                    element.matches(':focus') ||
                                    element.getAttribute('aria-expanded') === 'true'
                                );
                            }
                            """,
                            xpath
                        )
                        if changed:
                            success = True

        except Exception as e:
            if attempts == max_attempts:
                click_actions_taken.append(f"Failed to click {element_type} after {max_attempts} attempts")
                continue
            await asyncio.sleep(1)  # Brief pause before retry

        element_description = (
            f"{click_action['action_element']['text']} {click_action['action_element']['type']}"
        )
        if success:
            click_actions_taken.append(f"Successfully clicked {element_description}")
        
        # Check if we need to break the loop (page changed)
        if page.url != old_page:
            break

    # Return appropriate status
    if old_page == state["page"].url:
        return {"actions_taken": click_actions_taken, "new_page": False}
    else:
        return {"actions_taken": click_actions_taken, "new_page": True}
Handles clicking elements with improved error handling and retry logic.
backend/app/task_agent.py