Spaces:
Runtime error

File size: 9,507 Bytes
ed86a97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
"""
Test Engine using Async Browser Controller.
This solves thread-safety issues.
"""

import asyncio
import json
import random
from datetime import datetime
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional

from rich.console import Console
from rich.panel import Panel

from ..models import ActionType, Bot, Persona, Scenario, TestResult, TestSession
from ..utils.env import env_int
from .ai_client import AIClient
from .browser_controller_async import BrowserControllerAsync
from .rag_evaluator import RAGEvaluator
from .tone_evaluator import ToneEvaluator

console = Console()


class TestEngineAsync:
    """Async test engine - solves thread issues with Playwright."""
    
    def __init__(
        self,
        ai_client: AIClient,
        rag_evaluator: RAGEvaluator,
        tone_evaluator: ToneEvaluator,
        output_dir: str = "./output",
        event_handler: Optional[Callable[[Dict[str, Any]], None]] = None,
        stop_requested: Optional[Callable[[], bool]] = None,
    ):
        self.ai_client = ai_client
        self.rag_eval = rag_evaluator
        self.tone_eval = tone_evaluator
        self.output_dir = Path(output_dir)
        self.output_dir.mkdir(parents=True, exist_ok=True)
        self.event_handler = event_handler
        self.stop_requested = stop_requested
        
        self.browser: Optional[BrowserControllerAsync] = None
        self.current_session: Optional[TestSession] = None
        self.conversation_log: List[Dict[str, Any]] = []
    
    def _emit(self, event: Dict[str, Any]) -> None:
        if self.event_handler:
            self.event_handler(event)
    
    def _is_stop_requested(self) -> bool:
        if not self.stop_requested:
            return False
        try:
            return bool(self.stop_requested())
        except Exception:
            return False

    async def run_multi_scenario_test(
        self,
        bot: Bot,
        scenarios: List[Scenario],
        persona: Persona,
        session: TestSession,
        headless: bool = False,
    ) -> TestResult:
        """Run multiple scenarios in a single continuous conversation."""
        self.current_session = session
        self.conversation_log = []
        
        result = TestResult(
            workspace_id=getattr(session, "workspace_id", None),
            session_id=session.id,
            scenario_id=session.id,
            persona_id=persona.id,
            status="pending",
            started_at=datetime.now(),
        )
        
        console.print(Panel.fit(
            f"[bold blue]Async Multi-Scenario Test[/bold blue]\n"
            f"Bot: {bot.name} | Persona: {persona.name}\n"
            f"Scenarios: {len(scenarios)}",
            title="AI Test Engine Async"
        ))
        
        try:
            # Initialize browser
            self.browser = BrowserControllerAsync(
                selectors=bot.selectors.model_dump(),
                output_dir=str(self.output_dir),
                headless=headless,
            )
            
            if not await self.browser.start(str(bot.url)):
                result.status = "error"
                result.error_message = "Failed to start browser"
                return result
            
            # Click "New Chat" if configured
            if bot.auto_click_new_chat:
                # Try to find and click new chat button
                pass
            
            # Execute all scenarios
            all_steps = []
            for scenario in scenarios:
                steps = scenario.steps if scenario.steps else []
                if not steps:
                    steps = self._auto_generate_steps(scenario)
                all_steps.extend(steps)
            
            # Execute each step
            for step_idx, step in enumerate(all_steps):
                if self._is_stop_requested():
                    result.status = "stopped"
                    break
                
                console.print(f"\n[bold]Step {step_idx + 1}/{len(all_steps)}:[/bold] {step.step_id}")
                
                success = await self._execute_turn(bot, persona, step)
                if not success:
                    console.print(f"[yellow]Step {step.step_id} failed[/yellow]")
                
                await asyncio.sleep(random.uniform(1.5, 3.0))
            
            # Finalize
            result.status = "completed"
            result.completed_at = datetime.now()
            result.conversation_log = json.dumps(self.conversation_log, ensure_ascii=False)
            
        except Exception as e:
            console.print(f"[red]Test error: {e}[/red]")
            result.status = "error"
            result.error_message = str(e)
            result.completed_at = datetime.now()
        
        finally:
            if self.browser:
                await self.browser.capture_screenshot("final")
                await self.browser.cleanup()
                self.browser = None
        
        return result

    async def _execute_turn(self, bot: Bot, persona: Persona, step) -> bool:
        """Execute a single conversation turn."""
        try:
            # Get context
            messages = await self.browser.get_chat_messages()
            if messages:
                last_bot = [m for m in messages if m.get("sender") == "bot"]
                if last_bot:
                    last_bot[-1].get("text", "")
            
            # Build conversation history
            history_text = ""
            if self.conversation_log:
                for entry in self.conversation_log[-5:]:
                    history_text += f"User: {entry.get('user_message', '')}\n"
                    history_text += f"Bot: {entry.get('bot_response', '')}\n\n"
            
            # AI decides action
            _system_prompt = f"""You are {persona.name}, a real human user.
Mood: {persona.mood or 'neutral'}
Language: {persona.language or 'italian'}

RULES:
1. Keep messages SHORT (3-10 words)
2. Reply naturally to what the bot says
3. NEVER generate long explanations

Respond with JSON: {{"content": "your message"}}"""

            # For now, use simple logic
            action_content = step.content or "Hello"
            
            console.print(f"[dim]Sending: {action_content[:50]}...[/dim]")
            
            # Send message
            success = await self.browser.send_message(action_content)
            if not success:
                return False
            
            self._emit({
                "type": "chat",
                "sender": "user",
                "text": action_content,
            })
            
            # Wait for response
            if step.wait_for_response:
                console.print("[dim]Waiting for bot response...[/dim]")
                
                bot_response = await self.browser.wait_for_bot_response(
                    timeout=env_int("RESPONSE_TIMEOUT", 60),
                    stop_requested=self._is_stop_requested,
                )
                
                if bot_response:
                    console.print(Panel(
                        bot_response[:200] + "..." if len(bot_response) > 200 else bot_response,
                        title="Bot Response", border_style="green"
                    ))
                    
                    self._emit({
                        "type": "chat",
                        "sender": "bot",
                        "text": bot_response,
                    })
                    
                    # Log conversation
                    self.conversation_log.append({
                        "turn": len(self.conversation_log) + 1,
                        "user_message": action_content,
                        "bot_response": bot_response,
                        "timestamp": datetime.now().isoformat(),
                    })
                    
                    return True
                else:
                    console.print("[yellow]No bot response received[/yellow]")
                    return False
            
            return True
            
        except Exception as e:
            console.print(f"[red]Turn error: {e}[/red]")
            return False
    
    def _auto_generate_steps(self, scenario: Scenario) -> List[Any]:
        """Auto-generate steps."""
        from ..models import Step
        return [
            Step(
                step_id=f"{scenario.id}_1",
                action_type=ActionType.SEND_MESSAGE,
                content=f"Hi, I need help with {scenario.name}",
                wait_for_response=True,
            ),
        ]


async def run_test_async(
    bot: Bot,
    scenarios: List[Scenario],
    persona: Persona,
    session: TestSession,
    ai_client: AIClient,
    rag_evaluator: RAGEvaluator,
    tone_evaluator: ToneEvaluator,
    output_dir: str = "./output",
    headless: bool = False,
    event_handler: Optional[Callable] = None,
    stop_requested: Optional[Callable] = None,
) -> TestResult:
    """Convenience function to run a test."""
    engine = TestEngineAsync(
        ai_client=ai_client,
        rag_evaluator=rag_evaluator,
        tone_evaluator=tone_evaluator,
        output_dir=output_dir,
        event_handler=event_handler,
        stop_requested=stop_requested,
    )
    
    return await engine.run_multi_scenario_test(
        bot=bot,
        scenarios=scenarios,
        persona=persona,
        session=session,
        headless=headless,
    )