-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathevaluate_browser_agent.py
More file actions
3344 lines (2927 loc) · 128 KB
/
evaluate_browser_agent.py
File metadata and controls
3344 lines (2927 loc) · 128 KB
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
OpenBrowser Agent Evaluation System
Evaluates AI agents on browser automation tasks using the OpenBrowser server.
Records SSE events (including images) and browser tracking events for analysis.
"""
import argparse
import atexit
import base64
import datetime
import fcntl
import json
import logging
import os
import shutil
import signal
import sqlite3
import sys
import threading
import time
from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
from contextlib import AbstractContextManager
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
from urllib.parse import urlparse
import requests
import yaml
from requests.exceptions import (
ChunkedEncodingError,
ConnectionError as RequestsConnectionError,
ReadTimeout,
)
from urllib3.exceptions import ProtocolError
logger = logging.getLogger(__name__)
# Configuration
OPENBROWSER_API_URL = "http://localhost:8765"
OPENBROWSER_WS_URL = "ws://localhost:8766"
EVAL_SERVER_URL = "http://localhost:16605"
EVAL_SERVER_PORT = 16605
OPENBROWSER_PORT = 8765
# SSE streaming timeouts for the agent channel at :8765.
# (connect_timeout, read_timeout) in seconds.
# The read timeout applies per-chunk: we need it longer than the slowest LLM
# turn so a slow turn doesn't abort mid-stream. The test-level wall-clock is
# still enforced by the outer thread-join in send_message.
# Override with OPENBROWSER_SSE_READ_TIMEOUT (seconds).
SSE_CONNECT_TIMEOUT = 30
SSE_READ_TIMEOUT = int(os.environ.get("OPENBROWSER_SSE_READ_TIMEOUT", "600"))
# API-stall detection & retry. After a test times out, we scan its SSE
# events for observation→action gaps exceeding this threshold. If found,
# the test is re-queued (up to API_STALL_MAX_RETRIES times).
API_STALL_THRESHOLD = float(os.environ.get("OPENBROWSER_API_STALL_THRESHOLD", "60"))
API_STALL_MAX_RETRIES = int(os.environ.get("OPENBROWSER_API_STALL_MAX_RETRIES", "3"))
# Paths
EVAL_DIR = Path(__file__).parent
DATASET_DIR = EVAL_DIR / "dataset"
OUTPUT_BASE_DIR = EVAL_DIR / "output"
LOCK_DIR = EVAL_DIR / ".locks"
# Ensure base directory exists
OUTPUT_BASE_DIR.mkdir(exist_ok=True)
DATASET_DIR.mkdir(exist_ok=True)
LOCK_DIR.mkdir(exist_ok=True)
DEFAULT_SESSION_DB_PATH = Path.home() / ".openbrowser" / "sessions.db"
def detect_api_stalls(
sse_events: List[Dict[str, Any]],
threshold: float = API_STALL_THRESHOLD,
) -> List[float]:
"""Scan SSE events for observation→action gaps that exceed *threshold*.
Returns a list of gap durations (seconds) where the model API took
unreasonably long to respond. An empty list means no stalls detected.
Also detects the "trailing stall" case: the test timed out while
waiting for an API response after the last observation, so no
completed pair exists. We approximate this by checking if the last
event is an ObservationEvent and the gap to the final timestamp in
the stream exceeds the threshold.
"""
# Build ordered list of (timestamp, kind) for action/observation events.
pairs: list[tuple[float, str]] = []
last_ts_overall: float = 0.0
for ev in sse_events:
ts = ev.get("timestamp")
if ts:
last_ts_overall = max(last_ts_overall, float(ts))
data = ev.get("data")
if not isinstance(data, dict):
continue
ev_type = data.get("type", "")
if not ts or ev_type not in ("ActionEvent", "ObservationEvent"):
continue
pairs.append((float(ts), ev_type))
pairs.sort(key=lambda p: p[0])
stalls: list[float] = []
for i in range(1, len(pairs)):
prev_ts, prev_kind = pairs[i - 1]
curr_ts, curr_kind = pairs[i]
if prev_kind == "ObservationEvent" and curr_kind == "ActionEvent":
gap = curr_ts - prev_ts
if gap >= threshold:
stalls.append(gap)
# Trailing stall: last event is an observation and a long time passed
# before the stream ended (test was killed waiting for model response).
if pairs and pairs[-1][1] == "ObservationEvent" and last_ts_overall:
trailing_gap = last_ts_overall - pairs[-1][0]
if trailing_gap >= threshold:
stalls.append(trailing_gap)
return stalls
@dataclass
class TestCase:
"""A test case definition"""
id: str
name: str
description: str
instruction: str
start_url: str
criteria: List[Dict[str, Any]]
difficulty: str = "medium"
time_limit: float = 600.0 # default 10 minutes in seconds
cost_limit: float = 1.0 # default 1 RMB
# Path to a Browser Routine markdown file relative to the repo root.
# When set, the test runs in routine_replay mode: the conversation is
# created with mode="routine_replay" and the routine markdown is sent
# as the message instead of `instruction`. Tracker-based scoring still
# applies, so the same `criteria` block grades the replayed run.
routine_file: Optional[str] = None
@dataclass
class TestResult:
"""Test execution result"""
test_case: TestCase
passed: bool
score: float
max_score: float
events: List[Dict[str, Any]]
sse_events: List[Dict[str, Any]]
track_events: List[Dict[str, Any]]
images: List[str] # image file paths
error: Optional[str] = None
conversation_id: Optional[str] = None
start_time: Optional[float] = None
end_time: Optional[float] = None
duration: Optional[float] = None
cost: Optional[float] = None # cost in RMB
efficiency_score: Optional[float] = None # score based on time efficiency (0-1)
usage_score: Optional[float] = None # score based on cost efficiency (0-1)
total_score: Optional[float] = None # combined score (task + efficiency + usage)
sse_events_file: Optional[str] = None # path to saved SSE events JSON file
track_events_file: Optional[str] = None # path to saved track events JSON file
model: Optional[str] = None # LLM model used for this test
@dataclass
class LLMTarget:
"""One configured LLM alias passed from the CLI."""
name: str
alias: str
model_name: str | None = None
@dataclass
class MessageRunResult:
"""Result of sending a message to the agent."""
events: List[Dict[str, Any]]
timed_out: bool = False
error: Optional[str] = None
@dataclass(frozen=True)
class ScheduledJob:
"""One scheduled automated evaluation job."""
target_index: int
test_index: int
target: LLMTarget
test_case: TestCase
model_key: str
site_bucket: str
class OpenBrowserClient:
"""Client for OpenBrowser server API"""
def __init__(
self, base_url: str = OPENBROWSER_API_URL, chrome_uuid: Optional[str] = None
):
self.base_url = base_url
self.session = requests.Session()
self.session.trust_env = False
self.chrome_uuid = chrome_uuid
def health_check(self) -> bool:
"""Check if OpenBrowser server is running"""
try:
response = self.session.get(f"{self.base_url}/health", timeout=2)
return response.status_code == 200
except requests.exceptions.RequestException:
return False
def get_llm_configs(self) -> List[Dict[str, Any]]:
"""Fetch configured LLM entries from the server."""
try:
response = self.session.get(f"{self.base_url}/api/config", timeout=5)
if response.status_code != 200:
return []
data = response.json()
config = data.get("config", {})
llm_configs = config.get("llm_configs", [])
return llm_configs if isinstance(llm_configs, list) else []
except Exception as e:
logger.error(f"Failed to fetch LLM configs: {e}")
return []
def is_browser_valid(self) -> Optional[bool]:
"""Check whether the configured browser UUID is currently registered."""
if not self.chrome_uuid:
return None
try:
response = self.session.get(
f"{self.base_url}/browsers/{self.chrome_uuid}/valid", timeout=3
)
if response.status_code != 200:
logger.warning(
"Browser validity check failed: status=%s body=%s",
response.status_code,
response.text,
)
return None
data = response.json()
valid = data.get("valid")
return bool(valid) if isinstance(valid, bool) else None
except Exception as e:
logger.warning(f"Browser validity check failed: {e}")
return None
def wait_for_browser_validity(
self,
timeout_seconds: float = 60.0,
poll_interval_seconds: float = 3.0,
) -> bool:
"""Wait for the configured browser UUID to become valid."""
if not self.chrome_uuid:
return True
deadline = time.time() + timeout_seconds
logged_wait = False
while time.time() < deadline:
is_valid = self.is_browser_valid()
if is_valid:
if logged_wait:
logger.info("Browser UUID %s is valid again", self.chrome_uuid)
return True
if not logged_wait:
logger.warning(
"Browser UUID %s is not currently valid; waiting up to %.0fs "
"for the extension to reconnect",
self.chrome_uuid,
timeout_seconds,
)
logged_wait = True
time.sleep(poll_interval_seconds)
logger.error(
"Browser UUID %s did not become valid within %.0fs",
self.chrome_uuid,
timeout_seconds,
)
return False
def create_conversation(
self,
model: Optional[str] = None,
base_url: Optional[str] = None,
model_alias: Optional[str] = None,
mode: Optional[str] = None,
) -> Optional[str]:
"""Create a new conversation and return its ID
Args:
model: Optional model name (e.g., "dashscope/qwen3.5-plus")
base_url: Optional base URL override
model_alias: Optional configured model alias
mode: Optional conversation mode tag (e.g., "routine_replay"
to enable the routine-replay system prompt block).
"""
if self.chrome_uuid and not self.wait_for_browser_validity(
timeout_seconds=30.0
):
return None
request_json: Dict[str, Any] = {}
if model:
request_json["model"] = model
if base_url:
request_json["base_url"] = base_url
if model_alias:
request_json["model_alias"] = model_alias
if mode:
request_json["mode"] = mode
if self.chrome_uuid:
request_json["browser_id"] = self.chrome_uuid
max_attempts = 4
for attempt in range(1, max_attempts + 1):
try:
response = self.session.post(
f"{self.base_url}/agent/conversations",
json=request_json,
timeout=5,
)
if response.status_code == 200:
data = response.json()
return data.get("conversation_id")
response_text = response.text
logger.error(
"Failed to create conversation (attempt %s/%s): status=%s body=%s",
attempt,
max_attempts,
response.status_code,
response_text,
)
should_wait_for_browser = (
self.chrome_uuid is not None
and response.status_code == 400
and "Invalid or expired browser_id" in response_text
)
if should_wait_for_browser and attempt < max_attempts:
if self.wait_for_browser_validity(timeout_seconds=90.0):
continue
return None
except Exception as e:
logger.error(
"Failed to create conversation (attempt %s/%s): %s",
attempt,
max_attempts,
e,
)
if attempt < max_attempts:
time.sleep(3.0)
return None
def send_message(
self,
conversation_id: str,
message: str,
cwd: str = ".",
timeout_seconds: Optional[float] = None,
) -> MessageRunResult:
"""Send a message to the agent and collect SSE events."""
if timeout_seconds is not None and timeout_seconds <= 0:
return MessageRunResult(events=[], timed_out=True)
events: List[Dict[str, Any]] = []
error: Optional[str] = None
timed_out = False
response_holder: Dict[str, Any] = {"response": None, "aborted": False}
def _open_stream(sess: requests.Session) -> requests.Response:
return sess.post(
f"{self.base_url}/agent/conversations/{conversation_id}/messages",
json={
"text": message,
"cwd": cwd,
"browser_id": self.chrome_uuid,
},
stream=True,
headers={"Accept": "text/event-stream"},
# (connect, read). Read timeout gates individual chunks; must be
# larger than the slowest LLM turn. Outer wall-clock is enforced
# via thread-join below.
timeout=(SSE_CONNECT_TIMEOUT, SSE_READ_TIMEOUT),
)
def _collect_events() -> None:
nonlocal error
response = None
local_session = requests.Session()
local_session.trust_env = False
try:
try:
response = _open_stream(local_session)
except (RequestsConnectionError, ReadTimeout) as connect_err:
# Pre-stream failure (agent server not accepting or slow to
# start): one backoff retry before we declare the run dead.
logger.warning(
"SSE open failed (%s); retrying once after 2s backoff",
connect_err,
)
if response_holder["aborted"]:
return
time.sleep(2.0)
# Outer wall-clock may have fired while we were sleeping.
if response_holder["aborted"]:
return
response = _open_stream(local_session)
response_holder["response"] = response
response.raise_for_status()
# Parse SSE events manually
buffer = ""
# Simply iterate until iter_content returns empty (connection closed)
for chunk in response.iter_content(
chunk_size=1024, decode_unicode=True
):
if not chunk:
# Empty chunk means end of stream
break
buffer += chunk
# Split on double newlines
while "\n\n" in buffer:
event_str, buffer = buffer.split("\n\n", 1)
event_lines = event_str.strip().split("\n")
event_type = None
data = {}
for line in event_lines:
line = line.strip()
if line.startswith("event:"):
event_type = line[6:].strip()
elif line.startswith("data:"):
data_str = line[5:].strip()
try:
data = json.loads(data_str)
except json.JSONDecodeError:
data = data_str
if event_type:
events.append(
{
"type": event_type,
"data": data,
"timestamp": time.time(),
}
)
logger.debug(f"SSE event: {event_type}")
# Process any remaining buffer (incomplete event)
if buffer.strip():
logger.debug(f"Processing trailing buffer: {buffer[:200]}")
# Try to parse as event even without \n\n delimiter
event_lines = buffer.strip().split("\n")
event_type = None
data = {}
for line in event_lines:
line = line.strip()
if line.startswith("event:"):
event_type = line[6:].strip()
elif line.startswith("data:"):
data_str = line[5:].strip()
try:
data = json.loads(data_str)
except json.JSONDecodeError:
data = data_str
if event_type:
events.append(
{
"type": event_type,
"data": data,
"timestamp": time.time(),
}
)
logger.debug(f"Processed trailing SSE event: {event_type}")
# Check if we have complete and usage_metrics events
has_complete = any(e["type"] == "complete" for e in events)
has_usage_metrics = any(e["type"] == "usage_metrics" for e in events)
logger.debug(
f"Event summary - Complete: {has_complete}, Usage Metrics: {has_usage_metrics}"
)
if has_complete and not has_usage_metrics:
logger.warning(
"Conversation completed but no usage_metrics event received"
)
except (
RequestsConnectionError,
ReadTimeout,
ChunkedEncodingError,
ProtocolError,
) as e:
if response_holder["aborted"]:
logger.info(
"Stopped SSE collection after hitting the test time limit"
)
else:
error = (
f"SSE transport error on :{OPENBROWSER_PORT} after "
f"read_timeout={SSE_READ_TIMEOUT}s: {e}"
)
logger.error(error)
except Exception as e:
if response_holder["aborted"]:
logger.info(
"Stopped SSE collection after hitting the test time limit"
)
else:
error = f"Failed to send message: {e}"
logger.error(error)
finally:
if response is not None:
response.close()
local_session.close()
worker = threading.Thread(target=_collect_events, daemon=True)
worker.start()
worker.join(timeout=timeout_seconds)
if worker.is_alive():
timed_out = True
response_holder["aborted"] = True
response = response_holder.get("response")
if response is not None:
response.close()
worker.join(timeout=5)
if worker.is_alive():
logger.warning(
"SSE collector thread did not exit promptly after timeout"
)
# Log all event types for debugging
event_types = [e["type"] for e in events]
logger.debug(f"Total SSE events collected: {len(events)}, types: {event_types}")
return MessageRunResult(
events=list(events),
timed_out=timed_out,
error=error,
)
def delete_conversation(self, conversation_id: str) -> bool:
"""Delete a conversation"""
try:
response = self.session.delete(
f"{self.base_url}/agent/conversations/{conversation_id}", timeout=5
)
return response.status_code == 200
except Exception:
return False
def get_conversation_events(self, conversation_id: str) -> List[Dict[str, Any]]:
"""Fetch persisted conversation events from the OpenBrowser server."""
try:
response = self.session.get(
f"{self.base_url}/agent/conversations/{conversation_id}/events",
timeout=5,
)
if response.status_code != 200:
logger.warning(
"Failed to fetch conversation events for %s: status=%s body=%s",
conversation_id,
response.status_code,
response.text,
)
return []
data = response.json()
events = data.get("events", [])
return events if isinstance(events, list) else []
except Exception as e:
logger.warning(
"Failed to fetch conversation events for %s: %s",
conversation_id,
e,
)
return []
def get_managed_tabs(self, conversation_id: str) -> List[Dict[str, Any]]:
"""Return managed tabs for a conversation."""
if not self.chrome_uuid:
return []
try:
response = self.session.get(
f"{self.base_url}/tabs",
params={
"browser_id": self.chrome_uuid,
"conversation_id": conversation_id,
"managed_only": "true",
},
timeout=5,
)
if response.status_code != 200:
logger.warning(
"Failed to fetch managed tabs for %s: status=%s body=%s",
conversation_id,
response.status_code,
response.text,
)
return []
data = response.json()
if not data.get("success"):
logger.warning(
"Managed tab fetch was unsuccessful for %s: %s",
conversation_id,
data,
)
return []
tabs = data.get("data", {}).get("tabs", [])
return tabs if isinstance(tabs, list) else []
except Exception as e:
logger.warning(
"Failed to fetch managed tabs for %s: %s", conversation_id, e
)
return []
def close_tab(self, conversation_id: str, tab_id: int) -> bool:
"""Close a managed tab for a conversation."""
if not self.chrome_uuid:
return False
try:
response = self.session.post(
f"{self.base_url}/tabs",
params={
"action": "close",
"browser_id": self.chrome_uuid,
"conversation_id": conversation_id,
"tab_id": tab_id,
},
timeout=5,
)
if response.status_code != 200:
logger.warning(
"Failed to close tab %s for %s: status=%s body=%s",
tab_id,
conversation_id,
response.status_code,
response.text,
)
return False
data = response.json()
success = bool(data.get("success"))
if not success:
logger.warning(
"Close tab command failed for tab %s in %s: %s",
tab_id,
conversation_id,
data,
)
return success
except Exception as e:
logger.warning(
"Failed to close tab %s for %s: %s",
tab_id,
conversation_id,
e,
)
return False
def cleanup_managed_tabs(self, conversation_id: str) -> bool:
"""Close all managed tabs opened for a conversation."""
tabs = self.get_managed_tabs(conversation_id)
if not tabs:
return True
all_closed = True
for tab in tabs:
tab_id = tab.get("tabId")
if not isinstance(tab_id, int):
tab_id = tab.get("tab_id")
if not isinstance(tab_id, int):
logger.warning(
"Skipping managed tab cleanup for %s due to missing tab id: %s",
conversation_id,
tab,
)
all_closed = False
continue
if not self.close_tab(conversation_id, tab_id):
all_closed = False
return all_closed
class EvalServerClient:
"""Client for evaluation server tracking API"""
def __init__(self, base_url: str = EVAL_SERVER_URL):
self.base_url = base_url
self.session = requests.Session()
self.session.trust_env = False
def health_check(self) -> bool:
"""Check if eval server is running"""
try:
response = self.session.get(f"{self.base_url}/api/events", timeout=2)
return response.status_code == 200
except requests.exceptions.RequestException:
return False
def clear_events(self, site: Optional[str] = None) -> bool:
"""Clear tracked events, optionally scoped to one mock site."""
try:
params = {"site": site} if site else None
response = self.session.get(
f"{self.base_url}/api/events/clear", params=params, timeout=2
)
return response.status_code == 200
except Exception:
return False
def get_events(self, site: Optional[str] = None) -> List[Dict[str, Any]]:
"""Get tracked events, optionally scoped to one mock site."""
try:
params = {"site": site} if site else None
response = self.session.get(
f"{self.base_url}/api/events", params=params, timeout=5
)
if response.status_code == 200:
data = response.json()
return data.get("events", [])
except Exception as e:
logger.error(f"Failed to get events: {e}")
return []
def get_sites(self) -> List[str]:
"""Get available sites"""
try:
response = self.session.get(f"{self.base_url}/api/sites", timeout=2)
if response.status_code == 200:
data = response.json()
return data.get("sites", [])
except Exception:
return []
class ServiceManager:
"""Manage OpenBrowser and eval server processes"""
def __init__(self):
self.openbrowser_proc = None
self.eval_server_proc = None
def start_openbrowser(self) -> bool:
"""Check if OpenBrowser server is running, prompt user to start if not"""
try:
# Check if already running
client = OpenBrowserClient()
if client.health_check():
logger.info("OpenBrowser server is running ✓")
return True
root_dir = EVAL_DIR.parent
logger.error(f"""
❌ OpenBrowser server is not running!
Please start the OpenBrowser server manually with:
cd {root_dir}
uv run local-chrome-server serve
The server should start on port 8765 (REST API) and 8766 (WebSocket).
""")
return False
except Exception as e:
logger.error(f"Failed to check OpenBrowser server status: {e}")
return False
def start_eval_server(self) -> bool:
"""Check if eval server is running, prompt user to start if not"""
try:
client = EvalServerClient()
if client.health_check():
logger.info("Eval server is running ✓")
return True
eval_dir = EVAL_DIR
root_dir = EVAL_DIR.parent
logger.error(f"""
❌ Eval server is not running!
Please start the eval server manually with:
cd {eval_dir}
python server.py
Or in another terminal:
cd {root_dir}
uv run python eval/server.py
The server should start on port 16605.
""")
return False
except Exception as e:
logger.error(f"Failed to check eval server status: {e}")
return False
def stop_services(self):
"""Stop all services"""
if self.openbrowser_proc:
try:
os.killpg(os.getpgid(self.openbrowser_proc.pid), signal.SIGTERM)
self.openbrowser_proc.wait(timeout=5)
logger.info("OpenBrowser server stopped")
except Exception as e:
logger.error(f"Error stopping OpenBrowser server: {e}")
self.openbrowser_proc = None
if self.eval_server_proc:
try:
os.killpg(os.getpgid(self.eval_server_proc.pid), signal.SIGTERM)
self.eval_server_proc.wait(timeout=5)
logger.info("Eval server stopped")
except Exception as e:
logger.error(f"Error stopping eval server: {e}")
self.eval_server_proc = None
class EvaluationRunLock(AbstractContextManager["EvaluationRunLock"]):
"""Prevent concurrent evaluation runs from reusing the same browser UUID."""
def __init__(self, browser_uuid: str):
safe_uuid = browser_uuid.replace("/", "_")
self.browser_uuid = browser_uuid
self.path = LOCK_DIR / f"evaluation_{safe_uuid}.lock"
self._handle: Optional[Any] = None
def acquire(self) -> None:
self.path.parent.mkdir(parents=True, exist_ok=True)
handle = open(self.path, "a+")
try:
fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
handle.seek(0)
existing = handle.read().strip()
handle.close()
detail = f" Existing lock info: {existing}" if existing else ""
raise RuntimeError(
"Another evaluation run is already using browser UUID "
f"{self.browser_uuid}.{detail}"
)
handle.seek(0)
handle.truncate()
payload = {
"pid": os.getpid(),
"browser_uuid": self.browser_uuid,
"started_at": datetime.datetime.now().isoformat(),
}
handle.write(json.dumps(payload))
handle.flush()
self._handle = handle
def release(self) -> None:
if self._handle is None:
return
try:
self._handle.seek(0)
self._handle.truncate()
fcntl.flock(self._handle.fileno(), fcntl.LOCK_UN)
finally:
self._handle.close()
self._handle = None
def __enter__(self) -> "EvaluationRunLock":
self.acquire()
return self
def __exit__(self, exc_type, exc, tb) -> None:
self.release()
return None
class Evaluator:
"""Main evaluator class"""
def __init__(self, chrome_uuid: Optional[str] = None):
self.chrome_uuid = chrome_uuid
self.openbrowser = OpenBrowserClient(chrome_uuid=chrome_uuid)
self.eval_server = EvalServerClient()
self.service_manager = ServiceManager()
self.results: List[TestResult] = []
self.output_dir: Optional[Path] = None # Will be set per run
self.current_model: Optional[str] = None # Current model being tested
self.current_target: Optional[LLMTarget] = None # Current CLI target
@staticmethod
def _sanitize_model_name(model_name: str) -> str:
"""Make a model name safe for filesystem paths."""
return model_name.replace("/", "_").replace(":", "_")
@staticmethod
def _get_model_key(target: LLMTarget) -> str:
"""Return the concurrency key for one target."""
return target.model_name or target.alias or target.name
@staticmethod
def _get_test_site_bucket(test_case: TestCase) -> str:
"""Infer the mock-site bucket from the test start URL."""
parsed = urlparse(test_case.start_url)
segments = [segment for segment in parsed.path.split("/") if segment]
if segments:
return segments[0]
return test_case.id
@staticmethod
def _usage_event_signature(event: Dict[str, Any]) -> str:
"""Return a stable signature for one usage_metrics event."""
return json.dumps(event.get("data", {}), sort_keys=True, default=str)
@staticmethod
def _usage_event_timestamp(created_at: Optional[str]) -> float:
"""Convert persisted event timestamps to unix seconds."""
if not created_at:
return time.time()
try:
return datetime.datetime.fromisoformat(created_at).timestamp()
except ValueError:
return time.time()
def _merge_persisted_usage_metrics(
self,
sse_events: List[Dict[str, Any]],
persisted_events: List[Dict[str, Any]],
source: str,
) -> List[Dict[str, Any]]:
"""Inject persisted usage snapshots when the SSE stream missed them."""
persisted_usage_events = [
{
"type": "usage_metrics",
"data": event.get("event_data", {}),
"timestamp": self._usage_event_timestamp(event.get("created_at")),
"recovered_from": source,
"history_event_index": event.get("event_index"),
}
for event in persisted_events
if event.get("event_type") == "usage_metrics"
and isinstance(event.get("event_data"), dict)
]
if not persisted_usage_events:
return list(sse_events)
local_signatures = {
self._usage_event_signature(event)
for event in sse_events
if event.get("type") == "usage_metrics"
}
recovered_events = [
event
for event in persisted_usage_events
if self._usage_event_signature(event) not in local_signatures
]
if not recovered_events:
return list(sse_events)
merged_events = list(sse_events)
complete_index = next(
(
index
for index, event in enumerate(merged_events)
if event.get("type") == "complete"
),
len(merged_events),
)
merged_events[complete_index:complete_index] = recovered_events
logger.info(
"Recovered %s usage_metrics event(s) from %s",
len(recovered_events),
source,
)