"""Keep BrowserGym's synchronous Playwright connection local to each invocation.""" from contextlib import contextmanager @contextmanager def browser_session(): """Create and close Playwright in the worker that actually uses the browser. BrowserGym caches a global connection. ZeroGPU workers must not reuse a connection inherited from another process or a previous Gradio thread. Callers serialize browser work because BrowserGym's cache is process-global. """ import browsergym.core from playwright.sync_api import sync_playwright # An inherited connection belongs to its original loop: do not call stop on it. browsergym.core._set_global_playwright(None) with sync_playwright() as playwright: browsergym.core._set_global_playwright(playwright) try: yield finally: browsergym.core._set_global_playwright(None)