from __future__ import annotations import json import os import threading from pathlib import Path import pytest if os.getenv("STACKCHAIN_RUN_RELEASE_E2E") != "1": pytest.skip("packaged Human Gates journey runs only in its gated CI job", allow_module_level=True) pytest.importorskip("playwright.sync_api") from playwright.sync_api import expect, sync_playwright from fake_gitea import FakeGiteaServer from test_mobile_offline_issue_release import ACCESS_TOKEN, ROOT, hydrate_workspace, release_server @pytest.mark.parametrize(("width", "height"), [(320, 568), (390, 844)]) def test_release_artifact_reopens_human_gates_with_one_fresh_mobile_snapshot( tmp_path: Path, width: int, height: int ): archives = sorted((ROOT / "dist").glob("stackchain-dashboard-*.tar.gz")) assert len(archives) == 1, "browser job must download exactly one assembled release archive" fake = FakeGiteaServer(("127.0.0.1", 0)) fake_thread = threading.Thread(target=fake.serve_forever, daemon=True) fake_thread.start() current = {"gate": "g1"} evidence_url = {"value": "/evidence/manifest"} list_requests: list[str] = [] decision_requests: list[dict] = [] browser_errors: list[str] = [] def gate(gate_id: str) -> dict: return { "id": gate_id, "title": "First candidate" if gate_id == "g1" else "Fresh candidate", "project": "stackchain/stackchain-dashboard", "candidate_hash": "a1" if gate_id == "g1" else "b2", "revision": 1, "priority": 5, "checks": [], "artifacts": [{"name": "Signed manifest", "url": evidence_url["value"]}], "links": [], "provenance": {}, "history": [], } try: with release_server( archives[0], tmp_path, f"http://127.0.0.1:{fake.server_port}" ) as origin, sync_playwright() as playwright: evidence_url["value"] = origin + "/evidence/manifest" browser = playwright.chromium.launch(args=["--ignore-certificate-errors"]) context = browser.new_context( viewport={"width": width, "height": height}, ignore_https_errors=True ) page = context.new_page() page.on("pageerror", lambda error: browser_errors.append(error.stack or str(error))) def human_gates_route(route): path = route.request.url.split("?", 1)[0] if route.request.method == "POST": decision_requests.append({ "path": path, "key": route.request.headers.get("idempotency-key"), "body": route.request.post_data_json, }) if len(decision_requests) == 1: route.abort("failed") return payload = {"receipt_id": "receipt-1", "state": "released"} elif path.endswith("/api/v1/human-gates"): list_requests.append(current["gate"]) payload = {"pending_count": 1, "items": [gate(current["gate"])]} else: payload = gate(path.rsplit("/", 1)[-1]) route.fulfill(status=200, content_type="application/json", body=json.dumps(payload)) page.route("**/api/v1/human-gates**", human_gates_route) page.route("**/api/v1/human-gates/**", human_gates_route) page.goto(origin + "/", wait_until="networkidle") page.locator('input[name="device_label"]').fill("Human Gates release phone") page.locator('input[name="access_token"]').fill(ACCESS_TOKEN) page.locator("#submit-sign-in").click() page.wait_for_url(origin + "/", wait_until="networkidle") hydrate_workspace(page) page.evaluate("document.querySelector('#open-human-gates').click()") expect(page.locator("#human-gates")).to_be_visible() expect(page.locator("#human-gate-detail")).to_contain_text("First candidate") tray = page.locator(".human-gate-decision-tray") expect(tray).to_be_visible() expect(page.locator("[data-gate-readiness]")).to_have_text( "0 of 3 confirmations complete" ) tray_bounds = tray.bounding_box() assert tray_bounds assert tray_bounds["y"] + tray_bounds["height"] <= height + 1 for action in ("hold", "release"): bounds = page.locator(f'[data-gate-decision="{action}"]').bounding_box() assert bounds and bounds["height"] >= 44 page.locator('[data-gate-decision="release"]').click() expect(page.locator("[data-gate-error]")).to_contain_text( "Complete the release checklist" ) expect(page.locator('[data-gate-checklist="exact_hash"]')).to_be_focused() assert decision_requests == [] page.locator('[data-gate-checklist="exact_hash"]').check() page.locator('[data-gate-checklist="artifacts_reviewed"]').check() page.locator('[data-gate-checklist="provenance_reviewed"]').check() expect(page.locator("[data-gate-readiness]")).to_have_text( "3 of 3 confirmations complete" ) page.locator("[data-gate-reason]").fill("Awaiting final approval") with page.expect_popup() as popup_info: page.get_by_role("link", name="Signed manifest").click() popup = popup_info.value popup.wait_for_load_state("domcontentloaded") assert not page.url.endswith("/evidence/manifest") expect(page.locator("#human-gates")).to_be_visible() expect(page.locator("#human-gate-detail")).to_contain_text("First candidate") popup.close() page.reload(wait_until="networkidle") hydrate_workspace(page) page.wait_for_load_state("networkidle") page.evaluate("document.querySelector('#open-human-gates').click()") expect(page.locator("#human-gates")).to_be_visible() expect(page.locator('[data-gate-checklist="exact_hash"]')).to_be_checked() expect(page.locator('[data-gate-checklist="artifacts_reviewed"]')).to_be_checked() expect(page.locator('[data-gate-checklist="provenance_reviewed"]')).to_be_checked() expect(page.locator("[data-gate-reason]")).to_have_value("Awaiting final approval") progress_key = page.evaluate( "Object.keys(localStorage).find(key => key.startsWith('stackchain.human-gate-review.v1:'))" ) assert progress_key and progress_key.endswith(":g1:1") assert page.evaluate("key => localStorage.getItem(key) !== null", progress_key) page.locator('[data-gate-decision="release"]').click() expect(page.locator("#human-gate-detail")).to_contain_text("Decision outcome unknown") expect(page.locator("[data-gate-recover]")).to_have_count(1) decision_key = page.evaluate( "Object.keys(localStorage).find(key => key.startsWith('stackchain.human-gate-decision.v1:'))" ) assert decision_key assert len(decision_requests) == 1 page.reload(wait_until="networkidle") hydrate_workspace(page) page.wait_for_load_state("networkidle") page.evaluate("document.querySelector('#open-human-gates').click()") expect(page.locator("#human-gates")).to_be_visible() expect(page.locator("#human-gate-detail")).to_contain_text("Decision outcome unknown") recover = page.locator("[data-gate-recover]") expect(recover).to_be_visible() recover_height = recover.evaluate("element => element.getBoundingClientRect().height") assert recover_height >= 44 recover.click() expect(page.locator("#human-gates-status")).to_contain_text("Decision saved") expect(page.locator(".human-gate-decision-tray")).to_have_count(0) assert len(decision_requests) == 2 assert decision_requests[0] == decision_requests[1] assert not page.evaluate("key => localStorage.getItem(key) !== null", decision_key) assert not page.evaluate("key => localStorage.getItem(key) !== null", progress_key) page.evaluate("document.querySelector('#close-human-gates').click()") before_reopen = len(list_requests) current["gate"] = "g2" page.evaluate("document.querySelector('#open-human-gates').click()") expect(page.locator("#human-gate-detail")).to_contain_text("Fresh candidate") expect(page.locator("#human-gates-list")).to_contain_text("Fresh candidate") assert len(list_requests) == before_reopen + 1 assert page.evaluate("window.innerWidth") == width assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth") bounds = page.locator('[data-human-gate-id="g2"]').bounding_box() assert bounds and bounds["height"] >= 44 assert not browser_errors browser.close() finally: fake.shutdown() fake.server_close() fake_thread.join(timeout=5) def test_release_artifact_reviews_live_human_gate_history_and_receipt_on_phone(tmp_path: Path): archives = sorted((ROOT / "dist").glob("stackchain-dashboard-*.tar.gz")) assert len(archives) == 1 fake = FakeGiteaServer(("127.0.0.1", 0)) fake_thread = threading.Thread(target=fake.serve_forever, daemon=True) fake_thread.start() browser_errors: list[str] = [] history_requests: list[str] = [] held = { "id": "held", "title": "Held candidate", "project": "stackchain/stackchain-dashboard", "candidate_hash": "bbb222", "state": "held", "revision": 2, "priority": 5, "created_at": 100, "updated_at": 200, "reason": "Needs mobile evidence", "override_reason": "", "checklist": {}, "receipt_id": "receipt-2", "checks": [], "artifacts": [], "links": [], "provenance": {}, "history": [{"action": "held", "at": 200, "receipt_id": "receipt-2"}], } released = { **held, "id": "released", "title": "Released candidate", "candidate_hash": "aaa111", "state": "released", "updated_at": 150, "reason": "", "receipt_id": "receipt-1", } superseded = { **held, "id": "superseded", "title": "Superseded candidate", "candidate_hash": "old000", "state": "superseded", "updated_at": 100, "reason": "", "receipt_id": None, } try: with release_server( archives[0], tmp_path, f"http://127.0.0.1:{fake.server_port}" ) as origin, sync_playwright() as playwright: browser = playwright.chromium.launch(args=["--ignore-certificate-errors"]) context = browser.new_context( viewport={"width": 390, "height": 844}, ignore_https_errors=True ) page = context.new_page() page.on("pageerror", lambda error: browser_errors.append(error.stack or str(error))) def gates_route(route): history_requests.append(route.request.url) if "state=history" in route.request.url and "cursor=older-page" in route.request.url: payload = {"pending_count": 0, "items": [superseded], "next_cursor": None} elif "state=history" in route.request.url: payload = {"pending_count": 0, "items": [held, released], "next_cursor": "older-page"} elif route.request.url.endswith("/held"): payload = held else: payload = {"pending_count": 0, "items": []} route.fulfill(status=200, content_type="application/json", body=json.dumps(payload)) page.route("**/api/v1/human-gates**", gates_route) page.route("**/api/v1/human-gates/**", gates_route) page.route("**/api/v1/human-gate-receipts/receipt-2", lambda route: route.fulfill( status=200, content_type="application/json", body=json.dumps({ "receipt_id": "receipt-2", "gate_id": "held", "candidate_hash": "bbb222", "state": "held", "decided_at": 200, "reason": "Needs mobile evidence", "override_reason": "", "checklist": {}, "unmet_required_checks": [], }) )) page.goto(origin + "/", wait_until="networkidle") page.locator('input[name="device_label"]').fill("Human Gate history phone") page.locator('input[name="access_token"]').fill(ACCESS_TOKEN) page.locator("#submit-sign-in").click() page.wait_for_url(origin + "/", wait_until="networkidle") hydrate_workspace(page) page.wait_for_load_state("networkidle") page.evaluate("document.querySelector('#open-human-gates').click()") expect(page.locator("#human-gates")).to_be_visible() cached_before = page.evaluate( "Object.keys(localStorage).filter(key => key.includes('human-gate')).sort()" ) page.locator("#human-gates-history").click() expect(page.locator("#human-gates-status")).to_contain_text("Older decisions are available") expect(page.locator('[data-human-gate-history-id="held"]')).to_contain_text("Held") expect(page.locator('[data-human-gate-history-id="released"]')).to_contain_text("Released") page.locator('[data-human-gate-history-id="held"]').click() expect(page.locator("#human-gate-detail")).to_contain_text("Needs mobile evidence") expect(page.locator("#human-gate-detail")).to_contain_text("receipt-2") expect(page.locator("#human-gate-detail [data-gate-decision]")).to_have_count(0) more = page.get_by_role("button", name="Load older decisions") more_bounds = more.bounding_box() assert more_bounds and more_bounds["height"] >= 44 more.click() expect(page.locator('[data-human-gate-history-id="superseded"]')).to_contain_text("Superseded") expect(page.locator("#human-gate-detail")).to_contain_text("receipt-2") expect(page.locator("#human-gates-status")).to_have_text("All 3 Human Gate decisions loaded.") expect(page.locator("[data-human-gate-history-more]")).to_have_count(0) assert page.evaluate( "Object.keys(localStorage).filter(key => key.includes('human-gate')).sort()" ) == cached_before assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth") for selector in ("#human-gates-pending", "#human-gates-history"): bounds = page.locator(selector).bounding_box() assert bounds and bounds["height"] >= 44 assert any("state=history&limit=20" in url for url in history_requests) assert any("cursor=older-page" in url for url in history_requests) assert not browser_errors browser.close() finally: fake.shutdown() fake.server_close() fake_thread.join(timeout=5)