File size: 10,943 Bytes
2b86c60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
"""Browser acceptance against a local API and Vite server; reviewer simulations only.

The runner rejects mutation requests unless they originate from its isolated reviewer
session, and rejects every external API request. Screenshots are local artifacts.
"""
import argparse
import json
from pathlib import Path
from urllib.parse import urlsplit
from playwright.sync_api import sync_playwright, expect

ROUTES = {
    '/': 'AI Commerce Agent', '/agent': 'AI Commerce Agent',
    '/store': 'Storefront', '/consumer': 'Storefront',
    '/driver': 'Courier workspace', '/courier': 'Courier workspace',
    '/basket-optimizer': 'BasketOps', '/basketops': 'BasketOps',
    '/dark-store-intel': 'Store Intelligence', '/dark-store': 'Store Intelligence',
    '/site-selection': 'Site Selection', '/route-intelligence': 'Route Intelligence',
    '/route-intel': 'Route Intelligence', '/ml-guard': 'ML Guard',
    '/analytics': 'Analytics', '/replay': 'Failure Replay & Timeline',
    '/case-study': 'Commerce that can explain itself',
}


def navigate(page, path):
    # Client routing preserves the authenticated session; reload rehydrates it from the backend.
    page.evaluate("path => { history.pushState({}, '', path); dispatchEvent(new PopStateEvent('popstate')); }", path)
    expect(page.get_by_role('heading', name=ROUTES[path], exact=True)).to_be_visible()


def reviewer(page):
    page.get_by_role('button', name='Workspace', exact=True).click()
    page.get_by_role('button', name='Open isolated reviewer workspace').click()
    expect(page.get_by_text('ISOLATED SIMULATION', exact=False).first).to_be_visible()


def create_proposal(page, button):
    with page.expect_response(lambda r: r.url.endswith('/api/v2/proposals') and r.request.method == 'POST') as pending:
        button.click()
    response = pending.value
    assert response.ok, response.text()
    proposal = response.json()
    card = page.locator('#proposal-' + proposal['id'])
    expect(card).to_be_visible()
    return card


def approve_execute(card):
    approve = card.get_by_role('button', name='Approve version 1', exact=True)
    expect(approve).to_be_disabled()
    card.get_by_role('checkbox').focus()
    card.get_by_role('checkbox').press('Space')
    expect(approve).to_be_enabled()
    approve.focus()
    approve.press('Enter')
    execute = card.get_by_role('button', name='Execute approved action')
    expect(execute).to_be_enabled()
    execute.focus()
    execute.press('Enter')


def verify(base, output, offline_only=False):
    output.mkdir(parents=True, exist_ok=True)
    checks, errors, scenarios = [], [], []
    with sync_playwright() as playwright:
        browser = playwright.chromium.launch(headless=True)
        context = browser.new_context(viewport={'width': 1440, 'height': 1000})
        context.set_default_timeout(15000)
        context.route('**/*', lambda route: route.continue_() if urlsplit(route.request.url).hostname in ('127.0.0.1', 'localhost') else route.abort())
        page = context.new_page()
        page.on('pageerror', lambda err: errors.append(str(err)))
        try:
            for route, heading in ROUTES.items():
                page.goto(base + route)
                expect(page.get_by_role('heading', name=heading, exact=True)).to_be_visible()
                expect(page.get_by_text('Connect through Workspace', exact=False)).to_be_visible()
                checks.append('disconnected:' + route)
            page.goto(base + '/basket-optimizer')
            page.keyboard.press('Tab')
            expect(page.get_by_role('link', name='Skip to content')).to_be_focused()
            page.keyboard.press('Enter')
            expect(page.locator('#main-content')).to_be_focused()
            checks.append('keyboard:skip-link-and-target')
            if not offline_only:
                reviewer(page)
                for route in ROUTES:
                    navigate(page, route)
                    expect(page.get_by_text('Isolated reviewer workspace · Simulation data · No live transactions', exact=True)).to_be_visible()
                    checks.append('reviewer:' + route)
                navigate(page, '/basket-optimizer')
                page.get_by_role('button', name='Load provider addresses').click()
                expect(page.locator('select').filter(has=page.locator('option[value="scenario-address"]'))).to_be_visible()
                page.get_by_label('Delivery address ID').select_option('scenario-address')
                for scenario in ('success', 'stockout', 'price_change', 'external_edit', 'lost_response'):
                    page.get_by_label('Grocery request').fill('1 L milk')
                    page.get_by_label('Item budget (INR)').fill('200')
                    page.get_by_label('Simulation scenario').select_option(scenario)
                    page.get_by_role('button', name='Find variants and plan basket').click()
                    create = page.get_by_role('button', name='Create cart proposal for review')
                    expect(create).to_be_enabled()
                    card = create_proposal(page, create)
                    approve_execute(card)
                    expected = 'SUPERSEDED' if scenario in ('stockout', 'price_change', 'external_edit') else 'UNKNOWN' if scenario == 'lost_response' else 'SUCCEEDED'
                    expect(card.locator('.state-heading')).to_have_text(expected)
                    if expected == 'SUPERSEDED':
                        # Repairs must remain unapproved until the human reviews them.
                        expect(card.get_by_role('link', name='Review renewed proposal')).to_be_visible()
                        target = card.get_by_role('link', name='Review renewed proposal').get_attribute('href')
                        expect(page.locator(target).get_by_role('button', name='Approve version 1')).to_be_disabled()
                    if scenario == 'lost_response':
                        card.get_by_role('button', name='Inspect uncertain outcome').click()
                        expect(card.locator('.state-heading')).to_have_text('SUCCEEDED')
                    scenarios.append({'scenario': scenario, 'initial_outcome': expected, 'final_outcome': card.locator('.state-heading').inner_text()})
                    checks.append('replay:' + scenario)
                page.locator('.app-main').evaluate('(element) => element.scrollTo(0, 0)')
                page.screenshot(path=str(output / 'basket-desktop.png'), full_page=True)
                navigate(page, '/store')
                page.get_by_label('Mutation tool').fill('checkout')
                page.get_by_label('Address ID', exact=True).fill('scenario-address')
                page.get_by_label('Exact proposed payload (JSON)').fill(json.dumps({'addressId': 'scenario-address', 'paymentMethod': 'COD'}))
                page.get_by_label('Simulation scenario').select_option('uncertain')
                card = create_proposal(page, page.get_by_role('button', name='Create proposal', exact=True))
                approve_execute(card)
                expect(card.locator('.state-heading')).to_have_text('UNKNOWN')
                card.get_by_role('button', name='Inspect uncertain outcome').click()
                expect(card.locator('.state-heading')).to_have_text('UNKNOWN')
                expect(card.get_by_role('button', name='Execute approved action')).to_have_count(0)
                checks.append('replay:unknown-without-exact-receipt')
                scenarios.append({'scenario': 'uncertain_checkout', 'initial_outcome': 'UNKNOWN', 'final_outcome': 'UNKNOWN'})
                navigate(page, '/replay')
                expect(page.get_by_role('heading', name='Durable events')).to_be_visible()
                expect(page.locator('.timeline li').first).to_be_visible()
                page.screenshot(path=str(output / 'timeline-desktop.png'), full_page=True)
                checks.append('durable-timeline')
                context.set_offline(True)
                expect(page.get_by_text('Offline. Saved content may be stale.', exact=False)).to_be_visible()
                context.set_offline(False)
                expect(page.get_by_text('Listening for events', exact=True)).to_be_visible(timeout=15000)
                checks.append('events:reconnect-after-offline')
                navigate(page, '/analytics')
                expect(page.get_by_role('heading', name='Metric definitions and source')).to_be_visible()
                for metric in page.locator('[data-evidence-path]').all():
                    assert metric.get_attribute('data-evidence-endpoint') == '/api/v2/analytics'
                checks.append('analytics:explicit-evidence-binding')
                page.route('**/api/v2/analytics', lambda route: route.abort())
                page.get_by_role('button', name='Refresh saved records').click()
                expect(page.get_by_role('alert').filter(has_text='Backend unavailable')).to_be_visible()
                expect(page.locator('[data-evidence-path]')).to_have_count(0)
                checks.append('offline:explicit-error-no-stale-metrics')
                context.set_offline(True)
                expect(page.get_by_text('Offline. Saved content may be stale.', exact=False)).to_be_visible()
                context.set_offline(False)
                checks.append('offline:browser-banner')
                navigate(page, '/basket-optimizer')
            page.set_viewport_size({'width': 390, 'height': 844})
            if offline_only:
                page.goto(base + '/basket-optimizer')
            expect(page.get_by_role('heading', name='BasketOps')).to_be_visible()
            assert page.evaluate('document.documentElement.scrollWidth <= window.innerWidth'), 'Mobile document overflow'
            page.screenshot(path=str(output / 'basket-mobile.png'), full_page=True)
            checks.append('mobile:no-document-overflow')
            assert not errors, errors
        except Exception:
            page.screenshot(path=str(output / 'failure.png'), full_page=True)
            raise
        finally:
            browser.close()
    result = {'checks': checks, 'passed': len(checks), 'page_errors': errors, 'scenarios': scenarios, 'provider_mode': 'simulation_only', 'offline_only': offline_only}
    (output / 'browser-results.json').write_text(json.dumps(result, indent=2))
    print(json.dumps(result, indent=2))


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--base', default='http://127.0.0.1:5179')
    parser.add_argument('--output', type=Path, default=Path('.local/evidence/browser'))
    parser.add_argument('--offline-only', action='store_true')
    args = parser.parse_args()
    if urlsplit(args.base).hostname not in ('127.0.0.1', 'localhost'):
        parser.error('Acceptance checks require a local isolated demo server')
    verify(args.base.rstrip('/'), args.output, args.offline_only)