diff --git a/CLAUDE.md b/CLAUDE.md index 6ae26df..48bfb66 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -153,7 +153,7 @@ $ python -m wodify bookings `moduleVersion=4qHsLi2Es1qvgd2NhStmPw` - Auth accepted: responses carry `hasApiVersionChanged: false`, so cookie + CSRF + both versions are all valid -- 60 tests pass, no network needed +- 60 tests pass, no network needed (161 as of 2026-11-10) ### The body contract (learned the hard way) @@ -312,6 +312,106 @@ command had its own older inline renderer that only knew `Name`/ class. Rule reinforced: **there must be exactly one attendee-shape parser**; `render.attendees()` now delegates to `attendee_rows()`. +### 2026-11: "the interface changed" -- it was a stale service worker, not the API + +Wodify redeployed on 2026-11-10 (`moduleVersion` -> `+_VG7Ud3pDy9uLRnDiVCAg`). `prime` +then captured **zero** actions, wrote a cache with an empty action table, and every query +reported `NOT PRIMED ... missing 'actions'`. It looked exactly like the 2026-08 endpoint +move. It was not: **every allowlisted path and every response shape is unchanged**, and +the prime walk passes as written on the current Schedule screen (Classes / Appointments +tabs, an "All classes" filter, a week strip, then the class rows). + +What actually happened: the app's **service worker** kept serving the old OutSystems +runtime script to pages whose screen code was already the new build. In that mixed state +every data action throws client-side, before any request leaves the browser: + +``` +TypeError: s is not a function + at Controller.callServerDataSource (.../scripts/OutSystems__....js) +``` + +So screens render blank (Schedule shows only its title bar), the only requests on the wire +are the bootstrap ones (`ActionShowFeaturesAvailable`, `ActionSync*`, `Firebase_CW/*`), and +there is nothing for `_observe` to match. The session was valid the whole time -- cookie and +CSRF were captured fine. + +Which layer, measured rather than assumed (Home, 18 s, errors counted per mode): + +| Tab setting | Runtime script loaded | Data requests | Page errors | +|-------------|-----------------------|---------------|-------------| +| default | `OutSystems__F9kv…` (old) | 14 | `s is not a function` | +| HTTP cache disabled only | `OutSystems__F9kv…` (old) | 14 | `s is not a function` | +| service worker bypassed only | `OutSystems__fKIr…` (new) | 34 | none | +| both | `OutSystems__fKIr…` (new) | 34 | none | + +The HTTP cache is not involved. The worker reported `active`, with nothing `waiting`, so +this is not an upgrade blocked on open tabs either -- it is simply serving stale files. +Why it does not refresh itself was not established; do not write a cause into this file +without measuring it. + +The fix, in `cdp.open_page`: `Network.setBypassServiceWorker` on the prime tab, so the app +loads from the network. Per-tab; nothing in the profile is unregistered or cleared, which +also means **the profile itself is still stale** -- anything else driving that Chrome (the +hermes browser fallback) still gets the broken app until the worker is refreshed. + +Two other defects surfaced, both fixed: + +1. **`prime` saved the empty capture**, replacing the previous cache with one that could + answer nothing. It now raises instead, leaves the existing cache alone, and names the + cause. +2. **`prime` leaked a tab on every run** (`open_page` never closed its target); six stale + Wodify tabs had piled up in the profile. `CDPSession.close()` now closes the tab it + opened. No evidence the leak caused the stale worker -- it is fixed because it is a leak. + +How to tell the two failure modes apart next time -- `prime` now does it for you: + +| `prime` says | Meaning | +|--------------|---------| +| `captured none ... The page itself reported errors ... callServerDataSource` | the *browser's copy of the app* is broken. Endpoints are fine. | +| `captured none ... none matched actions.ACTIONS -- Wodify has probably moved its endpoints` | a real endpoint move, as in 2026-08. Run the path-dump recipe. | +| `page_errors: [...]` on an otherwise successful prime | informational; the app logged errors but data actions still fired. | + +Diagnosis recipe that found it: enable `Runtime` + `Log` on the tab and read the console, +and look at the bodies the app POSTs to `/WodifyClient/moduleservices/log` -- it reports its +own exceptions there, stack included. Six of those posts on a page load is the tell. + +Red herrings from this investigation, so nobody chases them again: + +- The app talks to **Firebase**: `Firebase_CW/ServiceAPIGet_FirebaseCustomToken`, + `identitytoolkit.googleapis.com/...signInWithCustomToken`, and Firestore `Listen` channels + on `firestore-prd-dfda5`. With the data actions dead, that was the *only* traffic, so it + looked like the schedule had moved to Firestore. It has not. Firestore carries the inbox + (`communication-service` database), a per-user notification feed + (`GeneralListenerRequests//Client//Requests`) and performance-result + counts. Classes, rosters and workouts still come from the OutSystems data actions. +- A direct load of `/WodifyClient/Scheduler` was seen to bounce back to Home after ~20 s + with the app in this state. That is the crash, not a route change. +- `WodifyClient_Class/Classes/Attendance/DataActionGetClasses` still fires on Home. It is + still the dead placeholder action (see below). Do not re-add it. + +Also noticed while verifying: the schedule's `Status` (the `YOU` column) can be +`Waitlist`, alongside `Reserved` and `Signed In`. A waitlisted class is marked `»` like any +other of the account's classes, but it is not a confirmed spot -- the `Skill/` prompts now +say so. + +### Exit codes: `list` differs from the generic commands + +This bit the cron prompts: they applied the generic table to `list` commands, so "session +expired" handling fired on bad arguments and `NOT PRIMED` (exit 5) was not handled at all. + +| | `list date` / `list workout` | `bookings`, `schedule`, other action commands | +|---|---|---| +| bad argument | 2 | (argparse) 2 | +| session expired | **3** | **2** | +| stale (redeploy) | **4** | **3** | +| not primed | **5** | **4** | +| write refused | -- | 5 | +| class id not indexed | 6 | -- | + +`prime` exits 1 on any failure. Changing either column would break the deployed hermes +skill, which documents both -- keep them as they are and keep prompts explicit about which +table applies. + ### Publishing Test fixtures use **fictional** names. Real gym members' names were scrubbed and the git diff --git a/README.md b/README.md index 1a4bd62..d59235a 100644 --- a/README.md +++ b/README.md @@ -97,6 +97,13 @@ cannot be obtained any other way: Results are cached at `~/.cache/wodify/session.json`, mode `600`. That file holds live credentials: never commit it, never log it. +`prime` loads the app **from the network**, bypassing the PWA service worker for its own +tab (nothing in the profile is unregistered or cleared), and closes that tab when it is +done. After a Wodify redeploy the worker can otherwise keep serving the old runtime to the +new screens -- an app that throws before it sends a single data request. If a prime +captures nothing it says why (`page_errors`), refuses to overwrite the existing cache, and +exits 1. + ### Priming against a remote profile If the logged-in Chrome is on another host, tunnel first: @@ -122,6 +129,17 @@ result: | `SessionExpiredError` | 2 | Session dead — a human must log in again, then re-prime | | `VersionStaleError` | 3 | Wodify redeployed — re-prime | +Those exit codes are for the action commands (`bookings`, `schedule`, `workout`, …). The +`list` commands use a different set, because 2 is taken by argument errors there: + +| `list date` / `list workout` | Exit | +|------------------------------|------| +| bad date or class id | 2 | +| session expired | 3 | +| Wodify redeployed — re-prime | 4 | +| not primed | 5 | +| class id not in the local index — run `list date` for its day first | 6 | + A silently wrong "no workout today" is worse than an error, so there is no fallback path that guesses. diff --git a/Skill/README.md b/Skill/README.md index 1bfe2a6..f533440 100644 --- a/Skill/README.md +++ b/Skill/README.md @@ -12,7 +12,10 @@ - **没有预约就完全静默**——不发 "今天没课" 这种废话 - WOD 内容是 nice-to-have:拉不到也照常 nag,绝不编造课表 -- CLI 挂了按 exit code 分级处理(2=session 过期,3/4=先 prime 再重试) +- CLI 挂了按 exit code 分级处理。两个 job 只用 `list` 命令,它的退出码是: + 3=session 过期(停下,等人重新登录),4/5=缓存过期或未 prime(prime 一次再重试一次), + 6=class ID 未索引,2=参数错误。注意这和 `bookings` 等通用命令的退出码(2/3/4)不同 +- YOU 列取值:`signed in`(已签到)、`reserved`(已预约)、`waitlist`(候补,不算确认的预约) ## 安装(Hermes Agent 示例) diff --git a/Skill/daily-wod-briefing.md b/Skill/daily-wod-briefing.md index 7df3759..e444555 100644 --- a/Skill/daily-wod-briefing.md +++ b/Skill/daily-wod-briefing.md @@ -4,8 +4,9 @@ 1. 获取今天的日期(YYYY-MM-DD) 2. 运行 `wodify list date <今天日期>` 查看当天课程列表 -3. 检查输出中的 YOU 列: +3. 检查输出中的 YOU 列(你的课前面还会有 `»` 标记): - 如果有 `reserved` 或 `signed in` 的课 → 继续步骤 4 + - 如果是 `waitlist`(候补中,名额未确认)→ 也继续步骤 4,但简报里要写明"候补中",不要说成已预约 - 如果没有任何预约(全是 `-`)→ **什么都不输出,直接结束**(不要发任何消息) 4. 拿到预约课的 ID,运行 `wodify list workout ` 获取训练内容 5. 根据训练内容生成简报并发送 @@ -44,4 +45,13 @@ - 如果有多节课都预约了,每节都出一份简报 - 保持简洁,不要长篇大论 - wodify CLI 路径:~/.local/bin/wodify(或 PATH 中的 `wodify`) -- 如果 wodify 返回 exit code 2(session expired),输出:"⚠️ Wodify session 过期了,需要重新登录才能查 WOD。" 然后结束。 + +## Wodify CLI 退出码处理(`list date` / `list workout`) + +`list` 命令的退出码和 `bookings` 等通用命令**不一样**,别混用: + +- exit 3:session 过期。输出:"⚠️ Wodify session 过期了,需要重新登录才能查 WOD。" 然后结束。**不要** prime,prime 救不了过期的 session。 +- exit 4(Wodify 重新部署,缓存过期)/ exit 5(未 prime):运行一次 `wodify prime --workout-date <今天日期>`,然后把刚才失败的命令重试一次。 + - prime 自己失败(exit 1)或重试后仍失败:输出一行 "⚠️ Wodify CLI 暂时不可用:",然后结束。不要循环 prime,也不要猜课表。 +- exit 6:这个 class ID 不在本地索引里 → 先对那一天跑 `wodify list date`,再重试。 +- exit 2:参数写错了(日期或 ID 格式),改正后重试一次。 diff --git a/Skill/fitness-diary-nag.md b/Skill/fitness-diary-nag.md index 58974ec..ae9e233 100644 --- a/Skill/fitness-diary-nag.md +++ b/Skill/fitness-diary-nag.md @@ -4,11 +4,14 @@ 1. 获取今天的日期(YYYY-MM-DD) 2. 运行 `~/.local/bin/wodify list date <今天日期> --refresh` 查看当天课程(签到状态必须实时获取,一小时缓存也可能早于刚发生的签到) -3. 检查是否有「你」预约了的课(YOU 列显示 booked / signed in) +3. 检查是否有「你」的课(行首有 `»`,YOU 列不是 `-`)。YOU 列的取值: + - `signed in`:已签到,确认上了课 + - `reserved`:只是预约了,不能当作实际上了课 + - `waitlist`:候补,没排上 —— 到晚上还是 `waitlist` 就等于没上课,**按没有预约处理** ## 判断逻辑 -- **如果没有预约**:什么都不要说。静默退出,不发任何消息。 +- **如果没有预约**(全是 `-`,或只有 `waitlist`):什么都不要说。静默退出,不发任何消息。 - **如果有预约**:尝试运行 `~/.local/bin/wodify list workout ` 获取 WOD 内容,然后**无论如何都要**主动来找用户问问题,nag 他记录今天的锻炼数据。 ## 有预约时的行为 @@ -26,10 +29,14 @@ **⚠️ 核心规则:只要有预约就必须发消息 nag。WOD 内容是 nice-to-have,不是必要条件。** 有些课程类型本身就没有 WOD 数据;`list workout` 也可能因为 CLI prime 失败、attendees action 无法 prime 等原因拿不到内容 —— 这些都只影响第 2 步,不影响整个 nag。用预约信息(课名/时间/教练)+ 骨架问题(重量 / Level / 成绩 / AW 截图 / 感觉)照常提问。 -## Wodify CLI 退出码处理 +## Wodify CLI 退出码处理(`list date` / `list workout`) -- exit 2: session 过期,告诉用户需要重新登录 -- exit 3/4: 运行 `~/.local/bin/wodify prime` 后重试 +`list` 命令的退出码和 `bookings` 等通用命令**不一样**,别混用: + +- exit 3: session 过期,告诉用户需要重新登录。**不要** prime,prime 救不了过期的 session +- exit 4(Wodify 重新部署,缓存过期)/ exit 5(未 prime): 运行一次 `~/.local/bin/wodify prime --workout-date <今天日期>` 后,把失败的命令重试一次。prime 自己失败(exit 1)就不要再循环 +- exit 6: class ID 不在本地索引里,先跑当天的 `list date` 再重试 +- exit 2: 参数写错了(日期或 ID 格式),改正后重试一次 - exit 0 但无课程: 当天没课,静默退出 ## 重要 diff --git a/src/wodify/cdp.py b/src/wodify/cdp.py index fb40376..2af0582 100644 --- a/src/wodify/cdp.py +++ b/src/wodify/cdp.py @@ -53,6 +53,7 @@ class CDPSession: self._ws = ws self._id = 0 self.session_id: str | None = None + self.target_id: str | None = None self._pending: dict[int, asyncio.Future] = {} self._events: asyncio.Queue = asyncio.Queue() self._reader: asyncio.Task | None = None @@ -97,6 +98,16 @@ class CDPSession: self._pending.clear() async def close(self) -> None: + # Close the tab this session opened; every prime used to leave one + # behind in the profile. Best-effort -- a dead socket must not mask the + # error that got us here. + if self.target_id is not None: + try: + await self.call("Target.closeTarget", {"targetId": self.target_id}, + timeout=5) + except Exception: # noqa: BLE001 - cleanup only + pass + self.target_id = None if self._reader is not None: self._reader.cancel() self._reader = None @@ -124,13 +135,34 @@ class CDPSession: raise RuntimeError(f"{method}: {raw['error']}") return raw.get("result", {}) - async def open_page(self, url: str = "about:blank") -> None: + async def open_page(self, url: str = "about:blank", *, fresh: bool = True) -> None: + """Open and attach a tab. ``fresh`` bypasses the PWA service worker. + + The app's service worker caches its scripts, and after a Wodify + redeploy it can keep serving the *old* OutSystems runtime to pages + whose screen code is already the new build. That mixed app throws + inside ``Controller.callServerDataSource`` before any data action is + sent: every screen renders blank and there is nothing to capture, while + the session itself is perfectly valid. + + Bypassing the worker for this tab makes the app load from the network. + Nothing in the profile is unregistered or cleared. The HTTP cache is + left on deliberately: it was tested and is not the stale layer (script + URLs are content-hashed), so disabling it gains nothing. + """ target = await self.call("Target.createTarget", {"url": url}) + self.target_id = target["targetId"] att = await self.call("Target.attachToTarget", - {"targetId": target["targetId"], "flatten": True}) + {"targetId": self.target_id, "flatten": True}) self.session_id = att["sessionId"] await self.call("Page.enable", on_target=True) await self.call("Network.enable", on_target=True) + # Console errors and uncaught exceptions: prime reports them, because + # "captured nothing" is undiagnosable without knowing the page crashed. + await self.call("Runtime.enable", on_target=True) + if fresh: + await self.call("Network.setBypassServiceWorker", {"bypass": True}, + on_target=True) async def navigate(self, url: str) -> None: await self.call("Page.navigate", {"url": url}, on_target=True) diff --git a/src/wodify/prime.py b/src/wodify/prime.py index 909c0e3..d81fa92 100644 --- a/src/wodify/prime.py +++ b/src/wodify/prime.py @@ -17,10 +17,13 @@ from __future__ import annotations import asyncio import datetime as _dt import json +import re from typing import Any from . import actions, cdp, client, config +_STAMP = re.compile(r"^\[\d{4}-\d\d-\d\dT[\d:.]+Z\]:?\s*") + #: Screens to walk so the interesting data actions actually fire. Ordered: #: Home first (it is the reliable entry point and populates client vars). WALK = ( @@ -132,6 +135,41 @@ def _observe(event: dict[str, Any], found: dict[str, dict[str, Any]], } +#: How many distinct page errors to keep. Enough to name the failure, not a log. +MAX_PAGE_ERRORS = 5 + + +def _observe_errors(event: dict[str, Any], errors: list[str]) -> None: + """Collect a one-line summary of each distinct page error. + + Only ever reported back to the operator. A page that throws on every data + action captures nothing, and without this the only symptom is an empty + result that looks like "Wodify moved its endpoints again". + """ + method = event.get("method") + params = event.get("params") or {} + chunks: list[str] = [] + if method == "Runtime.exceptionThrown": + details = params.get("exceptionDetails") or {} + exc = details.get("exception") or {} + chunks.append(str(exc.get("description") or details.get("text") or "")) + elif method == "Runtime.consoleAPICalled" and params.get("type") == "error": + for arg in params.get("args") or []: + chunks.append(str(arg.get("description") or arg.get("value") or "")) + lines = [ln.strip() for chunk in chunks for ln in chunk.splitlines() if ln.strip()] + if not lines: + return + # The app stamps its own console errors ("[2026-11-11T05:02:11.964Z]: ..."); + # drop the stamp so identical errors de-duplicate. + message = next((m for m in (_STAMP.sub("", ln).strip() for ln in lines) if m), "") + # First stack frame says *where*, which is the half that identifies a + # broken runtime ("... at Controller.callServerDataSource"). + frame = next((ln.split(" (", 1)[0] for ln in lines if ln.startswith("at ")), "") + summary = (f"{message} {frame}".strip())[:200] + if summary and summary not in errors and len(errors) < MAX_PAGE_ERRORS: + errors.append(summary) + + def _date_label(date: str | None) -> str: """JS string literal for the aria-label fragment of a schedule date button. @@ -155,10 +193,15 @@ async def _run(walk=WALK, workout_date: str | None = None) -> dict[str, Any]: found: dict[str, dict[str, Any]] = {} csrf: list[str] = [] + page_errors: list[str] = [] + + def on_event(ev: dict[str, Any]) -> None: + _observe(ev, found, csrf) + _observe_errors(ev, page_errors) for path, wait in walk: await session.navigate(config.origin() + path) - await session.drain(wait, lambda ev: _observe(ev, found, csrf)) + await session.drain(wait, on_event) # Walk to a real workout screen so GetAllWorkoutData (and the class # detail actions) actually fire. The walk and the request-observer run @@ -166,9 +209,7 @@ async def _run(walk=WALK, workout_date: str | None = None) -> dict[str, Any]: # walk. CDPSession multiplexes one socket reader, so this is safe. script = WORKOUT_WALK_JS.replace("__DATE_LABEL__", _date_label(workout_date)) walk_task = asyncio.create_task(session.evaluate(script, await_promise=True)) - drain_task = asyncio.create_task( - session.drain(30, lambda ev: _observe(ev, found, csrf)) - ) + drain_task = asyncio.create_task(session.drain(30, on_event)) try: walk_log = await asyncio.wait_for(asyncio.shield(walk_task), timeout=45) except asyncio.TimeoutError: @@ -185,10 +226,24 @@ async def _run(walk=WALK, workout_date: str | None = None) -> dict[str, Any]: finally: await session.close() + crashed = (" The page itself reported errors, so the app is failing to " + "run rather than calling different endpoints: " + + " | ".join(page_errors)) if page_errors else "" if not csrf: raise RuntimeError( "no X-CSRFToken observed. The browser is logged in but made no data " - "action calls -- try again, or widen the walk in prime.WALK." + "action calls -- try again, or widen the walk in prime.WALK." + crashed + ) + if not found: + # Never persist an empty capture: it would replace a cache that may + # still answer queries with one that cannot answer any. + raise RuntimeError( + "captured none of the allowlisted data actions; the existing cache " + "was left untouched." + (crashed or + " The app made data-action calls, but none matched actions.ACTIONS " + "-- Wodify has probably moved its endpoints. Dump every " + "/screenservices/ path while clicking Home -> Schedule -> a class " + "and compare.") ) if not module_version: module_version = next( @@ -205,6 +260,7 @@ async def _run(walk=WALK, workout_date: str | None = None) -> dict[str, Any]: "module_version": module_version, "actions": found, "walk_log": walk_log, + "page_errors": page_errors, } @@ -216,6 +272,7 @@ def prime(workout_date: str | None = None) -> dict[str, Any]: """ payload = asyncio.run(_run(workout_date=workout_date)) walk_log = payload.pop("walk_log", None) + page_errors = payload.pop("page_errors", []) path = client.save_cache(payload) captured = sorted(payload["actions"]) @@ -234,4 +291,5 @@ def prime(workout_date: str | None = None) -> dict[str, Any]: "actions_missing": missing, "raw_paths_captured": len(captured), "walk": walk_log, + "page_errors": page_errors, } diff --git a/tests/test_cdp.py b/tests/test_cdp.py index c95df62..5cce043 100644 --- a/tests/test_cdp.py +++ b/tests/test_cdp.py @@ -139,3 +139,92 @@ async def test_call_on_target_without_attachment_raises(session): with pytest.raises(RuntimeError, match="no page target"): await s.call("Page.navigate", on_target=True) await s.close() + + +# -------------------------------------------------------------------------- +# page lifecycle +# -------------------------------------------------------------------------- + +class PageWS(FakeWS): + """Replies with the ids open_page needs.""" + + async def send(self, raw): + msg = json.loads(raw) + self.sent.append(msg) + result = {"Target.createTarget": {"targetId": "TAB1"}, + "Target.attachToTarget": {"sessionId": "SESS1"}}.get(msg["method"], {}) + await self._out.put(json.dumps({"id": msg["id"], "result": result})) + + +def _sent(ws, method): + return [m for m in ws.sent if m["method"] == method] + + +@pytest.mark.asyncio +async def test_open_page_bypasses_the_service_worker_by_default(): + """After a Wodify redeploy the app's service worker can keep serving the + old runtime to new screen code; that app throws before sending any data + action. Priming must bypass the worker -- for this tab only.""" + ws = PageWS() + s = cdp.CDPSession(ws) + s.start() + await s.open_page() + + worker = _sent(ws, "Network.setBypassServiceWorker") + assert [m["params"] for m in worker] == [{"bypass": True}] + # Scoped to the attached tab, never browser-wide. + assert worker[0]["sessionId"] == "SESS1" + # Bypass, not destroy: nothing is unregistered or cleared in the profile. + assert not [m for m in ws.sent + if any(w in m["method"].lower() for w in ("clear", "unregister", "delete"))] + await s.close() + + +@pytest.mark.asyncio +async def test_open_page_can_opt_out_of_fresh_load(): + ws = PageWS() + s = cdp.CDPSession(ws) + s.start() + await s.open_page(fresh=False) + assert not _sent(ws, "Network.setBypassServiceWorker") + await s.close() + + +@pytest.mark.asyncio +async def test_close_closes_the_tab_it_opened(): + """Every prime used to leave its tab open in the profile forever.""" + ws = PageWS() + s = cdp.CDPSession(ws) + s.start() + await s.open_page() + await s.close() + assert [m["params"] for m in _sent(ws, "Target.closeTarget")] == [{"targetId": "TAB1"}] + assert ws.closed + + +@pytest.mark.asyncio +async def test_close_without_a_page_closes_nothing(session): + s, ws = session + await s.close() + assert not _sent(ws, "Target.closeTarget") + assert ws.closed + + +@pytest.mark.asyncio +async def test_close_survives_a_failing_tab_close(): + class Failing(PageWS): + async def send(self, raw): + msg = json.loads(raw) + if msg["method"] == "Target.closeTarget": + self.sent.append(msg) + await self._out.put(json.dumps( + {"id": msg["id"], "error": {"message": "no such target"}})) + return + await super().send(raw) + + ws = Failing() + s = cdp.CDPSession(ws) + s.start() + await s.open_page() + await s.close() # must not raise + assert ws.closed diff --git a/tests/test_prime.py b/tests/test_prime.py new file mode 100644 index 0000000..b09c0ca --- /dev/null +++ b/tests/test_prime.py @@ -0,0 +1,165 @@ +"""Priming must fail loudly, and must load the app fresh. + +Background (2026-11): after a Wodify redeploy the app's service worker kept +serving the old runtime to new screen code. Every data action threw client-side +before a request was sent, so prime observed nothing, wrote a cache with an +empty action table, and every later query reported NOT PRIMED. The session was +valid the whole time. Nothing here needs a browser. +""" +from __future__ import annotations + +import json + +import pytest + +from wodify import actions, cdp, client, prime + + +def _console_error(*texts: str) -> dict: + return {"method": "Runtime.consoleAPICalled", + "params": {"type": "error", + "args": [{"type": "string", "value": t} for t in texts]}} + + +# The shape the broken app actually emitted. +STAMPED = "[2026-11-11T05:02:11.964Z]: s is not a function " +STACK = ("TypeError: s is not a function\n" + " at Controller.callServerDataSource (https://h/scripts/OutSystems.js:17:20936)\n" + " at Controller.innerCallDataAction (https://h/scripts/OutSystems.js:17:20451)") + + +def test_page_error_is_summarised_with_its_first_frame(): + errors: list[str] = [] + prime._observe_errors(_console_error(STAMPED, STACK), errors) + assert errors == ["s is not a function at Controller.callServerDataSource"] + + +def test_identical_errors_with_different_stamps_collapse(): + errors: list[str] = [] + for stamp in ("05:02:11.964", "05:02:15.717", "05:02:16.154"): + prime._observe_errors( + _console_error(f"[2026-11-11T{stamp}Z]: s is not a function ", STACK), errors) + assert len(errors) == 1 + + +def test_uncaught_exception_is_collected(): + errors: list[str] = [] + prime._observe_errors({"method": "Runtime.exceptionThrown", "params": { + "exceptionDetails": {"text": "Uncaught (in promise)", + "exception": {"description": STACK}}}}, errors) + assert errors == ["TypeError: s is not a function at Controller.callServerDataSource"] + + +def test_page_errors_are_capped(): + errors: list[str] = [] + for i in range(prime.MAX_PAGE_ERRORS + 10): + prime._observe_errors(_console_error(f"boom {i}"), errors) + assert len(errors) == prime.MAX_PAGE_ERRORS + + +def test_console_logs_and_requests_are_not_errors(): + errors: list[str] = [] + prime._observe_errors({"method": "Runtime.consoleAPICalled", "params": { + "type": "log", "args": [{"value": "Firestore Initialized"}]}}, errors) + prime._observe_errors({"method": "Network.requestWillBeSent", "params": {}}, errors) + assert errors == [] + + +# -------------------------------------------------------------------------- +# _run / prime, against a scripted session +# -------------------------------------------------------------------------- + +def _request(path: str, *, csrf: str = "T" * 28) -> dict: + body = {"versionInfo": {"moduleVersion": "MV", "apiVersion": "AV"}, + "viewName": "MainScreens.Home", "screenData": {"variables": {}}} + return {"method": "Network.requestWillBeSent", "params": {"request": { + "url": f"https://example.invalid/WodifyClient/screenservices/{path}", + "headers": {"X-CSRFToken": csrf}, + "postData": json.dumps(body)}}} + + +class ScriptedSession: + """Stands in for CDPSession: replays ``events`` on the first drain.""" + + def __init__(self, events): + self.events = list(events) + self.closed = False + + async def session_cookies(self): + return "nr1W_Theme_UI=x" + + async def open_page(self, *a, **kw): + return None + + async def navigate(self, url): + return None + + async def drain(self, seconds, handler): + events, self.events = self.events, [] + for ev in events: + handler(ev) + + async def evaluate(self, expression, *, await_promise=False): + return "MV" if "moduleversioninfo" in expression else '{"ok": true}' + + async def close(self): + self.closed = True + + +@pytest.fixture() +def scripted(monkeypatch): + def install(events): + session = ScriptedSession(events) + + async def connect(*a, **kw): + return session + monkeypatch.setattr(cdp.CDPSession, "connect", connect) + return session + return install + + +def _never_save(monkeypatch): + def boom(*a, **kw): + raise AssertionError("an empty capture must never be written to the cache") + monkeypatch.setattr(client, "save_cache", boom) + + +def test_empty_capture_from_a_crashing_page_is_refused_not_saved(scripted, monkeypatch): + """The regression. CSRF is observed (the app's bootstrap calls still fire), + no allowlisted action is, and the page is throwing.""" + session = scripted([ + _request("WodifyClient/ActionShowFeaturesAvailable"), + _console_error(STAMPED, STACK), + ]) + _never_save(monkeypatch) + with pytest.raises(RuntimeError) as err: + prime.prime() + message = str(err.value) + assert "left untouched" in message + assert "callServerDataSource" in message # names the real cause + assert "moved its endpoints" not in message # and does not guess another + assert session.closed + + +def test_empty_capture_without_page_errors_points_at_moved_endpoints(scripted, monkeypatch): + scripted([_request("WodifyClient/ActionShowFeaturesAvailable")]) + _never_save(monkeypatch) + with pytest.raises(RuntimeError, match="moved its endpoints"): + prime.prime() + + +def test_successful_capture_is_saved_and_reports_page_errors(scripted, monkeypatch, tmp_path): + scripted([_request(actions.ACTIONS["schedule"].path), _console_error("minor")]) + saved = {} + + def save(payload, path=None): + saved.update(payload) + return tmp_path / "session.json" + monkeypatch.setattr(client, "save_cache", save) + + summary = prime.prime() + assert summary["actions_captured"] == ["schedule"] + assert summary["page_errors"] == ["minor"] + # Diagnostics are for the operator, not for the credential cache. + assert "page_errors" not in saved and "walk_log" not in saved + assert actions.ACTIONS["schedule"].path in saved["actions"]