""" Initial Setup: X2 — Won deal to invoice to notification Source: generated from CUA-Gym-Hub/task_benchmark/tasks/lc_x2.py Variant: eval Mocks: hubspot_mock,quickbooks_mock,gmail_mock """ 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}') APP_STATES = [('http://28.7.184.198:8150', {'companies': [{'id': 'comp1', 'name': 'Acme', 'domain': 'acme.com', 'industry': 'Technology', 'phone': '+1 (555) 100-0001', 'city': 'San Francisco', 'state': 'CA', 'country': 'United States', 'numberOfEmployees': 250, 'annualRevenue': 15000000, 'lifecycleStage': 'customer', 'owner': 'Admin User', 'description': 'Enterprise SaaS platform', 'createDate': '2024-01-10T09:00:00Z'}, {'id': 'comp2', 'name': 'Globex', 'domain': 'globex.com', 'industry': 'Manufacturing', 'phone': '+1 (555) 100-0002', 'city': 'New York', 'state': 'NY', 'country': 'United States', 'numberOfEmployees': 500, 'annualRevenue': 32000000, 'lifecycleStage': 'customer', 'owner': 'Admin User', 'description': 'Industrial parts supplier', 'createDate': '2024-01-12T09:00:00Z'}, {'id': 'comp3', 'name': 'Initech', 'domain': 'initech.com', 'industry': 'Technology', 'phone': '+1 (555) 100-0003', 'city': 'Austin', 'state': 'TX', 'country': 'United States', 'numberOfEmployees': 120, 'annualRevenue': 8000000, 'lifecycleStage': 'customer', 'owner': 'Admin User', 'description': 'Office software vendor', 'createDate': '2024-01-14T09:00:00Z'}, {'id': 'comp4', 'name': 'Umbrella', 'domain': 'umbrella.com', 'industry': 'Healthcare', 'phone': '+1 (555) 100-0004', 'city': 'Boston', 'state': 'MA', 'country': 'United States', 'numberOfEmployees': 800, 'annualRevenue': 55000000, 'lifecycleStage': 'customer', 'owner': 'Admin User', 'description': 'Healthcare research', 'createDate': '2024-01-16T09:00:00Z'}, {'id': 'comp5', 'name': 'Wayne', 'domain': 'wayne.com', 'industry': 'Finance', 'phone': '+1 (555) 100-0005', 'city': 'Chicago', 'state': 'IL', 'country': 'United States', 'numberOfEmployees': 1200, 'annualRevenue': 90000000, 'lifecycleStage': 'customer', 'owner': 'Admin User', 'description': 'Financial holding group', 'createDate': '2024-01-18T09:00:00Z'}, {'id': 'comp6', 'name': 'Stale Co', 'domain': 'stale.com', 'industry': 'Other', 'phone': '+1 (555) 100-0006', 'city': 'Seattle', 'state': 'WA', 'country': 'United States', 'numberOfEmployees': 90, 'annualRevenue': 5000000, 'lifecycleStage': 'customer', 'owner': 'Admin User', 'description': 'Legacy customer (last quarter)', 'createDate': '2024-01-22T09:00:00Z'}, {'id': 'comp7', 'name': 'Future Inc', 'domain': 'future.com', 'industry': 'Technology', 'phone': '+1 (555) 100-0007', 'city': 'Denver', 'state': 'CO', 'country': 'United States', 'numberOfEmployees': 60, 'annualRevenue': 3000000, 'lifecycleStage': 'opportunity', 'owner': 'Admin User', 'description': 'Q2 prospect', 'createDate': '2024-01-24T09:00:00Z'}, {'id': 'comp8', 'name': 'LostCorp', 'domain': 'lostcorp.com', 'industry': 'Other', 'phone': '+1 (555) 100-0008', 'city': 'Miami', 'state': 'FL', 'country': 'United States', 'numberOfEmployees': 40, 'annualRevenue': 2000000, 'lifecycleStage': 'lead', 'owner': 'Admin User', 'description': 'Lost competitive bid', 'createDate': '2024-01-26T09:00:00Z'}], 'contacts': [{'id': 'c1', 'firstName': '', 'lastName': 'Acme', 'email': 'ap@acme.com', 'phone': '+1 (555) 100-0001', 'jobTitle': 'AP Manager', 'companyId': 'comp1', 'lifecycleStage': 'customer', 'leadStatus': 'connected', 'owner': 'Admin User', 'city': 'San Francisco', 'state': 'CA', 'country': 'United States', 'createDate': '2024-01-15T10:30:00Z', 'lastActivityDate': '2026-04-05T10:00:00Z', 'timeline': []}, {'id': 'c2', 'firstName': '', 'lastName': 'Globex', 'email': 'ap@globex.com', 'phone': '+1 (555) 100-0002', 'jobTitle': 'AP Manager', 'companyId': 'comp2', 'lifecycleStage': 'customer', 'leadStatus': 'connected', 'owner': 'Admin User', 'city': 'New York', 'state': 'NY', 'country': 'United States', 'createDate': '2024-01-15T10:30:00Z', 'lastActivityDate': '2026-04-08T10:00:00Z', 'timeline': []}, {'id': 'c3', 'firstName': '', 'lastName': 'Initech', 'email': 'ap@initech.com', 'phone': '+1 (555) 100-0003', 'jobTitle': 'AP Manager', 'companyId': 'comp3', 'lifecycleStage': 'customer', 'leadStatus': 'connected', 'owner': 'Admin User', 'city': 'Austin', 'state': 'TX', 'country': 'United States', 'createDate': '2024-01-15T10:30:00Z', 'lastActivityDate': '2026-04-12T10:00:00Z', 'timeline': []}, {'id': 'c4', 'firstName': '', 'lastName': 'Umbrella', 'email': 'ap@umbrella.com', 'phone': '+1 (555) 100-0004', 'jobTitle': 'AP Manager', 'companyId': 'comp4', 'lifecycleStage': 'customer', 'leadStatus': 'connected', 'owner': 'Admin User', 'city': 'Boston', 'state': 'MA', 'country': 'United States', 'createDate': '2024-01-15T10:30:00Z', 'lastActivityDate': '2026-04-18T10:00:00Z', 'timeline': []}, {'id': 'c5', 'firstName': '', 'lastName': 'Wayne', 'email': 'ap@wayne.com', 'phone': '+1 (555) 100-0005', 'jobTitle': 'AP Manager', 'companyId': 'comp5', 'lifecycleStage': 'customer', 'leadStatus': 'connected', 'owner': 'Admin User', 'city': 'Chicago', 'state': 'IL', 'country': 'United States', 'createDate': '2024-01-15T10:30:00Z', 'lastActivityDate': '2026-04-22T10:00:00Z', 'timeline': []}, {'id': 'c6', 'firstName': '', 'lastName': 'Stale Co', 'email': 'ap@stale.com', 'phone': '+1 (555) 100-0006', 'jobTitle': 'AP Manager', 'companyId': 'comp6', 'lifecycleStage': 'customer', 'leadStatus': 'connected', 'owner': 'Admin User', 'city': 'Seattle', 'state': 'WA', 'country': 'United States', 'createDate': '2024-01-15T10:30:00Z', 'lastActivityDate': '2026-03-25T10:00:00Z', 'timeline': []}, {'id': 'c7', 'firstName': '', 'lastName': 'Future Inc', 'email': 'ap@future.com', 'phone': '+1 (555) 100-0007', 'jobTitle': 'AP Manager', 'companyId': 'comp7', 'lifecycleStage': 'opportunity', 'leadStatus': 'connected', 'owner': 'Admin User', 'city': 'Denver', 'state': 'CO', 'country': 'United States', 'createDate': '2024-01-15T10:30:00Z', 'lastActivityDate': '2026-05-03T10:00:00Z', 'timeline': []}, {'id': 'c8', 'firstName': '', 'lastName': 'LostCorp', 'email': 'ap@lostcorp.com', 'phone': '+1 (555) 100-0008', 'jobTitle': 'AP Manager', 'companyId': 'comp8', 'lifecycleStage': 'lead', 'leadStatus': 'unqualified', 'owner': 'Admin User', 'city': 'Miami', 'state': 'FL', 'country': 'United States', 'createDate': '2024-01-15T10:30:00Z', 'lastActivityDate': '2026-04-15T10:00:00Z', 'timeline': []}], # Each deal carries the schema fields the hubspot_mock front-end reads # (name/stage/amount/closeDate/dealType/priority/owner/companyId/ # contactIds/probability/description). The rewritten reward.py reads the # same schema (companies[id==deal.companyId].name, contacts[id== # contactIds[0]].email, deal.description) -- there are NO legacy # tag-along fields any more. # # Single-line-only design: every April Closed Won deal is invoiced with # exactly one line item. The deal name follows the pattern # " - " so the agent can derive the QuickBooks # Product/Service name (the part after " - ") and the QB product catalog # below seeds a matching product whose price equals deals[].amount. # # IMPORTANT: stage value is 'closedwon' (no underscore) because reward.py # filters won deals via norm(d['stage']) == 'closedwon'. We add a matching # 'closedwon' entry to dealStages below so the front-end pipeline shows # those deals in their own labelled column. 'deals': [{'id': 'd1', 'name': 'Acme - Enterprise License', 'stage': 'closedwon', 'amount': 12000, 'closeDate': '2026-04-05', 'dealType': 'new_business', 'priority': 'high', 'owner': 'Admin User', 'companyId': 'comp1', 'contactIds': ['c1'], 'probability': 100, 'description': 'Annual enterprise license, 250 seats', 'createDate': '2026-03-01T10:00:00Z', 'lastActivityDate': '2026-04-05T14:00:00Z'}, {'id': 'd2', 'name': 'Globex - Onboarding Package', 'stage': 'closedwon', 'amount': 7000, 'closeDate': '2026-04-08', 'dealType': 'new_business', 'priority': 'high', 'owner': 'Admin User', 'companyId': 'comp2', 'contactIds': ['c2'], 'probability': 100, 'description': 'Onboarding bundle (setup + license)', 'createDate': '2026-03-01T10:00:00Z', 'lastActivityDate': '2026-04-08T14:00:00Z'}, {'id': 'd3', 'name': 'Initech - Annual Subscription', 'stage': 'closedwon', 'amount': 8000, 'closeDate': '2026-04-12', 'dealType': 'existing_business', 'priority': 'medium', 'owner': 'Admin User', 'companyId': 'comp3', 'contactIds': ['c3'], 'probability': 100, 'description': 'Standard annual plan', 'createDate': '2026-03-05T10:00:00Z', 'lastActivityDate': '2026-04-12T14:00:00Z'}, {'id': 'd4', 'name': 'Umbrella - Hybrid Plan', 'stage': 'closedwon', 'amount': 8000, 'closeDate': '2026-04-18', 'dealType': 'new_business', 'priority': 'high', 'owner': 'Admin User', 'companyId': 'comp4', 'contactIds': ['c4'], 'probability': 100, 'description': 'Hybrid plan (seats + support bundled)', 'createDate': '2026-03-08T10:00:00Z', 'lastActivityDate': '2026-04-18T14:00:00Z'}, {'id': 'd5', 'name': 'Wayne - Renewal', 'stage': 'closedwon', 'amount': 15000, 'closeDate': '2026-04-22', 'dealType': 'existing_business', 'priority': 'high', 'owner': 'Admin User', 'companyId': 'comp5', 'contactIds': ['c5'], 'probability': 100, 'description': 'Renewal of existing master contract', 'createDate': '2026-03-12T10:00:00Z', 'lastActivityDate': '2026-04-22T14:00:00Z'}, {'id': 'd6', 'name': 'Stale Co - Last Quarter', 'stage': 'closedwon', 'amount': 9000, 'closeDate': '2026-03-25', 'dealType': 'existing_business', 'priority': 'medium', 'owner': 'Admin User', 'companyId': 'comp6', 'contactIds': ['c6'], 'probability': 100, 'description': 'Q1 deal, closed in March 2026', 'createDate': '2026-02-20T10:00:00Z', 'lastActivityDate': '2026-03-25T14:00:00Z'}, {'id': 'd7', 'name': 'Future Inc - Q2 Pipeline', 'stage': 'contract_sent', 'amount': 11000, 'closeDate': '2026-05-03', 'dealType': 'new_business', 'priority': 'medium', 'owner': 'Admin User', 'companyId': 'comp7', 'contactIds': ['c7'], 'probability': 90, 'description': 'Q2 deal, awaiting signature', 'createDate': '2026-04-10T10:00:00Z', 'lastActivityDate': '2026-05-03T14:00:00Z'}, {'id': 'd8', 'name': 'LostCorp - Lost Bid', 'stage': 'closed_lost', 'amount': 7000, 'closeDate': '2026-04-15', 'dealType': 'new_business', 'priority': 'low', 'owner': 'Admin User', 'companyId': 'comp8', 'contactIds': ['c8'], 'probability': 0, 'description': 'Lost to competitor', 'createDate': '2026-02-25T10:00:00Z', 'lastActivityDate': '2026-04-15T14:00:00Z', 'closedLostReason': 'Lost to competitor pricing'}], 'tickets': [], 'tasks': [], # Single-line-only design: no per-deal line-item notes are needed. 'notes': [], 'templates': [], 'meetings': [], 'forms': [], # NOTE: 'closedwon' (no underscore) is intentional and matches the literal # value used in reward.py (norm(d['stage']) == 'closedwon'). The default # mockData.js dealStages uses 'closed_won' (with underscore); we override # with this dict so the pipeline view actually has a column whose id === # 'closedwon' to render our deals into. 'dealStages': {'appointment_scheduled': {'id': 'appointment_scheduled', 'label': 'Appointment Scheduled', 'probability': 20, 'color': '#E5F4FF', 'order': 1}, 'qualified_to_buy': {'id': 'qualified_to_buy', 'label': 'Qualified to Buy', 'probability': 40, 'color': '#FFF0E6', 'order': 2}, 'presentation_scheduled': {'id': 'presentation_scheduled', 'label': 'Presentation Scheduled', 'probability': 60, 'color': '#FFF8E6', 'order': 3}, 'decision_maker_bought_in': {'id': 'decision_maker_bought_in', 'label': 'Decision Maker Bought-In', 'probability': 80, 'color': '#E8F5E9', 'order': 4}, 'contract_sent': {'id': 'contract_sent', 'label': 'Contract Sent', 'probability': 90, 'color': '#E6FFFA', 'order': 5}, 'closedwon': {'id': 'closedwon', 'label': 'Closed Won', 'probability': 100, 'color': '#E6FFEC', 'order': 6}, 'closed_lost': {'id': 'closed_lost', 'label': 'Closed Lost', 'probability': 0, 'color': '#FFE6E6', 'order': 7}}, 'ticketStatuses': {'new': {'id': 'new', 'label': 'New', 'color': '#E5F4FF', 'order': 1}, 'waiting_on_contact': {'id': 'waiting_on_contact', 'label': 'Waiting on Contact', 'color': '#FFF8E6', 'order': 2}, 'waiting_on_us': {'id': 'waiting_on_us', 'label': 'Waiting on Us', 'color': '#FFF0E6', 'order': 3}, 'in_progress': {'id': 'in_progress', 'label': 'In Progress', 'color': '#E6FFFA', 'order': 4}, 'closed': {'id': 'closed', 'label': 'Closed', 'color': '#E6FFEC', 'order': 5}}, 'appState': {'sidebarOpen': True, 'currentUser': {'name': 'Admin User', 'email': 'admin@example.com', 'avatar': None}}}), # ---- QuickBooks ---- # Customer naming convention: B2B mapping. Each pre-seeded customer's `name` # equals the corresponding HubSpot company's `name`, and `company` is set to # the same value so the agent can satisfy the instruction's "use that name # as both Name and Company" rule by selecting an existing record. # # Coverage of April 2026 Closed Won deals (d1..d5): # d1 Acme -> qb_c1 (pre-seeded) # d2 Globex -> qb_c2 (pre-seeded) # d3 Initech -> qb_c3 (pre-seeded) # d4 Umbrella -> qb_c4 (pre-seeded) # d5 Wayne -> NOT pre-seeded -> agent MUST create it first. # # Plus distractors (qb_c5 Hooli, qb_c6 Pied Piper) that are unrelated to any # HubSpot deal -- they verify the agent picks customers by deal mapping # rather than blindly choosing the first row. qb_c7 (Stale Co) is the # historical customer for d6 (March 25 won deal, NOT to be invoiced this run); # keeping it makes the seed look like a realistic ongoing books. # # `products` is pre-seeded with one Service per April Closed Won deal: each # product's `name` equals the part of the corresponding deal's name after # " - " (e.g. d1 "Acme - Enterprise License" -> product "Enterprise # License"), and its `price` equals deals[].amount. This way, when the # agent picks the product on the invoice line the form auto-fills the Rate # to the correct amount with no manual override needed. Every product is # `isTaxable: false` so the form's auto-tax stays at $0. ('http://28.7.184.198:8172', {'customers': [{'id': 'qb_c1', 'name': 'Acme', 'company': 'Acme', 'email': 'ap@acme.com', 'phone': '+1 (555) 100-0001', 'address': 'San Francisco, CA, United States', 'balance': 0, 'isActive': True, 'createdAt': '2024-02-01', 'notes': ''}, # NOTE: qb_c2 (Globex) / qb_c3 (Initech) / qb_c4 (Umbrella) # are intentionally NOT pre-seeded. The agent must create # these customers via Sales -> Customers -> "New customer" # before invoicing d2/d3/d4 (same as d5 Wayne). Only d1 # (Acme) starts with a pre-seeded customer in QB. # Distractors: legitimate-looking customers unrelated to any # HubSpot deal in this task. These should NOT receive any # invoice in this run. {'id': 'qb_c5', 'name': 'Hooli', 'company': 'Hooli', 'email': 'billing@hooli.com', 'phone': '+1 (555) 200-0001', 'address': 'Palo Alto, CA, United States', 'balance': 1500, 'isActive': True, 'createdAt': '2023-09-15', 'notes': 'Legacy account'}, {'id': 'qb_c6', 'name': 'Pied Piper', 'company': 'Pied Piper', 'email': 'ap@piedpiper.com', 'phone': '+1 (555) 200-0002', 'address': 'San Francisco, CA, United States', 'balance': 0, 'isActive': True, 'createdAt': '2023-11-02', 'notes': ''}, # Historical customer for d6 (March 25 won, OUT of April scope). {'id': 'qb_c7', 'name': 'Stale Co', 'company': 'Stale Co', 'email': 'ap@stale.com', 'phone': '+1 (555) 100-0006', 'address': 'Seattle, WA, United States', 'balance': 0, 'isActive': True, 'createdAt': '2024-02-01', 'notes': 'Q1 customer; already invoiced in March.'}], # One Service per April Closed Won deal. price == deals[].amount so that # selecting the product on the invoice line auto-fills the Rate correctly. 'products': [{'id': 'qb_p1', 'name': 'Enterprise License', 'description': 'Annual enterprise license', 'type': 'Service', 'price': 12000, 'cost': 0, 'category': 'Services', 'sku': '', 'isActive': True, 'isTaxable': False, 'quantityOnHand': None}, {'id': 'qb_p2', 'name': 'Onboarding Package', 'description': 'Onboarding bundle (setup + license)', 'type': 'Service', 'price': 7000, 'cost': 0, 'category': 'Services', 'sku': '', 'isActive': True, 'isTaxable': False, 'quantityOnHand': None}, {'id': 'qb_p3', 'name': 'Annual Subscription', 'description': 'Standard annual plan', 'type': 'Service', 'price': 8000, 'cost': 0, 'category': 'Services', 'sku': '', 'isActive': True, 'isTaxable': False, 'quantityOnHand': None}, {'id': 'qb_p4', 'name': 'Hybrid Plan', 'description': 'Hybrid plan (seats + support bundled)', 'type': 'Service', 'price': 8000, 'cost': 0, 'category': 'Services', 'sku': '', 'isActive': True, 'isTaxable': False, 'quantityOnHand': None}, {'id': 'qb_p5', 'name': 'Renewal', 'description': 'Renewal of existing master contract', 'type': 'Service', 'price': 15000, 'cost': 0, 'category': 'Services', 'sku': '', 'isActive': True, 'isTaxable': False, 'quantityOnHand': None}], 'invoices': []}), ('http://28.7.184.198:8138', {'emails': []})] 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= (preferred) or /go?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')