From 22016871b99f00e5928177f7a333774b53643c2c Mon Sep 17 00:00:00 2001 From: Alajmah <55954113+Alajmah@users.noreply.github.com> Date: Fri, 13 Nov 2026 03:48:48 +0300 Subject: [PATCH 01/21] fix(navigation): fail closed on unverified fresh-chat route and composer --- src/chatgpt_web2api/cdp_driver.py | 135 ++++++++++++++++++++++-------- 1 file changed, 98 insertions(+), 37 deletions(-) diff --git a/src/chatgpt_web2api/cdp_driver.py b/src/chatgpt_web2api/cdp_driver.py index 3bc3eae4..9c06fe4b 100644 --- a/src/chatgpt_web2api/cdp_driver.py +++ b/src/chatgpt_web2api/cdp_driver.py @@ -1209,53 +1209,114 @@ async def select_model(self, slug: str) -> bool: # ── Navigation ──────────────────────────────────────────── + @staticmethod + def _is_url_at_new_chat(url: str, gizmo_id: str | None = None) -> bool: + """Require the exact HTTPS ChatGPT origin and the requested fresh route. + + A composer's presence on /c/{id}, a different project, or a host + merely containing 'chatgpt.com' must never qualify a new chat. + Query parameters and a trailing slash may be normalized by the SPA. + """ + if not url: + return False + try: + parsed = urllib.parse.urlparse(url) + except ValueError: + return False + if parsed.scheme != "https" or parsed.netloc.lower() != "chatgpt.com": + return False + expected = ( + f"/g/{urllib.parse.quote(gizmo_id, safe='')}/project" + if gizmo_id else "/" + ) + return parsed.path.rstrip("/") == expected.rstrip("/") + async def navigate_new_chat(self, gizmo_id: str = None) -> None: - """Navigate to a fresh chat. Optionally scope to a project gizmo.""" + """Navigate to a verified, idle fresh-chat composer or fail closed. + + An old conversation ID must not survive a failed new-chat navigation. + A usable editor and the exact requested route are verified together; + an in-progress generation (Stop visible) is not send-ready. A second + probe after a short settle detects immediate SPA displacement. + """ + # Clear stale continuation state BEFORE any navigation or probe can fail. + self._current_conv_id = None if gizmo_id: - url = f"https://chatgpt.com/g/{gizmo_id}/project" + url = f"https://chatgpt.com/g/{urllib.parse.quote(gizmo_id, safe='')}/project" else: - # The bare ``chatgpt.com/`` home shell renders only the hidden - # fallback textarea (``name=prompt-textarea``, no id, not visible), - # so neither COMPOSER_SELECTOR nor COMPOSER_FALLBACK_SELECTOR matches - # and type_message fails with "No composer found". The - # ``?model=auto`` query triggers the SPA to render the real - # ProseMirror composer reliably. Verified live: bare home → no - # composer after 20s; ``?model=auto`` → composer present. + # The bare home shell may render only a hidden fallback textarea; + # ?model=auto has been observed to hydrate the real composer. url = "https://chatgpt.com/?model=auto" logger.info("Navigate: %s", url) - await self._cdp("Page.navigate", {"url": url}) + navigation = await self._cdp("Page.navigate", {"url": url}) + if isinstance(navigation, dict) and navigation.get("errorText"): + raise SendReadinessError( + f"Fresh chat navigation rejected: {navigation['errorText']}" + ) await asyncio.sleep(2) - # Wait for the composer. The new composer is a contenteditable - # ProseMirror div (#prompt-textarea is now a hidden fallback); - # COMPOSER_SELECTOR matches the real textbox, with the legacy - # textarea as a last resort for older deployments. - for _ in range(30): - result = await self._js( - "(function() {" - " return JSON.stringify({" - f" ready: !!document.querySelector('{COMPOSER_SELECTOR}') || !!document.querySelector('{COMPOSER_FALLBACK_SELECTOR}')," - " url: location.href" - " });" - "})()" - ) + # This probe is read-only. In particular, never try a submit-button + # fallback to infer readiness: the same button can become Stop while + # a foreign tab is generating. + probe_js = ( + "(function(){" + " function visible(el) {" + " return !!el && el.getClientRects().length > 0 &&" + " !el.disabled && el.getAttribute('aria-disabled') !== 'true';" + " }" + f" var composer = document.querySelector('{COMPOSER_SELECTOR}')" + f" || document.querySelector('{COMPOSER_FALLBACK_SELECTOR}');" + ' var stop = document.querySelector(\'[data-testid="stop-button"], ' + 'button[aria-label*="Stop" i]\');' + " return JSON.stringify({" + " url: location.href, ready_state: document.readyState," + " composer: visible(composer), stop_present: visible(stop)" + " });" + "})()" + ) + last_state: dict | None = None + + def is_ready(raw: str) -> bool: + nonlocal last_state try: - state = json.loads(result) - if state.get("ready"): - actual_url = state.get("url", "") - # #14: verify we actually landed on chatgpt.com, not an - # error/recovery page that happens to have a textarea. - if "chatgpt.com" not in actual_url: - raise RuntimeError(f"Navigation landed on unexpected URL: {actual_url}") - logger.info("Page ready: %s", actual_url) - break - except (json.JSONDecodeError, TypeError): - pass + state = json.loads(raw) + except (ValueError, TypeError): + return False + if not isinstance(state, dict): + return False + last_state = state + return ( + self._is_url_at_new_chat(state.get("url", ""), gizmo_id) + and state.get("ready_state") == "complete" + and state.get("composer") is True + and state.get("stop_present") is False + ) + + for _ in range(30): + if is_ready(await self._js(probe_js)): + await asyncio.sleep(0.25) + if is_ready(await self._js(probe_js)): + logger.info("Fresh chat ready: %s", last_state.get("url")) + return await asyncio.sleep(0.5) - # Settle time for sentinel init - await asyncio.sleep(2) - self._current_conv_id = None + if last_state is None: + stage = "no readable readiness probes" + elif not self._is_url_at_new_chat(last_state.get("url", ""), gizmo_id): + stage = "wrong fresh-chat route" + elif last_state.get("stop_present") is True: + stage = "generation active (Stop visible)" + elif last_state.get("ready_state") != "complete": + stage = "document not ready" + elif last_state.get("composer") is not True: + stage = "usable composer absent" + else: + stage = "readiness not stable" + if self._breakers: + self._breakers.record_failure(BreakerKind.COMPOSER_SEND_READINESS) + raise SendReadinessError( + f"Fresh chat navigation failed closed after readiness polling: {stage}" + ) async def _has_composer(self) -> bool: """Is a send-capable composer present on the live tab? From 60687f3c98d52a580a7e288413c8ec4e32a4a918 Mon Sep 17 00:00:00 2001 From: Alajmah <55954113+Alajmah@users.noreply.github.com> Date: Fri, 13 Nov 2026 03:49:42 +0300 Subject: [PATCH 02/21] fix(composer): scope Send to visible form and never select Stop as fallback --- src/chatgpt_web2api/chatgpt_dom.py | 72 ++++++++++++++++-------------- 1 file changed, 38 insertions(+), 34 deletions(-) diff --git a/src/chatgpt_web2api/chatgpt_dom.py b/src/chatgpt_web2api/chatgpt_dom.py index fc76f168..36289778 100644 --- a/src/chatgpt_web2api/chatgpt_dom.py +++ b/src/chatgpt_web2api/chatgpt_dom.py @@ -84,16 +84,9 @@ # the legacy testid for older deployments. SEND_BUTTON_SELECTOR = 'button[aria-label*="Send" i]:not([data-testid="stop-button"])' SEND_BUTTON_FALLBACK_SELECTOR = 'button[data-testid="send-button"]' -# P2.5: broader fallback — a submit-type button inside the COMPOSER FORM -# (scoped to the form containing #prompt-textarea, not page-global, to avoid -# hitting login/search/feedback forms if the page is displaced). If ChatGPT -# changes the aria-label (selector drift), a submit-type button inside the -# composer form is still the send affordance. This is the LAST resort. -SEND_BUTTON_BROAD_SELECTOR = ( - 'form:has(#prompt-textarea) button[type="submit"],' - 'form:has(.ProseMirror) button[type="submit"]' -) - +# No type=submit fallback: during generation the only submit-like control +# may be Stop. A widened fallback could cancel a foreign in-progress turn. +# An unknown send control must fail closed until its semantics are verified. # Send-button readiness poll. After a prior send completes (or under parallel # mode, where the MutationLock releases the instant a send finishes), ChatGPT's # composer can take several seconds to re-enable the send button — the composer @@ -421,29 +414,42 @@ async def _verify_composer_text(self, selector: str, expected: str) -> bool: return canon_actual == canon_expected or canon_actual == canon_expected + "\n" async def click_send(self) -> None: - """Click the send button via JS MouseEvent sequence. - - The new composer has no ``data-testid="send-button"``; its send - affordance is the submit ``