Download csops_ticket_queue_005__long/initial_setup.py from tencent/OSWorkerBench: direct link, hf CLI and curl.
- Browser
- Download file 35.6 kB
-
https://huggingface.co/datasets/tencent/OSWorkerBench/resolve/main/csops_ticket_queue_005__long/initial_setup.py
- Command line
-
hf download hf://datasets/tencent/OSWorkerBench/csops_ticket_queue_005__long/initial_setup.py
-
curl -L -o initial_setup.py https://huggingface.co/datasets/tencent/OSWorkerBench/resolve/main/csops_ticket_queue_005__long/initial_setup.py
35.6 kB
| """ | |
| Initial Setup: Support ticket triage with hidden SLA rules & ask-before-guess | |
| Task ID: csops_ticket_queue_005__long (output/0707 #10, cluster C / support) | |
| Mocks: Zendesk_mock, slack_mock, gmail_mock, google_sheets_mock | |
| The agent is a support lead triaging the overnight ticket queue in Zendesk. Set a | |
| priority + route each new ticket per an SLA POLICY -- NOT in the instruction: | |
| * lever g (hidden rule): priority rules (keyword down/outage/breach -> urgent; | |
| Enterprise tier -> high; else normal) live in the Slack #support-ops PINNED message; | |
| a DM names a VIP account (Globex) whose tickets are ALWAYS urgent. Merge both. | |
| * lever k (PROACTIVE / ask-if-unsure): ticket #1007 gives no customer tier, so it | |
| cannot be prioritized from the ticket + SLA policy alone. The agent should ASK in | |
| #support-ops instead of guessing. We reward the *act of asking* (a #support-ops | |
| message naming the ticket + a question marker); #1007 is NOT in the priority | |
| decision set and has no scored "correct" priority (we can't preset a mid-run reply). | |
| * lever i (bulk + keep-group): 16 tickets. 8 new to triage; 1 ambiguous (ask, not | |
| graded for priority); 3 spam (skip); 2 already triaged + 2 solved/closed (keep). | |
| Triaging a spam/keep/ask ticket, or a wrong priority, lowers decision-set PRECISION. | |
| Denominator = the 8. | |
| Urgent tickets escalate to Tier 2 (group_id=2). The agent logs a "Triage Log" register | |
| (Ticket, Priority, Escalated) and posts+pins a summary to #support-ops. | |
| GROUND TRUTH: Zendesk.tickets[*]._tri {branch, priority, escalate, customer, actionable}; | |
| google_sheets._task_adapter holds the answer key + ask_detector + VIP. | |
| Observable results ship ABSENT (Rule 3): new/ask tickets priority null / group 1, register | |
| header-only, no question/reply. | |
| SCORING (HIDDEN_STATE_DIFFICULTY.md §3 positive form): "don't triage spam/keep/ask" is a | |
| PRECISION denominator; the ask is a positive act-of-asking component (no preset reply). No | |
| negatives. | |
| """ | |
| 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}') | |
| VIP_ACCOUNT = 'Globex' | |
| # review comment #1: we cannot preset a mid-run reply, so #1007 is a genuinely | |
| # ambiguous ticket the agent should ASK about (not guess). We grade the *act of | |
| # asking*, not a revealed answer — so #1007 has no "correct" priority and is | |
| # excluded from the priority decision set. | |
| ASK_TICKET = 1007 | |
| URGENT_KEYWORDS = ['down', 'outage', 'breach'] | |
| TIER2_GROUP = 2 | |
| # review (2026-07-11, gmail round): a support lead wraps up the overnight triage by emailing a | |
| # one-line summary to the support team. This is the task's Gmail action (real + gradeable). | |
| SUMMARY_TO = 'support-team@northgate.com' | |
| SUMMARY_SUBJECT = 'Overnight triage summary - 2026-04-30' | |
| # --------------------------------------------------------------------------- | |
| # Ticket spec: (id, subject, customer, tier, status, kind) | |
| # tier: 'Enterprise'|'Standard'|None (None = 1007, unknown -> ASK, don't guess) | |
| # kind: 'triage'=new to triage (8) / 'ask'=ambiguous, ask instead of guess (1) / | |
| # 'spam'=skip / 'triaged'=already done (keep) / 'closed'=solved/closed (keep) | |
| # priority computed by the SLA rule below (VIP or keyword -> urgent; Enterprise -> high; else normal). | |
| # --------------------------------------------------------------------------- | |
| _TICKET_SPEC = [ | |
| # --- 8 new to triage (deterministically decidable from the SLA policy) --- | |
| (1001, 'Production system is down', 'Acme', 'Standard', 'new', 'triage'), # keyword -> urgent | |
| (1002, 'API returning 500 outage', 'Initech', 'Enterprise', 'new', 'triage'), # keyword -> urgent | |
| (1003, 'Security breach suspected', 'Umbrella','Standard', 'new', 'triage'), # keyword -> urgent | |
| (1004, 'Feature request: dark mode', 'Globex', 'Standard', 'new', 'triage'), # VIP -> urgent | |
| (1005, 'Cannot export report', 'Soylent', 'Enterprise', 'new', 'triage'), # Enterprise -> high | |
| (1006, 'Question about invoice', 'Stark', 'Enterprise', 'new', 'triage'), # Enterprise -> high | |
| (1008, 'How do I reset my password', 'Hooli', 'Standard', 'new', 'triage'), # normal | |
| (1009, 'Typo on marketing page', 'Wonka', 'Standard', 'new', 'triage'), # normal | |
| # --- 1 ambiguous: no customer tier -> ASK in #support-ops, do NOT guess --- | |
| (1007, 'Billing question', 'Wayne', None, 'new', 'ask'), # k: unknown tier -> ask | |
| # --- 3 spam (skip) --- | |
| (1010, 'You won a prize!!!', 'spammer', 'Standard', 'new', 'spam'), | |
| (1011, 'Cheap meds online', 'spammer', 'Standard', 'new', 'spam'), | |
| (1012, 'Re: re: re: FWD winner', 'spammer', 'Standard', 'new', 'spam'), | |
| # --- 2 already triaged (keep) --- | |
| (1013, 'Login loop on mobile', 'Tyrell', 'Enterprise', 'open', 'triaged'), # priority already set | |
| (1014, 'Data sync delay', 'Vandelay','Standard', 'open', 'triaged'), | |
| # --- 2 solved/closed (keep) --- | |
| (1015, 'Old issue resolved', 'Oscorp', 'Standard', 'solved', 'closed'), | |
| (1016, 'Closed ticket', 'Nakatomi','Standard', 'closed', 'closed'), | |
| ] | |
| def _sla_priority(subject, customer, tier): | |
| s = subject.lower() | |
| if any(k in s for k in URGENT_KEYWORDS): | |
| return 'urgent' | |
| if customer == VIP_ACCOUNT: | |
| return 'urgent' | |
| if tier == 'Enterprise': | |
| return 'high' | |
| return 'normal' | |
| def _build_ticket(tid, subject, customer, tier, status, kind): | |
| if kind == 'triage': | |
| priority = _sla_priority(subject, customer, tier) | |
| branch, escalate, actionable = 'triage', (priority == 'urgent'), True | |
| elif kind == 'ask': | |
| # ambiguous — the agent should ask, not guess; no "correct" priority to grade | |
| branch, priority, escalate, actionable = 'ask', None, False, False | |
| elif kind == 'spam': | |
| branch, priority, escalate, actionable = 'skip', None, False, False | |
| elif kind == 'triaged': | |
| branch, priority, escalate, actionable = 'keep', 'high', False, False | |
| else: | |
| branch, priority, escalate, actionable = 'keep', None, False, False | |
| # injected state: new/ask tickets ship priority null + group 1; keep tickets pre-set. | |
| if kind in ('triage', 'ask'): | |
| inj_priority, inj_group = None, 1 | |
| elif kind == 'triaged': | |
| inj_priority, inj_group = 'high', TIER2_GROUP | |
| else: | |
| inj_priority, inj_group = (None if kind == 'spam' else None), 1 | |
| tags = ['spam'] if kind == 'spam' else [] | |
| # NOTE (2026-07-15 fix): Zendesk_mock's ViewsPage/TicketDetail/Header all | |
| # render the requester by looking `ticket.requester_id` up in `state.users[]` | |
| # (matching on `id`) and displaying `user.name` — they ignore `customer_name` | |
| # entirely. So we tie requester_id to the ticket id 1:1 and seed a matching | |
| # end-user in _ZENDESK_STATE.users below (name = the ticket's customer), | |
| # otherwise the Requester column and Contact Info panel come up blank. | |
| return { | |
| 'id': tid, 'subject': subject, 'description': subject, | |
| 'status': status, 'priority': inj_priority, | |
| 'requester_id': tid, 'submitter_id': tid, | |
| 'assignee_id': None, 'group_id': inj_group, | |
| 'customer_name': customer, 'customer_tier': tier, 'tags': tags, | |
| 'created_at': '2026-04-30T02:00:00Z', 'updated_at': '2026-04-30T02:00:00Z', | |
| 'is_public': True, 'comment_count': 1, | |
| '_tri': {'branch': branch, 'priority': priority, 'escalate': escalate, | |
| 'customer': customer, 'actionable': actionable}, | |
| } | |
| _TICKETS = [_build_ticket(*spec) for spec in _TICKET_SPEC] | |
| # --------------------------------------------------------------------------- | |
| # Precompute answer key. | |
| # --------------------------------------------------------------------------- | |
| TRIAGE_IDS = [t['id'] for t in _TICKETS if t['_tri']['branch'] == 'triage'] | |
| URGENT_IDS = [t['id'] for t in _TICKETS if t['_tri']['branch'] == 'triage' and t['_tri']['escalate']] | |
| ASK_IDS = [t['id'] for t in _TICKETS if t['_tri']['branch'] == 'ask'] | |
| SKIP_IDS = [t['id'] for t in _TICKETS if t['_tri']['branch'] == 'skip'] | |
| KEEP_IDS = [t['id'] for t in _TICKETS if t['_tri']['branch'] == 'keep'] | |
| PRIORITY_BY_ID = {t['id']: t['_tri']['priority'] for t in _TICKETS if t['_tri']['branch'] == 'triage'} | |
| EXPECTED_REGISTER = [ | |
| {'Ticket': t['id'], 'Priority': t['_tri']['priority'], | |
| 'Escalated': 'yes' if t['_tri']['escalate'] else 'no'} | |
| for t in _TICKETS if t['_tri']['branch'] == 'triage' | |
| ] | |
| assert len(TRIAGE_IDS) == 8, TRIAGE_IDS | |
| assert len(ASK_IDS) == 1 and ASK_IDS[0] == ASK_TICKET, ASK_IDS | |
| assert len(SKIP_IDS) == 3 and len(KEEP_IDS) == 4, (SKIP_IDS, KEEP_IDS) | |
| _prios = set(PRIORITY_BY_ID.values()) | |
| assert {'urgent', 'high', 'normal'} <= _prios, _prios | |
| assert ASK_TICKET not in PRIORITY_BY_ID, 'ask ticket must be excluded from the priority decision set' | |
| assert len(URGENT_IDS) >= 2, URGENT_IDS | |
| print(f'Triage: {TRIAGE_IDS}; urgent(escalate): {URGENT_IDS}; ask: {ASK_IDS}; skip: {SKIP_IDS}; keep: {KEEP_IDS}') | |
| print(f'Priorities: {PRIORITY_BY_ID}') | |
| # --------------------------------------------------------------------------- | |
| # Zendesk state. | |
| # | |
| # NOTE (review comment #4): the Views page (route /views/:id) renders a ticket | |
| # list by evaluating each view's `conditions` against the tickets. If `views` | |
| # is empty, `currentView` is undefined and the list shows "No tickets in this | |
| # view" even though the dashboard's inline "Unassigned" counter (which does NOT | |
| # use views) still reports 14. So we MUST seed the standard Zendesk views here. | |
| # These 8 defaults mirror Zendesk_mock/src/utils/dataManager.js:createInitialData(). | |
| # The "Unassigned tickets" view (id 2) = {assignee_id is null AND status < solved}, | |
| # which matches our 14 non-solved unassigned tickets (8 triage + 1 ask + 3 spam + | |
| # 2 already-triaged open). | |
| # --------------------------------------------------------------------------- | |
| _ZENDESK_VIEWS = [ | |
| {'id': 1, 'title': 'Your unsolved tickets', 'description': 'Tickets assigned to you that are not yet solved', | |
| 'active': True, 'position': 0, 'type': 'standard', | |
| 'conditions': {'all': [{'field': 'assignee_id', 'operator': 'is', 'value': 'current_user'}, | |
| {'field': 'status', 'operator': 'less_than', 'value': 'solved'}], 'any': []}}, | |
| {'id': 2, 'title': 'Unassigned tickets', 'description': 'Tickets with no assignee', | |
| 'active': True, 'position': 1, 'type': 'standard', | |
| 'conditions': {'all': [{'field': 'assignee_id', 'operator': 'is', 'value': None}, | |
| {'field': 'status', 'operator': 'less_than', 'value': 'solved'}], 'any': []}}, | |
| {'id': 3, 'title': 'All unsolved tickets', 'description': 'All tickets that are not solved or closed', | |
| 'active': True, 'position': 2, 'type': 'standard', | |
| 'conditions': {'all': [{'field': 'status', 'operator': 'less_than', 'value': 'solved'}], 'any': []}}, | |
| {'id': 4, 'title': 'Recently updated tickets', 'description': 'Tickets updated in the last 7 days', | |
| 'active': True, 'position': 3, 'type': 'standard', | |
| 'conditions': {'all': [{'field': 'updated_at', 'operator': 'within', 'value': '7_days'}], 'any': []}}, | |
| {'id': 5, 'title': 'Recently solved tickets', 'description': 'Tickets solved in the last 7 days', | |
| 'active': True, 'position': 4, 'type': 'standard', | |
| 'conditions': {'all': [{'field': 'status', 'operator': 'is', 'value': 'solved'}], 'any': []}}, | |
| {'id': 6, 'title': 'Pending tickets', 'description': 'All pending tickets', | |
| 'active': True, 'position': 5, 'type': 'standard', | |
| 'conditions': {'all': [{'field': 'status', 'operator': 'is', 'value': 'pending'}], 'any': []}}, | |
| {'id': 7, 'title': 'New tickets', 'description': 'All new tickets', | |
| 'active': True, 'position': 6, 'type': 'shared', | |
| 'conditions': {'all': [{'field': 'status', 'operator': 'is', 'value': 'new'}], 'any': []}}, | |
| {'id': 8, 'title': 'Urgent & High priority', 'description': 'Urgent and high priority unsolved tickets', | |
| 'active': True, 'position': 7, 'type': 'personal', | |
| 'conditions': {'all': [{'field': 'status', 'operator': 'less_than', 'value': 'solved'}], | |
| 'any': [{'field': 'priority', 'operator': 'is', 'value': 'urgent'}, | |
| {'field': 'priority', 'operator': 'is', 'value': 'high'}]}}, | |
| ] | |
| # --------------------------------------------------------------------------- | |
| # Requester end-user records — one per ticket, id == ticket.id. | |
| # Zendesk_mock's UI (ViewsPage requester column, TicketDetail Contact Info, | |
| # Header conversations popover) all resolve the requester via | |
| # `state.users.find(u => u.id === ticket.requester_id)`, so if these are absent | |
| # the Requester column shows `—` and the ticket detail's right-hand Contact | |
| # Info panel is blank (which is exactly what the 2026-07-15 review flagged for | |
| # #1007 Wayne). We seed a lightweight end-user for every ticket so each | |
| # customer name shows up in the UI. Nothing here affects reward.py (which | |
| # doesn't read users[]). | |
| # --------------------------------------------------------------------------- | |
| def _initials(name): | |
| parts = [p for p in name.split() if p] | |
| if not parts: | |
| return '??' | |
| if len(parts) == 1: | |
| return parts[0][:2].upper() | |
| return (parts[0][0] + parts[-1][0]).upper() | |
| _REQUESTER_USERS = [ | |
| {'id': t['id'], 'name': t['customer_name'], | |
| 'email': f"contact{t['id']}@{t['customer_name'].lower().replace(' ', '')}.example.com", | |
| 'role': 'end-user', 'phone': None, 'photo': None, | |
| 'organization_id': None, 'group_id': None, | |
| 'time_zone': 'America/New_York', 'locale': 'en-US', | |
| 'suspended': False, 'verified': True, 'active': True, | |
| 'created_at': '2025-01-01T00:00:00Z', 'updated_at': '2026-04-01T00:00:00Z', | |
| 'last_login_at': '2026-04-29T09:00:00Z', | |
| 'initials': _initials(t['customer_name'])} | |
| for t in _TICKETS | |
| ] | |
| _ZENDESK_STATE = { | |
| 'currentUser': {'id': 1, 'name': 'Nadia Farouk', 'email': 'nadia@northgate.com', | |
| 'role': 'admin', 'group_id': 1}, | |
| 'users': [ | |
| {'id': 1, 'name': 'Nadia Farouk', 'email': 'nadia@northgate.com', 'role': 'admin', 'group_id': 1}, | |
| {'id': 3, 'name': 'Emily Rodriguez', 'email': 'emily@northgate.com', 'role': 'agent', 'group_id': 2}, | |
| *_REQUESTER_USERS, | |
| ], | |
| 'groups': [ | |
| {'id': 1, 'name': 'Tier 1 Support', 'description': 'Frontline', 'default': True}, | |
| {'id': 2, 'name': 'Tier 2 Support', 'description': 'Escalations', 'default': False}, | |
| ], | |
| 'tickets': _TICKETS, | |
| 'comments': {}, 'views': _ZENDESK_VIEWS, 'macros': [], | |
| '_task_adapter': {'source_schema': 'ticket_triage', | |
| 'task_id': 'e7f3a210-5c9d-4a1b-b70e-0707ee556688'}, | |
| } | |
| # --------------------------------------------------------------------------- | |
| # Google Sheet — 'Triage Log' register (header only) + answer key. | |
| # --------------------------------------------------------------------------- | |
| REG_HEADERS = ['Ticket', 'Priority', 'Escalated'] | |
| _HEADER_STYLE = {'bold': True, 'bg': '#F3F3F3', 'align': 'center'} | |
| def _header_cell(text): | |
| return {'value': text, 'formula': text, 'computed': text, 'style': dict(_HEADER_STYLE)} | |
| _reg_data = {} | |
| for col_idx, header in enumerate(REG_HEADERS): | |
| _reg_data[f'{chr(ord("A") + col_idx)}1'] = _header_cell(header) | |
| _SHEET_STATE = { | |
| 'id': 'workbook_triage', 'title': 'Triage Workbook', | |
| 'activeSheetId': 'sheet_reg', 'selectedCell': 'A1', 'selectionRange': None, | |
| 'clipboard': None, 'isDragging': False, 'undoStack': [], 'redoStack': [], | |
| 'namedRanges': [], 'conditionalFormats': [], 'charts': [], 'showGridlines': True, | |
| 'showFormulas': False, 'zoom': 100, | |
| 'sheets': [{ | |
| 'id': 'sheet_reg', 'name': 'Triage Log', 'data': _reg_data, | |
| 'rowCount': 100, 'colCount': 26, 'frozenRows': 1, 'frozenCols': 0, | |
| 'tabColor': None, 'isHidden': False, 'columnWidths': {}, 'rowHeights': {}, | |
| 'filterRange': None, 'filterCriteria': {}, 'sortColumn': None, 'sortDirection': None, | |
| }], | |
| '_task_adapter': { | |
| 'source_schema': 'ticket_triage', | |
| 'task_id': 'e7f3a210-5c9d-4a1b-b70e-0707ee556688', | |
| 'variant': 'eval', | |
| 'target_sheet': 'Triage Log', | |
| 'headers': REG_HEADERS, | |
| 'headers_by_sheet': {'Triage Log': REG_HEADERS}, | |
| 'sheet_names': ['Triage Log'], | |
| 'tier2_group': TIER2_GROUP, | |
| # ---- ANSWER KEY ---- | |
| 'triage_ids': TRIAGE_IDS, | |
| 'urgent_ids': URGENT_IDS, | |
| 'ask_ids': ASK_IDS, | |
| 'skip_ids': SKIP_IDS, | |
| 'keep_ids': KEEP_IDS, | |
| 'priority_by_id': {str(k): v for k, v in PRIORITY_BY_ID.items()}, | |
| 'expected_register': EXPECTED_REGISTER, | |
| # review comment #1: no preset mid-run reply. We only detect that the agent | |
| # RAISED the ambiguous ticket in #support-ops (trigger keyword + a question | |
| # marker). There is no scored "correct answer" for #1007 anymore. | |
| 'ask_ticket': ASK_TICKET, | |
| 'ask_detector': { | |
| 'trigger_keywords': ['1007', 'billing question', 'wayne'], | |
| 'question_markers': ['?', 'tier', 'priority', 'unsure', 'not sure', 'clarify', | |
| 'which', 'confirm', 'what'], | |
| }, | |
| # review (2026-07-11, gmail round): the wrap-up summary email answer key. | |
| 'summary_to': SUMMARY_TO, | |
| 'summary_subject': SUMMARY_SUBJECT, | |
| }, | |
| } | |
| # --------------------------------------------------------------------------- | |
| # Gmail — inbound context (a forwarded customer note) + decoy. The agent also SENDS a | |
| # wrap-up triage-summary email here (review 2026-07-11); that outgoing email is graded. | |
| # --------------------------------------------------------------------------- | |
| _GMAIL_STATE = { | |
| 'user': {'userId': 'u1', 'username': 'Nadia Farouk', 'email': 'nadia@northgate.com', | |
| 'avatar': 'https://picsum.photos/200/200?random=19'}, | |
| 'emails': [ | |
| {'id': 'm_note', 'threadId': 'thread_n', | |
| 'from': {'name': 'Globex Support', 'email': 'it@globex.com', 'avatar': ''}, | |
| 'to': [{'name': 'Nadia Farouk', 'email': 'nadia@northgate.com'}], 'cc': [], 'bcc': [], | |
| 'subject': 'FYI — we filed a feature request', | |
| 'body': 'Just a heads up we filed a ticket for dark mode. Thanks!', | |
| 'snippet': 'We filed a ticket for dark mode...', 'timestamp': '2026-04-30T01:00:00Z', | |
| 'read': False, 'starred': False, 'important': False, 'labels': [], | |
| 'category': 'primary', 'folder': 'inbox', 'attachments': []}, | |
| {'id': 'm_decoy1', 'threadId': 'thread_d1', | |
| 'from': {'name': 'Support Newsletter', 'email': 'news@northgate.com', 'avatar': ''}, | |
| 'to': [{'name': 'Nadia Farouk', 'email': 'nadia@northgate.com'}], 'cc': [], 'bcc': [], | |
| 'subject': 'April support tips', 'body': 'Reminders.', 'snippet': 'Reminders...', | |
| 'timestamp': '2026-04-29T15: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', | |
| } | |
| # --------------------------------------------------------------------------- | |
| # Slack — #support-ops pinned SLA policy + VIP DM (lever g). | |
| # --------------------------------------------------------------------------- | |
| _POLICY_TEXT = ( | |
| ':pushpin: SUPPORT SLA TRIAGE POLICY (read before triaging)\n' | |
| '1) Only triage tickets in status new; leave already-triaged, solved, or closed tickets.\n' | |
| '2) Skip spam tickets (tagged spam) — do not set a priority.\n' | |
| '3) Priority: if the subject mentions an outage/down/breach -> URGENT; else if the customer ' | |
| 'is on the Enterprise tier -> HIGH; otherwise NORMAL.\n' | |
| '4) Escalate every URGENT ticket to Tier 2 (group 2).' | |
| ) | |
| _DM_TEXT = ( | |
| 'Reminder: Globex is our VIP account — treat ALL of their tickets as URGENT regardless of ' | |
| 'the subject. Thanks!' | |
| ) | |
| _SLACK_STATE = { | |
| 'currentUser': {'userId': 'user_1', 'name': 'Nadia Farouk', 'fullName': 'Nadia Farouk', | |
| 'displayName': 'Nadia Farouk'}, | |
| # NOTE (review comment #2): slack_mock renders a message author by looking the | |
| # message's senderId up in users[] (key = `userId`) and displaying `fullName` | |
| # (falling back to `displayName`, else the literal "Unknown User"). It ignores | |
| # `name`/`firstName`/`lastName`. So every user MUST carry `fullName`+`displayName` | |
| # or the channel shows "Unknown User" for the pinned policy / DM / replies. | |
| 'users': [ | |
| {'userId': 'user_1', 'firstName': 'Nadia', 'lastName': 'Farouk', 'name': 'Nadia Farouk', | |
| 'fullName': 'Nadia Farouk', 'displayName': 'Nadia Farouk'}, | |
| {'userId': 'user_2', 'firstName': 'Sam', 'lastName': 'Wren', 'name': 'Sam Wren', | |
| 'fullName': 'Sam Wren', 'displayName': 'Sam Wren'}, | |
| ], | |
| # NOTE: slack_mock's index route hard-redirects to /channel/general (see App.jsx), | |
| # so we MUST seed a channelId='general' channel or the workspace lands on | |
| # "Channel not found". #general is pure watermark (harmless chatter); the task | |
| # (SLA policy + VIP DM + agent's question/summary) all live in #support-ops. | |
| 'channels': [ | |
| {'channelId': 'general', 'name': 'general', 'description': 'Company-wide announcements and chatter', | |
| 'topic': 'Say hi \U0001F44B', 'isPrivate': False, 'isStarred': False, | |
| 'members': ['user_1', 'user_2'], 'createdBy': 'user_2', | |
| 'createdAt': '2026-01-01T09:00:00Z', 'pinnedMessages': [], 'unreadCount': 0}, | |
| {'channelId': 'support_ops', 'name': 'support-ops', 'description': 'Support operations', | |
| 'topic': 'Triage', 'isPrivate': False, 'isStarred': True, | |
| 'members': ['user_1', 'user_2'], 'createdBy': 'user_2', | |
| 'createdAt': '2026-01-01T10:00:00Z', 'pinnedMessages': ['msg_policy'], 'unreadCount': 0}, | |
| ], | |
| 'messages': { | |
| # Harmless watermark chatter — no ask-detector trigger keywords | |
| # (1007/billing/wayne) and no summary keywords, so it cannot leak scoring. | |
| 'general': [ | |
| {'messageId': 'msg_gen_1', 'senderId': 'user_2', | |
| 'content': 'Good morning team! Coffee machine on 4F is back online \u2615', | |
| 'timestamp': '2026-04-29T09:00:00Z', 'threadId': None, 'reactions': [], | |
| 'attachments': [], 'isEdited': False}, | |
| {'messageId': 'msg_gen_2', 'senderId': 'user_1', | |
| 'content': 'Reminder: quarterly all-hands moved to Friday afternoon.', | |
| 'timestamp': '2026-04-29T15:30:00Z', 'threadId': None, 'reactions': [], | |
| 'attachments': [], 'isEdited': False}, | |
| {'messageId': 'msg_gen_3', 'senderId': 'user_2', | |
| 'content': 'Office closed Monday for the public holiday \U0001F389', | |
| 'timestamp': '2026-04-30T01:00:00Z', 'threadId': None, 'reactions': [], | |
| 'attachments': [], 'isEdited': False}, | |
| ], | |
| 'support_ops': [ | |
| {'messageId': 'msg_policy', 'senderId': 'user_2', 'content': _POLICY_TEXT, | |
| 'timestamp': '2026-04-01T09:00:00Z', 'threadId': None, 'reactions': [], | |
| 'attachments': [], 'isEdited': False}, | |
| ], | |
| 'dm_1': [ | |
| {'messageId': 'msg_dm_vip', 'senderId': 'user_2', 'content': _DM_TEXT, | |
| 'timestamp': '2026-04-02T11:00:00Z', 'threadId': None, 'reactions': [], | |
| 'attachments': [], 'isEdited': False}, | |
| ], | |
| }, | |
| 'threads': {}, | |
| 'dms': [{'dmId': 'dm_1', 'participants': ['user_1', 'user_2'], 'lastMessage': _DM_TEXT, | |
| 'lastTime': '2026-04-02T11:00:00Z', 'unreadCount': 1}], | |
| 'bookmarkedMessages': [], 'callHistory': [], 'notifications': [], | |
| } | |
| # --------------------------------------------------------------------------- | |
| # Inject. | |
| # --------------------------------------------------------------------------- | |
| APP_STATES = [ | |
| ('http://28.7.184.198:8107', _ZENDESK_STATE), # Zendesk_mock | |
| ('http://28.7.184.198:8178', _SLACK_STATE), # slack_mock | |
| ('http://28.7.184.198:8138', _GMAIL_STATE), # gmail_mock | |
| ('http://28.7.184.198:8145', _SHEET_STATE), # google_sheets_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') | |