"""Production-build interaction checks. Every browser API call is mocked.""" import copy from datetime import datetime, timedelta, timezone import json from pathlib import Path import re import sys from urllib.parse import urlparse, parse_qs from playwright.sync_api import sync_playwright, expect sys.stdout.reconfigure(encoding='utf-8', line_buffering=True) ROOT = Path(__file__).resolve().parents[1] OUT = ROOT / 'artifacts/uiux-upgrade' BASE = sys.argv[1] if len(sys.argv) > 1 else 'http://localhost:3008' report = {'base': BASE, 'checks': [], 'pageErrors': []} guest = 'uiux-browser-test' host = {'id': 'host-test', 'username': 'test-host', 'name': 'Test Host', 'timezone': 'Pacific/Kiritimati', 'bio': 'Coffee together', 'city': 'Chengdu', 'event_count': 1} event = {'id': 'event-test', 'slug': '30min', 'title': 'Test coffee', 'length_minutes': 30, 'host': host, 'locations': []} booking = {'id': 'booking-test', 'uid': 'calendar-test', 'status': 'accepted', 'title': '咖啡, test; calendar', 'host': host, 'attendee': {'name': 'Visitor', 'device': guest, 'email': 'visitor@example.test'}, 'start': '2030-01-15T14:00:00Z', 'end': '2030-01-15T14:30:00Z', 'notes': 'First line\nSecond line', 'location': 'Cafe'} class Backend: def __init__(self): self.calls = [] self.conflict = False self.fail = False self.saved = None self.schedule = {'availability': [], 'timezone': 'UTC'} self.channels = {'in_app': True, 'email': True, 'timezone': 'UTC', 'quiet_start': '22:00', 'quiet_end': '08:00'} self.messages = [{'id': 'message-test', 'category': 'system', 'subject': 'Test notice', 'body': 'Test body', 'created_at': '2026-11-01T12:00:00Z', 'read': False}] def route(self, route): req = route.request parsed = urlparse(req.url); path = parsed.path if not path.startswith('/api/'): return route.continue_() body = req.post_data_json if req.post_data and req.method in ['POST', 'PUT', 'PATCH'] else {} self.calls.append({'path': path, 'method': req.method, 'body': body, 'headers': req.headers, 'query': parse_qs(parsed.query)}) mutation = req.method in ['POST', 'PUT', 'PATCH', 'DELETE'] if mutation and (path.startswith('/api/coffee/') or path.startswith('/api/notify/')): if self.fail: self.fail = False return route.fulfill(status=503, json={'error': 'temporary_failure'}) if path.startswith('/api/config'): if path.endswith('/stream'): return route.fulfill(content_type='text/event-stream', body=': mock\n\n') return route.fulfill(json={'version': 999999, 'flags': {'socialTrialEnabled': False}, 'copy': {'socialTrial': {'enabled': False}}, 'modules': {'social': True}}) if path.startswith('/api/coffee/v1/'): suffix = path.removeprefix('/api/coffee/v1') if suffix == '/me': if req.method == 'PUT': self.saved = {**host, **body, 'username': guest} data = {'host': self.saved, 'schedule': self.schedule} elif suffix.endswith('/schedule') and mutation: self.schedule.update(body); data = {'schedule': self.schedule} elif suffix == '/hosts': data = {'hosts': [host]} elif suffix.endswith('/slots'): day = parse_qs(parsed.query)['day'][0] data = {'timezone': host['timezone'], 'day': day, 'slots': [{'start': day + 'T20:00:00Z', 'end': day + 'T20:30:00Z', 'local': '10:00'}]} elif suffix.endswith('/event-types/30min'): data = {'event_type': event} elif suffix == '/bookings' and mutation: if self.conflict: self.conflict = False return route.fulfill(status=409, json={'detail': 'slot_unavailable'}) data = {'booking': booking} elif suffix == '/bookings': data = {'bookings': []} elif suffix.endswith('/cancel'): data = {'booking': {**booking, 'status': 'cancelled'}} elif suffix.startswith('/bookings/'): data = {'booking': booking} else: data = {'host': {**host, 'event_types': [event]}} return route.fulfill(json={'ok': True, **data}) if path.startswith('/api/notify/v1/'): if path.endswith('/preferences'): if mutation: self.channels.update(body.get('channels', {})) data = {'preferences': {'subscriber_id': guest, 'channels': self.channels}} elif path.endswith('/read-all'): self.messages = [{**m, 'read': True} for m in self.messages] data = {'updated': 1, 'unread': 0} elif req.method == 'DELETE': self.messages = []; data = {} else: data = {'messages': self.messages, 'unread': sum(not m['read'] for m in self.messages), 'unread_by_category': {'system': sum(not m['read'] for m in self.messages)}} return route.fulfill(json={'ok': True, **data}) route.fulfill(json={'ok': True, 'items': [], 'item': None, 'peers': [], 'enabled': False}) with sync_playwright() as pw: browser = pw.chromium.launch() def run(name, path, callback, width=390): context = browser.new_context(viewport={'width': width, 'height': 900}, locale='en-US', timezone_id='America/Los_Angeles', reduced_motion='reduce') context.add_init_script("localStorage.setItem('nomadro-social:guest-id', JSON.stringify('uiux-browser-test')); localStorage.setItem('userEmail','visitor@example.test'); localStorage.setItem('userName','Visitor'); localStorage.setItem('nomadro_web_remote_config_v2', JSON.stringify({config:{version:999999,flags:{socialTrialEnabled:false},copy:{socialTrial:{enabled:false}}}}))") backend = Backend() context.route('**/api/**', backend.route) page = context.new_page(); page.set_default_timeout(10000) page.set_default_navigation_timeout(45000) page.on('pageerror', lambda e: report['pageErrors'].append(str(e))) page.on('dialog', lambda d: d.accept()) try: page.goto(BASE + path, wait_until='domcontentloaded') callback(page, backend) assert page.evaluate('document.documentElement.scrollWidth <= innerWidth + 1'), 'horizontal overflow' page.evaluate('window.scrollTo(0, 0)') page.screenshot(path=str(OUT / (name + '.png')), full_page=True) report['checks'].append({'name': name, 'passed': True}) except Exception as error: report['checks'].append({'name': name, 'passed': False, 'error': str(error)[:1500]}) (OUT / (name + '-failure.txt')).write_text(page.locator('body').inner_text(), encoding='utf-8') finally: context.close() print(json.dumps(report['checks'][-1], ensure_ascii=False)) def book_flow(page, backend): expect(page.locator('.cf-day')).to_have_count(14) expected = (datetime.now(timezone.utc) + timedelta(hours=14)).date().isoformat() expect(page.locator('.cf-day').first).to_have_attribute('aria-label', expected) page.locator('.cf-slot').first.click() page.locator('.cf-form input[autocomplete=name]').fill('Visitor') page.locator('.cf-form input[type=email]').fill('invalid') submit = page.locator('.cf-form button[type=submit]') submit.click() assert not [c for c in backend.calls if c['path'].endswith('/bookings') and c['method'] == 'POST'] page.locator('.cf-form input[type=email]').fill('visitor@example.test') backend.conflict = True submit.click() expect(page.locator('.cf-error')).to_contain_text(re.compile('no longer available|重新选择')) expect(submit).to_be_disabled() page.locator('.cf-slot').first.click() submit.click() expect(page).to_have_url(re.compile('/bookings/booking-test')) expect(page.locator('.cf-panel')).to_contain_text('Visitor') calls = [c for c in backend.calls if c['path'].endswith('/bookings') and c['method'] == 'POST'] assert len(calls) == 2 assert calls[0]['headers']['x-social-guest-id'] == guest assert len(calls[0]['headers']['x-coffee-key']) == 64 with page.expect_download() as download: page.get_by_role('button', name=re.compile('Add to calendar|添加到日历')).click() text = Path(download.value.path()).read_text(encoding='utf-8') assert 'DTSTART:20300115T140000Z' in text and 'SUMMARY:咖啡\\, test\\; calendar' in text page.get_by_role('button', name=re.compile('Cancel booking|取消预约')).click() expect(page.locator('.cf-panel')).to_contain_text('cancelled') run('coffee-booking-mobile', '/social/coffeechat/test-host/30min', book_flow) def manage(page, backend): expect(page.locator('.cf-form input[autocomplete=name]')).to_be_visible() page.locator('.cf-form input[autocomplete=name]').fill('New host') page.locator('.cf-form input[placeholder="Asia/Shanghai"]').fill('UTC') page.locator('.cf-form button[type=submit]').click() expect(page.get_by_role('link', name=re.compile('Public booking page|公开预约页'))).to_be_visible() page.get_by_role('button', name=re.compile('Add window|添加时段')).click() page.get_by_role('button', name=re.compile('Save availability|保存可约时间')).click() expect(page.get_by_role('status').filter(has_text=re.compile('Availability updated|可约时间已更新'))).to_be_visible() assert backend.schedule['availability'][0]['startTime'] == 600 run('coffee-management-desktop', '/social/coffeechat/manage', manage, 1440) def preferences(page, backend): timezone_input = page.locator('.ntf-quiet-fields input[type=text]') expect(timezone_input).to_have_value('UTC') timezone_input.fill('Asia/Shanghai') assert not [c for c in backend.calls if c['method'] == 'PUT'] page.locator('#dnd').click() expect(page.locator('#dnd')).to_be_checked() expect(timezone_input).to_have_value('Asia/Shanghai') save = page.get_by_role('button', name=re.compile('Save quiet hours|保存静默时段')) backend.fail = True save.click() expect(page.locator('.ntf-error')).to_be_visible() expect(timezone_input).to_have_value('Asia/Shanghai') save.click() expect(save).to_be_disabled() assert timezone_input.bounding_box()['width'] >= 200, 'quiet hours input must remain usable on mobile' assert save.bounding_box()['height'] < 80, 'save button must not wrap vertically' assert backend.channels['timezone'] == 'Asia/Shanghai' and backend.channels['dnd'] assert all(c['headers'].get('x-social-guest-id') == guest for c in backend.calls if c['path'].startswith('/api/notify/')) run('notification-preferences-mobile', '/notifications/settings', preferences) def inbox(page, backend): expect(page.locator('.ntf-card h2')).to_have_text('Test notice') page.get_by_role('tab', name=re.compile('System|系统')).click() backend.fail = True page.locator('.ntf-card-actions button').last.click() expect(page.locator('.ntf-error')).to_be_visible() expect(page.locator('.ntf-card')).to_have_count(1) page.get_by_role('button', name=re.compile('Mark category read|本类全部已读')).click() expect(page.locator('.ntf-card.is-unread')).to_have_count(0) call = next(c for c in backend.calls if c['path'].endswith('/read-all')) assert call['body']['subscriber_id'] == guest and call['body']['category'] == 'system' page.locator('.ntf-card-actions button').last.click() expect(page.locator('.ntf-card')).to_have_count(0) run('notification-inbox-desktop', '/notifications', inbox, 1440) browser.close() (OUT / 'portal-interactions.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8') print(json.dumps(report, ensure_ascii=False)) raise SystemExit(0 if all(item['passed'] for item in report['checks']) and not report['pageErrors'] else 1)