Download csops_incident_command_004__long/initial_setup.py from tencent/OSWorkerBench: direct link, hf CLI and curl.
- Browser
- Download file 29.9 kB
-
https://huggingface.co/datasets/tencent/OSWorkerBench/resolve/main/csops_incident_command_004__long/initial_setup.py
- Command line
-
hf download hf://datasets/tencent/OSWorkerBench/csops_incident_command_004__long/initial_setup.py
-
curl -L -o initial_setup.py https://huggingface.co/datasets/tencent/OSWorkerBench/resolve/main/csops_incident_command_004__long/initial_setup.py
29.9 kB
| """ | |
| Initial Setup: Incident triage & on-call routing with cross-source availability & ask-before-guess | |
| Task ID: csops_incident_command_004__long (output/0707 #12, cluster C / ITSM) | |
| Mocks: ServiceNow_mock, microsoft_teams_mock, google_calendar_mock, gmail_mock | |
| The agent is an incident commander working the overnight incident queue in ServiceNow. | |
| Assign each new incident to the on-call engineer for its service, then act by priority. | |
| * lever d (cross-source): the on-call rota is in a Gmail note; engineer availability | |
| (PTO this window) is in the Calendar. Assignee = rota[service], UNLESS the primary is | |
| on PTO -> route to their backup. No single app decides. | |
| * read-from-history (was lever k): incident INC0007 doesn't name its service owner and the | |
| service isn't in the rota; the answer is PRE-SEEDED in the Teams #incidents HISTORY | |
| (a manager already replied "INC0007 = Payments, on-call Priya Patel"). The agent reads | |
| the channel history and assigns Priya. (Review 2026-07-11: replaced the live ask/reply — | |
| we can't preset a mid-run reply — with an already-answered exchange in history.) | |
| * lever i (bulk + keep-group): 15 incidents. 8 New to assign (2 P1); 3 already In Progress | |
| + 2 Resolved/Closed (keep); 2 Planning (P5) skip. Assigning a keep/skip incident, or the | |
| wrong engineer, lowers decision-set PRECISION. Denominator = the 8. | |
| Assign = set assigned_to + state 2 (In Progress). P1 also gets a Teams bridge post + a | |
| Calendar "Bridge: <incident>" event (dated the incident date). | |
| GROUND TRUTH: ServiceNow.incidents[*]._inc {branch, priority, service, assignee, is_p1, | |
| actionable}; google_calendar._task_adapter holds the answer key + rota + PTO + bridge date. | |
| Observable results ship ABSENT (Rule 3): New incidents assigned_to null / state 1, no bridge | |
| posts, no bridge events. | |
| SCORING (HIDDEN_STATE_DIFFICULTY.md §3 positive form): "don't assign keep/skip" is a PRECISION | |
| denominator; the missing-owner (read from history) + PTO-reroute are positive, gated by data flow. | |
| No negatives. No live simulator. | |
| """ | |
| import os | |
| import shlex | |
| import subprocess | |
| import time | |
| import uuid | |
| import requests | |
| sid = str(uuid.uuid4()) | |
| with open('/tmp/task_web_sid', 'w', encoding='utf-8') as f: | |
| f.write(sid) | |
| print(f'Generated sid: {sid}') | |
| # --------------------------------------------------------------------------- | |
| # Engineers + on-call rota (rota lives in the Gmail note; embedded to precompute key). | |
| # rota: service -> {primary, backup}. PTO this window: user_diaz (primary for 'Search'). | |
| # --------------------------------------------------------------------------- | |
| ENGINEERS = { | |
| 'user_wong': 'Alice Wong', 'user_lee': 'Bob Lee', 'user_diaz': 'Carol Diaz', | |
| 'user_kim': 'David Kim', 'user_patel': 'Priya Patel', 'user_roy': 'Fiona Roy', | |
| } | |
| ROTA = { | |
| 'API': {'primary': 'user_wong', 'backup': 'user_lee'}, | |
| 'Database': {'primary': 'user_lee', 'backup': 'user_wong'}, | |
| 'Search': {'primary': 'user_diaz', 'backup': 'user_kim'}, # diaz on PTO -> backup kim | |
| 'Auth': {'primary': 'user_kim', 'backup': 'user_diaz'}, | |
| 'Web': {'primary': 'user_roy', 'backup': 'user_wong'}, | |
| 'Payments': {'primary': 'user_patel', 'backup': 'user_lee'}, # INC0007 owner (revealed via ask) | |
| } | |
| PTO_USERS = {'user_diaz'} # on PTO this window (from Calendar) | |
| MISSING_OWNER_INCIDENT = 'INC0007' | |
| MISSING_OWNER_SERVICE = 'Payments' | |
| def _assignee_for(service): | |
| r = ROTA[service] | |
| primary = r['primary'] | |
| return r['backup'] if primary in PTO_USERS else primary | |
| # --------------------------------------------------------------------------- | |
| # Incident spec: (number, short_desc, service, priority, state, kind) | |
| # kind: 'assign' (New, actionable) / 'skip' (P5 Planning) / 'keep' (In Progress/Resolved/Closed) | |
| # priority: 1 (P1) .. 5 (Planning). state: 1 New / 2 In Progress / 6 Resolved / 7 Closed. | |
| # INC0007 (Payments) has service unknown from the ticket -> ask; here we still tag its service | |
| # for the key, but the injected short_description won't name the owner. | |
| # --------------------------------------------------------------------------- | |
| _INC_SPEC = [ | |
| # --- 8 New to assign (2 P1, 6 P2/P3) --- | |
| ('INC0001', 'API 5xx spike', 'API', 1, 1, 'assign'), # P1 | |
| ('INC0002', 'Checkout DB timeouts', 'Database', 1, 1, 'assign'), # P1 | |
| ('INC0003', 'Search results stale', 'Search', 2, 1, 'assign'), # PTO reroute (diaz->kim) | |
| ('INC0004', 'Auth token refresh slow', 'Auth', 2, 1, 'assign'), | |
| ('INC0005', 'Web page load latency', 'Web', 3, 1, 'assign'), | |
| ('INC0006', 'API rate-limit errors', 'API', 3, 1, 'assign'), | |
| ('INC0007', 'Payments latency', 'Payments', 2, 1, 'assign'), # k: owner unknown -> ask | |
| ('INC0008', 'Auth MFA delays', 'Auth', 3, 1, 'assign'), | |
| # --- 2 Planning (P5) -> skip --- | |
| ('INC0009', 'Tech-debt: log rotation', 'Web', 5, 1, 'skip'), | |
| ('INC0010', 'Backlog: metrics cleanup', 'API', 5, 1, 'skip'), | |
| # --- 3 already In Progress -> keep --- | |
| ('INC0011', 'Ongoing DB migration', 'Database', 2, 2, 'keep'), | |
| ('INC0012', 'Search index rebuild', 'Search', 3, 2, 'keep'), | |
| ('INC0013', 'Auth cert renewal', 'Auth', 3, 2, 'keep'), | |
| # --- 2 Resolved/Closed -> keep --- | |
| ('INC0014', 'Resolved: web outage', 'Web', 2, 6, 'keep'), | |
| ('INC0015', 'Closed: api hotfix', 'API', 2, 7, 'keep'), | |
| ] | |
| def _build_incident(idx, number, desc, service, priority, state, kind): | |
| if kind == 'assign': | |
| branch, actionable = 'assign', True | |
| assignee = _assignee_for(service) | |
| elif kind == 'skip': | |
| branch, actionable, assignee = 'skip', False, None | |
| else: | |
| branch, actionable, assignee = 'keep', False, None | |
| is_p1 = (priority == 1 and kind == 'assign') | |
| # injected: New incidents unassigned; keep incidents pre-assigned. | |
| inj_assigned = None if kind in ('assign', 'skip') else 'user_wong' | |
| return { | |
| 'sys_id': f'inc{idx}', 'number': number, 'caller_id': 'user_ext', | |
| 'category': 'Software', 'short_description': desc, 'description': desc, | |
| 'state': state, 'impact': 2, 'urgency': 2, 'priority': priority, | |
| 'assignment_group': 'g1', 'assigned_to': inj_assigned, | |
| 'opened_at': '2026-04-30T02:00:00Z', 'opened_by': 'user_ext', | |
| 'service': service, 'updated_at': '2026-04-30T02:00:00Z', | |
| '_inc': {'branch': branch, 'priority': priority, 'service': service, | |
| 'assignee': assignee, 'is_p1': is_p1, 'actionable': actionable}, | |
| } | |
| _INCIDENTS = [_build_incident(i, *spec) for i, spec in enumerate(_INC_SPEC, start=1)] | |
| # --------------------------------------------------------------------------- | |
| # Precompute answer key. | |
| # --------------------------------------------------------------------------- | |
| ASSIGN_IDS = [t['sys_id'] for t in _INCIDENTS if t['_inc']['branch'] == 'assign'] | |
| P1_IDS = [t['sys_id'] for t in _INCIDENTS if t['_inc']['is_p1']] | |
| SKIP_IDS = [t['sys_id'] for t in _INCIDENTS if t['_inc']['branch'] == 'skip'] | |
| KEEP_IDS = [t['sys_id'] for t in _INCIDENTS if t['_inc']['branch'] == 'keep'] | |
| ASSIGNEE_BY_ID = {t['sys_id']: t['_inc']['assignee'] for t in _INCIDENTS if t['_inc']['branch'] == 'assign'} | |
| NUMBER_BY_ID = {t['sys_id']: t['number'] for t in _INCIDENTS} | |
| MISSING_ID = next(t['sys_id'] for t in _INCIDENTS if t['number'] == MISSING_OWNER_INCIDENT) | |
| MISSING_ASSIGNEE = ASSIGNEE_BY_ID[MISSING_ID] | |
| PTO_INCIDENT_ID = next(t['sys_id'] for t in _INCIDENTS if t['number'] == 'INC0003') # Search -> reroute | |
| BRIDGE_EVENTS = [{'number': NUMBER_BY_ID[i], 'title': f'Bridge: {NUMBER_BY_ID[i]}', | |
| 'date': '2026-04-30'} for i in P1_IDS] | |
| assert len(ASSIGN_IDS) == 8, ASSIGN_IDS | |
| assert len(P1_IDS) == 2, P1_IDS | |
| assert len(SKIP_IDS) == 2 and len(KEEP_IDS) == 5, (SKIP_IDS, KEEP_IDS) | |
| assert ASSIGNEE_BY_ID[PTO_INCIDENT_ID] == 'user_kim', ASSIGNEE_BY_ID[PTO_INCIDENT_ID] # backup, not diaz | |
| assert MISSING_ASSIGNEE == 'user_patel', MISSING_ASSIGNEE | |
| print(f'Assign: {ASSIGN_IDS} (P1={P1_IDS}); skip: {SKIP_IDS}; keep: {KEEP_IDS}') | |
| print(f'PTO reroute INC0003 -> {ASSIGNEE_BY_ID[PTO_INCIDENT_ID]}; INC0007 owner -> {MISSING_ASSIGNEE}') | |
| # --------------------------------------------------------------------------- | |
| # ServiceNow state. | |
| # NOTE: ServiceNow_mock frontend (see websites/ServiceNow_mock/SCHEMA.md and | |
| # src/pages/IncidentForm.jsx `${u.first_name} ${u.last_name}`) requires users to have | |
| # {sys_id, user_name, first_name, last_name, email, active}. Passing only {sys_id,name,email} | |
| # makes every Caller/Assigned-to option render as "undefined undefined". | |
| # --------------------------------------------------------------------------- | |
| def _split_full_name(full): | |
| parts = full.split(' ', 1) | |
| return parts[0], (parts[1] if len(parts) > 1 else '') | |
| def _sn_user(uid, full_name, email): | |
| first, last = _split_full_name(full_name) | |
| return {'sys_id': uid, 'user_name': uid, 'first_name': first, 'last_name': last, | |
| 'email': email, 'active': True} | |
| _SERVICENOW_STATE = { | |
| 'users': [_sn_user(uid, name, f'{uid}@northgate.com') for uid, name in ENGINEERS.items()] | |
| + [_sn_user('user_ext', 'External Caller', 'ext@customer.com')], | |
| 'groups': [{'sys_id': 'g1', 'name': 'SRE On-Call', 'description': 'On-call rotation'}], | |
| 'incidents': _INCIDENTS, 'problems': [], 'changeRequests': [], | |
| 'requests': [], 'requestedItems': [], 'catalogItems': [], 'knowledge': [], 'cmdb': [], | |
| '_task_adapter': {'source_schema': 'incident_oncall', | |
| 'task_id': 'a9b5c210-7e1f-4c3d-d92a-0707aa778800'}, | |
| } | |
| # --------------------------------------------------------------------------- | |
| # Microsoft Teams — the incident channel + extra channels/chatter. | |
| # Review changes: | |
| # #2 ask-before-guess REMOVED (no live mid-run reply). Instead the INC0007 owner Q&A is | |
| # PRE-SEEDED in the #incidents history: the manager already answered "INC0007 = Payments, | |
| # on-call Priya Patel". The agent READS history and assigns accordingly (no asking scored). | |
| # #5 add extra channels (general, sre-announcements) + harmless filler chatter so Teams looks | |
| # real; every senderId resolves to a users[] entry with a displayName. | |
| # --------------------------------------------------------------------------- | |
| TEAMS_USERS = [ | |
| {'userId': 'user_1', 'displayName': 'Lena Ortiz', 'email': 'lena@northgate.com'}, | |
| {'userId': 'user_mgr', 'displayName': 'Sam Wren', 'email': 'sam@northgate.com'}, | |
| {'userId': 'user_patel', 'displayName': 'Priya Patel', 'email': 'priya@northgate.com'}, | |
| {'userId': 'user_kim', 'displayName': 'David Kim', 'email': 'david@northgate.com'}, | |
| {'userId': 'user_wong', 'displayName': 'Alice Wong', 'email': 'alice@northgate.com'}, | |
| ] | |
| def _tmsg(mid, ch, sender, content, ts): | |
| return {'messageId': mid, 'containerId': ch, 'containerType': 'channel', | |
| 'senderId': sender, 'content': content, 'contentType': 'text', | |
| 'messageType': 'message', 'createdDateTime': ts, 'replyToId': None, | |
| 'reactions': [], 'mentions': [], 'attachments': [], 'isBookmarked': False} | |
| # #incidents history: seed the INC0007 owner Q&A (already asked & answered) + normal chatter. | |
| _INCIDENTS_HISTORY = [ | |
| _tmsg('msg_seed', 'ch_incidents', 'user_mgr', | |
| 'Overnight queue is up — please triage and assign per the on-call rota.', '2026-04-30T02:00:00Z'), | |
| _tmsg('msg_q_inc7', 'ch_incidents', 'user_1', | |
| 'Quick one: INC0007 (payments latency) does not name a service owner and Payments is ' | |
| 'not in the rota email — who is on-call for it?', '2026-04-30T02:05:00Z'), | |
| _tmsg('msg_a_inc7', 'ch_incidents', 'user_mgr', | |
| 'INC0007 is the Payments service — on-call is Priya Patel (user_patel). Assign it to her.', | |
| '2026-04-30T02:07:00Z'), | |
| ] | |
| _GENERAL_HISTORY = [ | |
| _tmsg('msg_g1', 'ch_general', 'user_mgr', 'Welcome to the SRE workspace :wave:', '2026-04-20T09:00:00Z'), | |
| _tmsg('msg_g2', 'ch_general', 'user_kim', 'Reminder: incident retro moved to Friday 3pm.', '2026-04-28T14:00:00Z'), | |
| _tmsg('msg_g3', 'ch_general', 'user_wong', 'Coffee machine on 4th floor is fixed 🎉', '2026-04-29T10:30:00Z'), | |
| ] | |
| _ANNOUNCE_HISTORY = [ | |
| _tmsg('msg_an1', 'ch_announcements', 'user_mgr', | |
| 'Q2 on-call rotation published — check the pinned rota email.', '2026-04-27T08:00:00Z'), | |
| _tmsg('msg_an2', 'ch_announcements', 'user_mgr', | |
| 'New sev-1 escalation policy takes effect May 1.', '2026-04-29T16:00:00Z'), | |
| ] | |
| _TEAMS_STATE = { | |
| 'currentUser': {'userId': 'user_1', 'displayName': 'Lena Ortiz', 'email': 'lena@northgate.com'}, | |
| 'users': TEAMS_USERS, | |
| 'teams': [{'teamId': 'team_1', 'displayName': 'SRE', 'description': 'Site reliability', | |
| 'avatar': '', 'channels': ['ch_general', 'ch_announcements', 'ch_incidents'], | |
| 'members': [u['userId'] for u in TEAMS_USERS], | |
| 'owners': ['user_mgr'], 'settings': {}}], | |
| 'channels': [ | |
| {'channelId': 'ch_general', 'teamId': 'team_1', 'displayName': 'general', | |
| 'description': 'Team-wide chatter', 'isPinned': False, | |
| 'members': [u['userId'] for u in TEAMS_USERS], 'pinnedMessages': [], 'tabs': []}, | |
| {'channelId': 'ch_announcements', 'teamId': 'team_1', 'displayName': 'sre-announcements', | |
| 'description': 'Announcements', 'isPinned': False, | |
| 'members': [u['userId'] for u in TEAMS_USERS], 'pinnedMessages': [], 'tabs': []}, | |
| {'channelId': 'ch_incidents', 'teamId': 'team_1', 'displayName': 'incidents', | |
| 'description': 'Incident bridge', 'isPinned': False, | |
| 'members': [u['userId'] for u in TEAMS_USERS], 'pinnedMessages': [], 'tabs': []}, | |
| ], | |
| 'chats': [], | |
| 'messages': { | |
| 'ch_general': _GENERAL_HISTORY, | |
| 'ch_announcements': _ANNOUNCE_HISTORY, | |
| 'ch_incidents': _INCIDENTS_HISTORY, | |
| }, | |
| 'meetings': [], 'calls': [], 'files': [], 'notifications': [], | |
| 'settings': {}, 'ui': {}, | |
| } | |
| # --------------------------------------------------------------------------- | |
| # Google Calendar — engineer PTO (Carol Diaz) + no Bridge events yet. Answer key on adapter. | |
| # NOTE (review #1): google_calendar_mock only renders events whose calendarId is one of its | |
| # hardcoded ids {c1,c2,c3,c4} AND whose calendar entry is visible. An injected calendar with | |
| # id='primary' is replaced-in (wiping the c1..c4 defaults) so events (normalized to 'c1') have | |
| # no visible calendar -> nothing shows. So we inject a calendar with id='c1', visible=True, and | |
| # reference calendarId='c1' on every event. | |
| # --------------------------------------------------------------------------- | |
| CAL_ID = 'c1' | |
| def cal_event(eid, title, start_iso, end_iso, guests): | |
| return {'id': eid, 'calendarId': CAL_ID, 'title': title, 'start': start_iso, | |
| 'end': end_iso, 'location': '', 'description': '', 'guests': guests, | |
| 'color': 'bg-blue-500', 'recurring': 'none'} | |
| _CAL_STATE = { | |
| 'user': {'userId': 'u1', 'email': 'lena@northgate.com'}, | |
| 'calendars': [{'id': CAL_ID, 'name': 'On-Call', 'color': 'bg-blue-500', | |
| 'textColor': 'text-white', 'visible': True, 'userId': 'u1'}], | |
| 'events': [ | |
| cal_event('ev_pto', 'PTO - Carol Diaz', '2026-04-29T00:00:00Z', '2026-05-02T00:00:00Z', []), | |
| cal_event('ev_decoy', 'Weekly SRE sync', '2026-05-01T15:00:00Z', '2026-05-01T15:30:00Z', []), | |
| ], | |
| 'today': '2026-04-30', | |
| '_task_adapter': { | |
| 'source_schema': 'incident_oncall', | |
| 'task_id': 'a9b5c210-7e1f-4c3d-d92a-0707aa778800', | |
| 'variant': 'eval', | |
| # ---- ANSWER KEY ---- | |
| 'assign_ids': ASSIGN_IDS, | |
| 'p1_ids': P1_IDS, | |
| 'skip_ids': SKIP_IDS, | |
| 'keep_ids': KEEP_IDS, | |
| 'assignee_by_id': ASSIGNEE_BY_ID, | |
| 'number_by_id': NUMBER_BY_ID, | |
| 'bridge_events': BRIDGE_EVENTS, | |
| 'missing_owner_id': MISSING_ID, | |
| 'missing_owner_assignee': MISSING_ASSIGNEE, | |
| 'pto_incident_id': PTO_INCIDENT_ID, | |
| 'in_progress_state': 2, | |
| # review #2: no live user-simulator anymore. INC0007's owner is revealed in the | |
| # #incidents Teams HISTORY (msg_a_inc7); the agent reads it and assigns Priya Patel. | |
| # review #3: bridge events must match title AND date (the incident date) on the calendar. | |
| 'bridge_event_date': '2026-04-30', | |
| }, | |
| } | |
| # --------------------------------------------------------------------------- | |
| # Gmail — the on-call rota note + a decoy. | |
| # --------------------------------------------------------------------------- | |
| _rota_lines = '<br>'.join( | |
| f"- {svc}: primary {ENGINEERS[r['primary']]}, backup {ENGINEERS[r['backup']]}" | |
| for svc, r in ROTA.items() if svc != MISSING_OWNER_SERVICE # Payments owner not in the note (ask) | |
| ) | |
| _GMAIL_STATE = { | |
| 'user': {'userId': 'u1', 'username': 'Lena Ortiz', 'email': 'lena@northgate.com', | |
| 'avatar': 'https://picsum.photos/200/200?random=23'}, | |
| 'emails': [ | |
| {'id': 'm_rota', 'threadId': 'thread_r', | |
| 'from': {'name': 'On-Call Bot', 'email': 'oncall@northgate.com', 'avatar': ''}, | |
| 'to': [{'name': 'Lena Ortiz', 'email': 'lena@northgate.com'}], 'cc': [], 'bcc': [], | |
| 'subject': 'This week on-call rota', | |
| 'body': ('Hi Lena,<br><br>On-call rota for this week:<br>' + _rota_lines + | |
| '<br><br>Remember to check calendars for PTO before assigning.<br>— On-Call Bot'), | |
| 'snippet': 'On-call rota for this week...', 'timestamp': '2026-04-28T08:00:00Z', | |
| 'read': False, 'starred': False, 'important': True, 'labels': [], | |
| 'category': 'primary', 'folder': 'inbox', 'attachments': []}, | |
| {'id': 'm_decoy1', 'threadId': 'thread_d1', | |
| 'from': {'name': 'IT Newsletter', 'email': 'news@northgate.com', 'avatar': ''}, | |
| 'to': [{'name': 'Lena Ortiz', 'email': 'lena@northgate.com'}], 'cc': [], 'bcc': [], | |
| 'subject': 'April reliability review', 'body': 'Reminders.', 'snippet': 'Reminders...', | |
| 'timestamp': '2026-04-27T15:00:00Z', 'read': True, 'starred': False, | |
| 'important': False, 'labels': [], 'category': 'updates', 'folder': 'inbox', | |
| 'attachments': []}, | |
| ], | |
| 'labels': [{'id': 'l1', 'name': 'Work', 'color': '#ef4444'}], | |
| 'drafts': [], 'settings': {'density': 'default', 'undoSend': 10}, 'today': '2026-04-30', | |
| } | |
| # --------------------------------------------------------------------------- | |
| # Inject. | |
| # --------------------------------------------------------------------------- | |
| APP_STATES = [ | |
| ('http://28.7.184.198:8105', _SERVICENOW_STATE), # ServiceNow_mock | |
| ('http://28.7.184.198:8162', _TEAMS_STATE), # microsoft_teams_mock | |
| ('http://28.7.184.198:8141', _CAL_STATE), # google_calendar_mock | |
| ('http://28.7.184.198:8138', _GMAIL_STATE), # gmail_mock | |
| ] | |
| for app_url, state in APP_STATES: | |
| resp = requests.post(f'{app_url}/post?sid={sid}', | |
| json={'action': 'set', 'state': state}, timeout=30) | |
| assert resp.status_code == 200, f'State injection failed for {app_url}: {resp.text}' | |
| print(f'State injected: {app_url} sid={sid}') | |
| for app_url, _ in APP_STATES: | |
| go_payload = requests.get(f'{app_url}/go?sid={sid}', timeout=15).json() | |
| assert go_payload.get('initial_state') is not None, ( | |
| f'initial_state is None after injection for {app_url}') | |
| print(f'Verified initial_state set: {app_url}') | |
| # PATCHED_BY: patch_wait_mocks_loaded.py | |
| def launch_gui(command, delay_sec=1.0): | |
| """Launch a GUI command, fully detached from this script. | |
| Inject --remote-debugging-port=1337 (and Chrome quiet flags) so that | |
| wait_mocks_loaded's CDP phase can verify browser render below. | |
| Idempotent: if the caller already specified a debug port, keep it. | |
| """ | |
| env = os.environ.copy() | |
| env['DISPLAY'] = ':0' | |
| if isinstance(command, str): | |
| _parts = shlex.split(command) | |
| else: | |
| _parts = list(command) | |
| if (_parts and 'google-chrome' in _parts[0] | |
| and not any(p.startswith('--remote-debugging-port') for p in _parts)): | |
| _parts[1:1] = [ | |
| '--no-first-run', | |
| '--no-default-browser-check', | |
| '--remote-debugging-port=1337', | |
| ] | |
| subprocess.Popen( | |
| _parts, | |
| stdin=subprocess.DEVNULL, | |
| stdout=subprocess.DEVNULL, | |
| stderr=subprocess.DEVNULL, | |
| env=env, | |
| start_new_session=True, | |
| ) | |
| time.sleep(delay_sec) | |
| def wait_mocks_loaded(app_states, sid_value, timeout=90, render_buffer=12): | |
| """2-phase readiness wait, mirrors cache/ae_pipeline_hygiene_004 style. | |
| Phase 1 - Backend readiness: | |
| Poll each mock's /state?sid=<sid> (preferred) or /go?sid=<sid> | |
| (fallback) until it returns 200 with 'stored_state' or | |
| 'initial_state' respectively, or until timeout. | |
| Phase 2 - Browser render verification (via CDP + Playwright): | |
| Connect to http://localhost:1337 (the --remote-debugging-port | |
| injected by launch_gui above), wait for every open tab to reach | |
| 'networkidle' AND to contain at least 20 DOM elements. This | |
| guarantees the SPA fetched /go?sid= data AND actually painted, | |
| not just that the mock backend is up. | |
| Fallback: | |
| If Playwright is missing or CDP cannot be reached, sleep for | |
| `render_buffer` seconds as a best-effort delay so the screenshot | |
| loop does not start on a still-blank tab. | |
| """ | |
| import urllib.request as _urlreq | |
| import time as _t | |
| _urls = [p for p, _ in app_states] | |
| _opener = _urlreq.build_opener(_urlreq.ProxyHandler({})) | |
| # ---- Phase 1: backend readiness ---- | |
| _deadline = _t.time() + timeout | |
| _todo = list(_urls) | |
| while _todo and _t.time() < _deadline: | |
| _rest = [] | |
| for _u in _todo: | |
| _ok = False | |
| for _path, _need in (('/state?sid=', b'stored_state'), | |
| ('/go?sid=', b'initial_state')): | |
| try: | |
| _r = _opener.open(f"{_u}{_path}{sid_value}", timeout=5) | |
| if _r.status == 200: | |
| _body = _r.read() | |
| if _need in _body: | |
| _ok = True | |
| break | |
| except Exception: | |
| pass | |
| if _ok: | |
| print(f" {_u}: backend ready") | |
| continue | |
| _rest.append(_u) | |
| _todo = _rest | |
| if _todo: | |
| _t.sleep(2) | |
| _done = len(_urls) - len(_todo) | |
| _pend = f" (pending: {_todo})" if _todo else "" | |
| print(f" mocks backend ready: {_done}/{len(_urls)}{_pend}") | |
| # ---- Phase 2: browser render verification via CDP ---- | |
| _cdp_ok = False | |
| try: | |
| from playwright.sync_api import sync_playwright | |
| _cdp_dl = _t.time() + max(15.0, _deadline - _t.time()) | |
| with sync_playwright() as _p: | |
| _br = None | |
| while _t.time() < _cdp_dl: | |
| try: | |
| _br = _p.chromium.connect_over_cdp('http://localhost:1337') | |
| break | |
| except Exception: | |
| _t.sleep(0.5) | |
| if _br is None: | |
| print(" wait_mocks_loaded: CDP connect to :1337 failed; is Chrome up with --remote-debugging-port?") | |
| else: | |
| _n_expected = len(_urls) | |
| _pages = [] | |
| _pg_dl = _t.time() + 15 | |
| _last_count = -1 | |
| _stable_since = None | |
| while _t.time() < _pg_dl: | |
| _pages = [] | |
| for _c in _br.contexts: | |
| _pages.extend(_c.pages) | |
| _cnt = len(_pages) | |
| if _n_expected > 0 and _cnt >= _n_expected: | |
| break | |
| if _cnt > 0 and _cnt == _last_count: | |
| if _stable_since is None: | |
| _stable_since = _t.time() | |
| elif _t.time() - _stable_since >= 1.5: | |
| break | |
| else: | |
| _stable_since = None | |
| _last_count = _cnt | |
| _t.sleep(0.5) | |
| _pages = [] | |
| for _c in _br.contexts: | |
| _pages.extend(_c.pages) | |
| if not _pages: | |
| print(" wait_mocks_loaded: CDP connected but no open tabs found") | |
| else: | |
| print(f" wait_mocks_loaded: {len(_pages)} tab(s) open (expected {_n_expected}); polling render") | |
| _MIN_ELEMS = 20 | |
| _verify_dl = _t.time() + 40.0 # bounded so total setup stays < VM 120s cap | |
| for _pg in _pages: # bring each to front once to defeat background-tab render throttling | |
| try: | |
| _pg.bring_to_front() | |
| except Exception: | |
| pass | |
| _pending = list(_pages) | |
| while _pending and _t.time() < _verify_dl: | |
| _still = [] | |
| for _pg in _pending: | |
| _ttl = "" | |
| try: | |
| _ttl = _pg.title() | |
| except Exception: | |
| pass | |
| try: | |
| _n = _pg.evaluate("document.body ? document.querySelectorAll('*').length : 0") | |
| except Exception: | |
| _n = 0 | |
| if _n >= _MIN_ELEMS: | |
| print(f" wait_mocks_loaded: tab {_ttl!r} rendered ({_n} elements)") | |
| else: | |
| _still.append(_pg) | |
| _pending = _still | |
| if _pending: | |
| _t.sleep(2) | |
| if not _pending: | |
| _cdp_ok = True | |
| else: | |
| for _pg in _pending: | |
| _ttl = "" | |
| try: | |
| _ttl = _pg.title() | |
| except Exception: | |
| pass | |
| print(f" wait_mocks_loaded: WARNING tab {_ttl!r} still not rendered after poll, will fall back") | |
| except ImportError: | |
| print(" wait_mocks_loaded: playwright not installed; skipping CDP phase") | |
| except Exception as _e: | |
| print(f" wait_mocks_loaded: CDP phase error ({_e!r})") | |
| if not _cdp_ok: | |
| print(f" wait_mocks_loaded: falling back to render_buffer={render_buffer}s sleep") | |
| _t.sleep(render_buffer) | |
| else: | |
| print(" wait_mocks_loaded: browser render verified, skipping render_buffer") | |
| def _open_mock_tabs(app_states, sid_value): | |
| """Open the first mock as the primary Chrome window, the rest as new tabs. | |
| Uses launch_gui once per URL so that the macOS localizer regex-extract | |
| (which grabs the FIRST quoted URL per call) still works correctly. | |
| """ | |
| _urls = [p for p, _ in app_states] | |
| if not _urls: | |
| return | |
| launch_gui(f'google-chrome "{_urls[0]}/?sid={sid_value}"', delay_sec=2.0) | |
| for _u in _urls[1:]: | |
| launch_gui(f'google-chrome --new-tab "{_u}/?sid={sid_value}"', delay_sec=1.0) | |
| # PATCHED_BY: add_wait_for_mocks_loaded (colleague headless+playwright render gate) | |
| def wait_for_mocks_loaded(mocks, sid, timeout=60.0, render_timeout=15.0): | |
| """Block until every mock serves injected state AND (best-effort) renders.""" | |
| import time as _t | |
| deadline = _t.time() + timeout | |
| pending = dict(mocks) | |
| while pending and _t.time() < deadline: | |
| for name in list(pending): | |
| try: | |
| r = requests.get(f'{pending[name]}/go?sid={sid}', timeout=5) | |
| if r.status_code == 200 and r.json().get('initial_state') is not None: | |
| del pending[name] | |
| except Exception: | |
| pass | |
| if pending: | |
| _t.sleep(1.0) | |
| if pending: | |
| print(f'WARN: mocks not ready within {timeout}s: {list(pending)}') | |
| try: | |
| from playwright.sync_api import sync_playwright | |
| except ImportError: | |
| print('WARN: playwright not installed; skipping render check, settle 3s') | |
| _t.sleep(3.0) | |
| return | |
| with sync_playwright() as p: | |
| try: | |
| browser = p.chromium.launch(channel='chrome', headless=True, | |
| args=['--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage']) | |
| except Exception as e: | |
| print(f'WARN: could not launch chrome for render check: {e}; settle 3s') | |
| _t.sleep(3.0) | |
| return | |
| try: | |
| for name, url in mocks.items(): | |
| page = browser.new_page() | |
| try: | |
| page.goto(f'{url}/?sid={sid}', wait_until='domcontentloaded', timeout=int(render_timeout * 1000)) | |
| page.wait_for_function( | |
| "document.body && document.body.innerText.length > 50", | |
| timeout=int(render_timeout * 1000)) | |
| print(f'[{name}] rendered OK') | |
| except Exception as e: | |
| print(f'WARN: [{name}] render check issue: {e}') | |
| finally: | |
| page.close() | |
| finally: | |
| browser.close() | |
| # ref pattern (out_benchmark_cache): open visible tabs FIRST, then block until mocks render | |
| _open_mock_tabs(APP_STATES, sid) | |
| wait_for_mocks_loaded({u.rsplit(':', 1)[-1]: u for u, _ in APP_STATES}, sid, timeout=60, render_timeout=15) | |
| wait_mocks_loaded(APP_STATES, sid, timeout=90, render_buffer=12) | |
| print(f'GUI_READY: launched browser tabs for {len(APP_STATES)} apps') | |