Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Harden evaluate_fetch against execution-context-destroyed during navigation (#6549)

Daniel Han821cfe561a5d
diff --git a/tests/studio/_playwright_robust.py b/tests/studio/_playwright_robust.py
index 774665581da..a4590066d4f 100644
--- a/tests/studio/_playwright_robust.py
+++ b/tests/studio/_playwright_robust.py
@@ -318,11 +318,75 @@ def dump_diagnostics(
info(f"diagnostics: json sidecar {name} failed: {exc}")
+# Markers for the transient Playwright error raised when a navigation, reload, or
+# auth refresh destroys the JS execution context while an evaluate is in flight.
+# Stored lowercase and matched against a lowercased message: Playwright varies the
+# casing across versions ("Frame was detached" vs "frame was detached"), so a
+# case-sensitive check would miss the very races this is meant to catch.
+_CONTEXT_LOST_MARKERS = (
+ "execution context was destroyed",
+ "context with specified id",
+ "frame was detached",
+ "target closed",
+ "target page, context or browser has been closed",
+ "execution context is not available",
+)
+
+# HTTP methods whose replay is side-effect-free, so an evaluate_fetch hit by a
+# mid-call context loss may safely re-run. Mutating methods are excluded by
+# default (see evaluate_fetch) to avoid double-applying an already-sent request.
+_IDEMPOTENT_METHODS = frozenset({"GET", "HEAD", "OPTIONS"})
+
+
+# Robust page/locator.evaluate.
+# A navigation mid-evaluate destroys the execution context and raises at the Python
+# level (not a JS result), which would crash the script. Retry that transient class
+# within a small budget, settling the page first; non-transient or persistent errors
+# still propagate.
+def robust_evaluate(
+ target: Any,
+ expression: str,
+ arg: Any = None,
+ *,
+ retries: int = 2,
+ backoff_ms: int = 250,
+) -> Any:
+ """`target.evaluate(expression, arg)` for a Page or Locator, retried when a
+ concurrent navigation destroys the execution context. Re-raises on a
+ non-transient error or after the final attempt."""
+ page = target if hasattr(target, "wait_for_load_state") else getattr(target, "page", None)
+ attempts = max(1, int(retries) + 1)
+ for attempt in range(attempts):
+ try:
+ return target.evaluate(expression, arg)
+ except Exception as exc:
+ exc_msg = str(exc).lower()
+ transient = any(s in exc_msg for s in _CONTEXT_LOST_MARKERS)
+ if not transient or attempt == attempts - 1:
+ raise
+ try:
+ sys.stderr.write(
+ f"[robust_evaluate] execution context lost "
+ f"({attempt + 1}/{attempts}); settling + retrying\n"
+ )
+ sys.stderr.flush()
+ except Exception:
+ pass
+ if page is not None:
+ try:
+ page.wait_for_load_state("domcontentloaded", timeout = 10_000)
+ except Exception:
+ pass
+ time.sleep((backoff_ms * (2**attempt)) / 1000.0)
+
+
# Bounded in-page fetch.
# `page.evaluate(...)` has no `timeout=`, so a stuck fetch hangs the script until
# the runner timeout (run 25696797934 / PR #5387 burned 27+ min). evaluate_fetch
# wraps the fetch in an AbortController.signal so the JS side always resolves --
# real response, or synthetic `{status: 0, error: "AbortError..."}` after timeout_ms.
+# It also retries the evaluate itself when a navigation destroys the execution
+# context mid-call (a transient Playwright race, not a real fetch failure).
def evaluate_fetch(
page: Any,
url: str,
@@ -333,11 +397,22 @@ def evaluate_fetch(
timeout_ms: int = 20_000,
transport_retries: int = 2,
transport_backoff_ms: int = 250,
+ retry_on_context_loss: bool | None = None,
) -> dict[str, Any]:
"""Run `fetch(url, opts)` in the page with an AbortSignal deadline; returns
`{"status", "body", "error"}` (status==0 + AbortError on timeout). Treat
status==0 or non-None error as transport failure. `body` may be str (verbatim)
- or dict/list (JSON-encoded); pass headers explicitly for Content-Type/Auth."""
+ or dict/list (JSON-encoded); pass headers explicitly for Content-Type/Auth.
+
+ `retry_on_context_loss` controls whether a navigation that destroys the JS
+ context mid-call replays the in-page fetch. The request may have already
+ reached the backend before the context died, so replaying a mutating call is
+ unsafe: a spent single-use POST /api/auth/refresh comes back 401, and a
+ duplicate POST /api/inference/load that lands while the first is still in
+ `loading_models` is rejected (the backend returns False -> 500) even though
+ the original load succeeds. Default (None) therefore retries only idempotent
+ reads (GET/HEAD/OPTIONS) and never replays a mutating method; pass an explicit
+ bool to override per call. Context loss on a non-retried call propagates."""
body_arg: str | None
if body is None:
body_arg = None
@@ -383,8 +458,18 @@ def evaluate_fetch(
# fetch" after auth rotation) retries after backoff to evict the dead socket.
last: dict[str, Any] | None = None
attempts = max(1, int(transport_retries) + 1)
+ # Replay the in-page evaluate on a context loss only for idempotent reads;
+ # mutating methods (POST/PUT/PATCH/DELETE) may have already hit the backend,
+ # so retrying would re-send them (see docstring). Honor an explicit override.
+ if retry_on_context_loss is None:
+ retry_on_context_loss = method.upper() in _IDEMPOTENT_METHODS
+ ctx_retries = 2 if retry_on_context_loss else 0
for attempt in range(attempts):
- result = page.evaluate(js, payload)
+ # robust_evaluate retries the evaluate when a navigation destroys the
+ # execution context mid-call; the loop here retries transport failures.
+ result = robust_evaluate(
+ page, js, payload, retries = ctx_retries, backoff_ms = transport_backoff_ms
+ )
last = result
try:
status = int(result.get("status") or 0)
diff --git a/tests/studio/playwright_chat_ui.py b/tests/studio/playwright_chat_ui.py
index f0a928982dd..54e9ca2f460 100644
--- a/tests/studio/playwright_chat_ui.py
+++ b/tests/studio/playwright_chat_ui.py
@@ -27,6 +27,7 @@ from _playwright_robust import ( # noqa: E402
is_benign_console_error,
is_benign_page_error,
recover_or_replace_page,
+ robust_evaluate,
wait_for_health,
)
@@ -356,12 +357,14 @@ with sync_playwright() as p:
# /api/models/list and /api/inference/load need a bearer; the
# frontend stores it under "unsloth_auth_token" (auth/session.ts).
- token = page.evaluate(
+ token = robust_evaluate(
+ page,
"() => localStorage.getItem('unsloth_auth_token')",
)
if not token:
# Fall back: exchange the refresh token via /api/auth/refresh.
- refresh_token = page.evaluate(
+ refresh_token = robust_evaluate(
+ page,
"() => localStorage.getItem('unsloth_auth_refresh_token')",
)
if refresh_token:
@@ -450,7 +453,7 @@ with sync_playwright() as p:
if load_resp.get("error"):
fail(f"/api/inference/load wedged: {load_resp['error']!r}")
if load_resp["status"] != 200:
- fail(f"/api/inference/load returned {load_resp['status']}: " f"{load_resp.get('body')!r}")
+ fail(f"/api/inference/load returned {load_resp['status']}: {load_resp.get('body')!r}")
info(f"loaded model: {(load_resp['body'] or {}).get('display_name')}")
# Studio caches model state in zustand; reload so the composer picks
@@ -670,7 +673,7 @@ with sync_playwright() as p:
for feature in ("thinking", "web search", "code execution"):
# Match whichever of "Disable X" / "Enable X" is rendered.
toggle = page.locator(
- f'button[aria-label="Disable {feature}"], ' f'button[aria-label="Enable {feature}"]'
+ f'button[aria-label="Disable {feature}"], button[aria-label="Enable {feature}"]'
).first
if toggle.count() == 0:
info(f"toggle '{feature}' not present on this layout")
@@ -685,7 +688,7 @@ with sync_playwright() as p:
page.wait_for_timeout(200)
after = (
page.locator(
- f'button[aria-label="Disable {feature}"], ' f'button[aria-label="Enable {feature}"]'
+ f'button[aria-label="Disable {feature}"], button[aria-label="Enable {feature}"]'
).first.get_attribute("aria-label")
or ""
)
@@ -696,7 +699,7 @@ with sync_playwright() as p:
# Flip back so test state is unchanged.
try:
page.locator(
- f'button[aria-label="Disable {feature}"], ' f'button[aria-label="Enable {feature}"]'
+ f'button[aria-label="Disable {feature}"], button[aria-label="Enable {feature}"]'
).first.click()
except Exception:
pass
@@ -773,9 +776,7 @@ with sync_playwright() as p:
acct.click(force = True)
except Exception as exc:
if attempt == 1:
- soft_fail(
- f"theme cycle {cycle + 1}: account-menu click failed " f"({exc!r})"
- )
+ soft_fail(f"theme cycle {cycle + 1}: account-menu click failed ({exc!r})")
continue
try:
page.wait_for_selector(
@@ -819,9 +820,7 @@ with sync_playwright() as p:
page.wait_for_timeout(200)
if click_err is not None:
page.keyboard.press("Escape")
- soft_fail(
- f"theme cycle {cycle + 1}: theme menuitem click failed " f"({click_err!r})"
- )
+ soft_fail(f"theme cycle {cycle + 1}: theme menuitem click failed ({click_err!r})")
break
# Settle. The ".dark" class on <html> is the ground truth
# (theme-store toggles only that); don't gate on ".light".
@@ -892,8 +891,7 @@ with sync_playwright() as p:
page.wait_for_timeout(800)
if expected_url_pat and not re.search(expected_url_pat, page.url):
soft_fail(
- f"clicking '{label}' didn't change url to /{expected_url_pat}; "
- f"current: {page.url}"
+ f"clicking '{label}' didn't change url to /{expected_url_pat}; current: {page.url}"
)
return False
return True
@@ -1061,7 +1059,7 @@ with sync_playwright() as p:
info(f"recent-thread click {i} failed: {_click_err!s}")
continue
if not clicked_recent:
- soft_fail(f"no Recents entry was clickable within 30s deadline " f"(n_threads={n_threads})")
+ soft_fail(f"no Recents entry was clickable within 30s deadline (n_threads={n_threads})")
# Back to chat.
page.goto(f"{BASE}/chat")
composer = page.locator('textarea[aria-label="Message input"]')
@@ -1283,8 +1281,7 @@ with sync_playwright() as p:
if real_errors:
fail(f"{len(real_errors)} non-benign pageerror events")
info(
- f"console.error events: {len(console_errors)} total "
- f"({len(real_console_errors)} non-benign)"
+ f"console.error events: {len(console_errors)} total ({len(real_console_errors)} non-benign)"
)
info("PASS comprehensive UI flow")
diff --git a/tests/studio/playwright_extra_ui.py b/tests/studio/playwright_extra_ui.py
index a23e182114a..304de7a9af6 100644
--- a/tests/studio/playwright_extra_ui.py
+++ b/tests/studio/playwright_extra_ui.py
@@ -23,6 +23,7 @@ from _playwright_robust import ( # noqa: E402
install_wall_clock_watchdog,
is_benign_page_error,
recover_or_replace_page,
+ robust_evaluate,
wait_for_health,
)
@@ -147,8 +148,7 @@ with sync_playwright() as p:
)
if status is not None and status >= 400:
raise AssertionError(
- f"change-password POST returned {status}; "
- f"see page_errors={page_errors[:1]!r}"
+ f"change-password POST returned {status}; see page_errors={page_errors[:1]!r}"
)
form_err = None
break
@@ -225,7 +225,7 @@ with sync_playwright() as p:
raise last_err
shoot("01-chat-loaded")
- token = page.evaluate("() => localStorage.getItem('unsloth_auth_token')")
+ token = robust_evaluate(page, "() => localStorage.getItem('unsloth_auth_token')")
if not token:
fail("no access token after change-password")
sys.exit(1)