Repository navigation
Conversation
Reintroduce shared pages functionality from PR zauberzeug#5421/zauberzeug#5005. When shared=True, all visitors see and interact with the same page instance using a weakref-based client reuse mechanism. Guiderails added: - RuntimeError for app.storage.tab/client/user/browser on shared pages - RuntimeError for awaiting run_javascript on shared pages - Warnings for broadcast operations (notify, download, navigate, open) - Warning for client.ip on shared pages (returns most recent visitor) - Shared clients exempt from pruning and disconnect-deletion Co-Authored-By: Claude Opus 4.6 <[email protected]>
14 tests covering: - Basic shared page rendering - Client reuse across multiple visitors - Non-shared pages still create separate clients - Page function only runs once for shared pages - Dynamic elements visible to all visitors - Shared clients exempt from pruning - Storage guiderails (tab, client raise RuntimeError) - Awaiting run_javascript raises RuntimeError - is_shared property - Shared and non-shared pages coexist - Selenium-based screen tests Co-Authored-By: Claude Opus 4.6 <[email protected]>
- RuntimeError for client.disconnected() on shared pages (shared client is never deleted) - RuntimeError for ui.sub_pages on shared pages (navigation would affect all browsers simultaneously) - Additional tests for both guards Co-Authored-By: Claude Opus 4.6 <[email protected]>
Document all guiderails (RuntimeErrors and warnings) added for shared pages, with reasoning for each design decision. Co-Authored-By: Claude Opus 4.6 <[email protected]>
There was a problem hiding this comment.
Pull request overview
This PR introduces shared pages to NiceGUI, allowing multiple users to view and interact with the same page instance (and thus the same underlying Client) via @ui.page(..., shared=True).
Changes:
- Add
sharedsupport toui.pageand reuse a singleClientinstance across requests for that route. - Restrict/adjust APIs whose semantics become ambiguous on shared pages (e.g.,
app.storage.tab/client,ui.sub_pages, awaitingrun_javascript) and add warnings for “broadcast” actions (notify/navigate/open/download). - Add a new test suite covering core shared-page behavior.
Reviewed changes
Copilot reviewed 8 out of 8 changed files in this pull request and generated 9 comments.
Show a summary per file
| File | Description |
|---|---|
| tests/test_shared_pages.py | Adds coverage for shared-page reuse and various shared-page restrictions. |
| nicegui/page.py | Adds shared parameter and shared-client reuse shortcut in the page decorator. |
| nicegui/storage.py | Raises clearer errors when per-user/tab/client storage is used from shared pages. |
| nicegui/client.py | Adds is_shared, prevents pruning shared clients, and blocks/adjusts some client APIs on shared pages. |
| nicegui/functions/notify.py | Warn once that notifications broadcast to all browsers on shared pages. |
| nicegui/functions/navigate.py | Warn once that navigation may broadcast to all browsers on shared pages. |
| nicegui/elements/sub_pages.py | Disallows ui.sub_pages on shared pages due to global navigation effects. |
| # Shared page shortcut: reuse existing client if available | ||
| if self.shared and self._shared_client is not None and (client := self._shared_client()) is not None: | ||
| client._request = request # pylint: disable=protected-access | ||
| binding._refresh_step() # pylint: disable=protected-access | ||
| return client.build_response(request) | ||
|
|
||
| with Client(self, request=request) as client: | ||
| if self.shared: | ||
| self._shared_client = weakref.ref(client) |
There was a problem hiding this comment.
Shared-page creation/reuse is not synchronized. If two users hit the shared route concurrently while _shared_client is still None (or has been GC’d), both requests can create separate Client instances; only the last one will be stored in _shared_client, potentially leaking the other and producing inconsistent state. Consider guarding shared client creation with an asyncio.Lock (per page) or similar single-flight mechanism.
| async def delete_content() -> None: | ||
| await asyncio.sleep(self.page.resolve_reconnect_timeout()) | ||
| if self._num_connections[document_id] == 0: | ||
| self._num_connections.pop(document_id) | ||
| self._delete_tasks.pop(document_id) | ||
| await core.app.storage.close_tab(tab_id_to_close) | ||
| self.delete() | ||
| if not self.is_shared: | ||
| self.delete() |
There was a problem hiding this comment.
On shared pages, multiple browser tabs/devices connect to the same Client id. However handle_disconnect (together with has_socket_connection being based on a single tab_id) can make the client appear disconnected when any one connection drops, which can stop outbox delivery and cause subsequent socket events from still-connected browsers to be ignored. Shared clients likely need connection state derived from active sockets (e.g., _socket_to_document_id / _num_connections) and only clear “connected” state when the last connection disconnects.
| async def test_shared_page_elements_visible_to_all(create_user: Callable[[], User]) -> None: | ||
| @ui.page('/', shared=True) | ||
| def index(): | ||
| ui.label('Initial Content') | ||
| ui.button('Add Label', on_click=lambda: ui.label('Dynamic Content')) | ||
|
|
||
| user1 = create_user() | ||
| user2 = create_user() | ||
|
|
||
| await user1.open('/') | ||
| await user2.open('/') | ||
|
|
||
| user1.find('Add Label').click() | ||
| await user1.should_see('Dynamic Content') | ||
|
|
There was a problem hiding this comment.
This test is intended to verify that changes on a shared page are visible to all users, but it only asserts that user1 sees the dynamically added label. Please also assert that user2 can see the same "Dynamic Content" after user1 clicks, otherwise the broadcast behavior isn’t actually covered.
| async def test_shared_page_client_not_pruned(user: User) -> None: | ||
| @ui.page('/', shared=True) | ||
| def index(): | ||
| ui.label('Shared Page') | ||
|
|
||
| await user.open('/') | ||
| client = user.client | ||
| assert client is not None | ||
|
|
||
| # Shared clients should not be pruned even when stale | ||
| client_count_before = len(Client.instances) | ||
| Client.prune_instances(client_age_threshold=0) | ||
| client_count_after = len(Client.instances) | ||
| assert client.id in Client.instances, 'Shared client should not be pruned' | ||
| assert client_count_after == client_count_before | ||
|
|
There was a problem hiding this comment.
Given shared pages introduce multi-connection semantics, it would be valuable to add a regression test where two users open a shared page, one user disconnects/closes, and the remaining user can still trigger UI updates/events. This would catch cases where the shared client is marked disconnected too early and stops processing events or sending updates.
| :param favicon: optional relative filepath or absolute URL to a favicon (default: `None`, NiceGUI icon will be used) | ||
| :param dark: whether to use Quasar's dark mode (defaults to `dark` argument of `run` command) | ||
| :param language: language of the page (defaults to `language` argument of `run` command) | ||
| :param shared: whether all users share the same page instance (default: ``False``, *added in version 3.x.0*) |
There was a problem hiding this comment.
The docstring uses the placeholder “added in version 3.x.0”, while the rest of the codebase appears to use concrete version numbers (e.g., 3.0.0, 3.7.0). Please replace this with the actual target version for this feature (or omit the version note) to keep documentation consistent.
| :param shared: whether all users share the same page instance (default: ``False``, *added in version 3.x.0*) | |
| :param shared: whether all users share the same page instance (default: ``False``) |
| from .context import context as ctx # pylint: disable=import-outside-toplevel | ||
| if ctx.slot_stack and ctx.client.is_shared: | ||
| raise RuntimeError('app.storage.browser is not supported on shared pages because the request identity ' | ||
| 'is ambiguous when multiple browsers share the same page; ' | ||
| 'use app.storage.general instead') | ||
| request: Request | None = request_contextvar.get() |
There was a problem hiding this comment.
New behavior: app.storage.browser now raises on shared pages (when accessed from UI context). There doesn’t seem to be a test covering this restriction yet; please add one to tests/test_shared_pages.py to ensure the RuntimeError and message stay stable.
| from .context import context as ctx # pylint: disable=import-outside-toplevel | ||
| if ctx.slot_stack and ctx.client.is_shared: | ||
| raise RuntimeError('app.storage.user is not supported on shared pages because the request identity ' | ||
| 'is ambiguous when multiple browsers share the same page; ' | ||
| 'use app.storage.general instead') |
There was a problem hiding this comment.
New behavior: app.storage.user now raises on shared pages (when accessed from UI context). Please add a regression test to tests/test_shared_pages.py similar to the tab/client tests to confirm this error is raised and to prevent accidental regressions.
|
|
||
| # Shared page shortcut: reuse existing client if available | ||
| if self.shared and self._shared_client is not None and (client := self._shared_client()) is not None: | ||
| client._request = request # pylint: disable=protected-access |
There was a problem hiding this comment.
In the shared-page reuse shortcut, the incoming request is assigned to the existing client, but the new request’s scope isn’t updated with nicegui_page_path. This can cause the global 500 handler to treat errors during this request as non-page requests (re-raising instead of rendering a NiceGUI error page). Consider setting request.scope['nicegui_page_path'] = self.path (or equivalent) when reusing the shared client, mirroring Client.__init__ behavior.
| client._request = request # pylint: disable=protected-access | |
| client._request = request # pylint: disable=protected-access | |
| request.scope['nicegui_page_path'] = self.path |
| await user1.open('/') | ||
| assert call_count == 1 | ||
| await user2.open('/') | ||
| assert call_count == 1, 'Page function should only run once for shared pages' |
There was a problem hiding this comment.
Test is always true, because of this condition.
Shared Pages GuiderailsThis document describes the guiderails added for the BackgroundWhen This is fundamentally different from the default per-user pages where each visitor gets their own Guiderail CategoriesGuiderails fall into two categories:
RuntimeError Guiderails
|
- Add asyncio.Lock to prevent race conditions in shared client creation - Set nicegui_page_path in request scope when reusing shared client - Remove placeholder version number (3.x.0) from docstring - Add user2 visibility assertion in elements_visible_to_all test - Add tests for app.storage.browser and app.storage.user on shared pages - Add disconnect resilience test (shared client survives disconnect) Co-Authored-By: Claude Opus 4.6 <[email protected]>
…d Chrome (zauberzeug#5740) ### Motivation The `ubuntu-latest` runner image already ships with matched Chrome and ChromeDriver versions ([runner-images manifest](https://github.com/actions/runner-images/blob/ubuntu24/20260201.15/images/ubuntu/Ubuntu2404-Readme.md)). The third-party `nanasess/[email protected]` action is redundant and introduces a point of fragility: when Chrome auto-updates on the runner image, the action may install a mismatched or conflicting ChromeDriver version, causing test failures unrelated to any code change. This issue materialized on Feb 8, 2026, when Chrome auto-updated from `144.0.7559.96` to `144.0.7559.109` on the runner image. The update caused 4 test failures and 1 error across multiple unrelated PRs: | Test | Error | |------|-------| | `test_page::test_exception` | `AssertionError: Could not find "500"` | | `test_select::test_add_new_values[add-False-True]` | `IndexError: pop from empty list` | | `test_select::test_add_new_values[add-True-True]` | `IndexError: pop from empty list` | | `test_storage::test_missing_storage_secret` | `IndexError: pop from empty list` | | `test_page::test_exception_after_connected` | JS `RangeError: Maximum call stack size exceeded` | These failures appeared identically on two completely unrelated PRs ([#68](#68), [#71](#71)), confirming they are environment-caused, not code-caused. Upstream last ran CI on Feb 5 with Chrome `.96` (passing); the next CI run will encounter the same failures. ### Implementation Remove the `nanasess/[email protected]` step from `.github/workflows/_test.yml`. The runner image's preinstalled Chrome and ChromeDriver are used instead. This is the most maintainable approach because: - The runner image always ships a matched Chrome + ChromeDriver pair - If the preinstalled Chrome breaks, it affects the entire GitHub Actions ecosystem, guaranteeing rapid upstream fixes from GitHub/Microsoft - No third-party action to maintain, audit, or pin versions for - One fewer network fetch during CI (the action downloads ChromeDriver on every run) ### Alternatives explored Five approaches were tested on [evnchn/nicegui](https://github.com/evnchn/nicegui) to triangulate the root cause and find the best fix: | PR | Approach | Result | Trade-off | |----|----------|--------|-----------| | [#72](#72) | Pin Chrome+ChromeDriver to `.96` via `browser-actions/setup-chrome@v2` | **All 769 tests pass** | Requires manual version bumps; masks Chrome regressions | | [#73](#73) | Pin ChromeDriver only to `.96` via `nanasess` with `chromedriver-version` | **All 769 tests pass** | Same pinning burden; still depends on third-party action | | [#74](#74) | ARM64 runner (`ubuntu-24.04-arm`) + Chromium via apt | **3 failures**, 769 passed | 8% slower pytest (24m06s vs 22m18s), +93s Chromium install overhead, new platform-specific test failures (`test_upload` file path bug, `test_xterm` terminal size mismatch) | | [#75](#75) | Remove `nanasess`, use preinstalled Chrome | **All 769 tests pass** | **This approach** — zero maintenance, zero overhead | ### Timing comparison (PR #75 vs PR #74) | | PR #75 x86_64 (this approach) | PR #74 ARM64 | |---|---|---| | Chrome install | 0s (preinstalled) | 93s (apt-get) | | pytest duration | 22m 18s | 24m 06s | | Total job wall-clock | 22m 30s | 25m 56s | | Test result | **769 passed** | 3 failed, 769 passed | ### Root cause analysis - Chrome auto-updated from `144.0.7559.96` to `144.0.7559.109` between Feb 6 and Feb 8 on the `ubuntu-latest` runner image - All Python dependencies are identical across passing and failing runs (`selenium==4.40.0`, `cpython-3.10.19`) - Chromium commit log between `.97` and `.110` contains only Chrome-internal changes (contextual tasks UI, i18n, Android GPU, sandbox policy, translation, PDF, PKI metadata) — no V8, CSS, WebDriver, or networking changes - The behavioral regression in `.109` is likely in a rolled dependency (via DEPS) rather than a direct Chromium commit - Removing `nanasess` resolves the issue because the runner image's preinstalled Chrome `.109` and its matched ChromeDriver work correctly together — the problem was the version mismatch introduced by the action ### Progress - [x] I chose a meaningful title that completes the sentence: "If applied, this PR will..." - [x] The implementation is complete. - [x] If this PR addresses a security issue, it has been coordinated via the [security advisory](https://github.com/zauberzeug/nicegui/security/advisories/new) process. - [x] Pytests have been added (or are not necessary). - [x] Documentation has been added (or is not necessary). Co-authored-by: Claude Opus 4.6 <[email protected]>
### Motivation The `sqlite_database` example breaks with Tortoise ORM 1.0: ``` RuntimeError: No TortoiseContext is currently active. Use 'async with TortoiseContext() as ctx:' to create one, or call Tortoise.init() for global state. ``` Tortoise ORM 1.0 replaced global state with a `ContextVar`-based architecture. Since NiceGUI runs async `on_startup` handlers as background tasks (via `safe_invoke` / `background_tasks.create`), the `ContextVar` set by `Tortoise.init()` in the startup task never propagates to request handler tasks. Additionally, `aiosqlite` was pinned to 0.21.0 to work around [tortoise/tortoise-orm#2037](tortoise/tortoise-orm#2037), and the example was skipped in CI for Python 3.11/3.12 due to [omnilib/aiosqlite#241](omnilib/aiosqlite#241). Both issues are resolved in Tortoise ORM 1.0. ### Implementation Replace the manual `Tortoise.init()` / `close_connections()` / `on_startup` / `on_shutdown` boilerplate with `register_tortoise()` from `tortoise.contrib.fastapi`. Since NiceGUI's `app` is a FastAPI subclass, this hooks directly into the app's lifespan and uses `_enable_global_fallback=True` internally, making the Tortoise context available across all async tasks. This also removes the `aiosqlite` pin and the CI skip for Python 3.11/3.12. ### Progress - [x] I chose a meaningful title that completes the sentence: "If applied, this PR will..." - [x] The implementation is complete. - [x] This is not a security issue. - [x] Pytests have been added (or are not necessary). - [x] Documentation has been added (or is not necessary).
) ### Motivation Sponsor images on the main page were passed as local file `Path` objects to `ui.interactive_image()`, causing NiceGUI to serve them via auto-generated paths like `/_nicegui/auto/static/<hash>/lechler-gmbh.webp`. This had two problems: 1. **Broken images across server instances:** The hash in the auto path is instance-specific. Since nicegui.io runs multiple server instances, a client could receive HTML from one instance but have the image request routed to another instance where that hash doesn't exist, causing the image to fail to load. 2. **Poor caching / Lighthouse score:** The auto path bypasses the `DocsSetCacheControlMiddleware` that sets cache headers for `/static/` paths. Using the static URL ensures sponsor images are strongly cached. ### Implementation Use the URL path `/static/sponsors/...` (served by `app.add_static_files`) instead of local file `Path` objects. The local path is still used for the `exists()` check to decide between single vs light/dark image variants. ### Progress - [x] I chose a meaningful title that completes the sentence: "If applied, this PR will..." - [x] The implementation is complete. - [x] If this PR addresses a security issue, it has been coordinated via the [security advisory](https://github.com/zauberzeug/nicegui/security/advisories/new) process. - [x] Pytests have been added (or are not necessary). - [x] Documentation has been added (or is not necessary). Co-authored-by: Claude Opus 4.6 <[email protected]>
…eug#5729) ### Motivation Starting a new Chrome browser for each test using the `Screen` fixture is slow. By reusing the same browser session across all tests, we can significantly reduce test execution time. ### Implementation - Made `nicegui_driver` and `nicegui_chrome_options` fixtures session-scoped so the browser is started once and reused - Added `_reset_browser_state()` helper to clean up browser state between tests (closes extra tabs, navigates to about:blank, clears browser logs) - Updated `Screen.close()` to navigate to about:blank instead of closing the last tab, which would invalidate the session-scoped driver - Consolidated `capabilities` fixture into `nicegui_chrome_options` (moved logging prefs to `set_capability()`) ### Progress - [x] I chose a meaningful title that completes the sentence: "If applied, this PR will..." - [x] The implementation is complete. - [x] If this PR addresses a security issue, it has been coordinated via the [security advisory](https://github.com/zauberzeug/nicegui/security/advisories/new) process. - [x] Pytests are not necessary. - [x] Documentation is not necessary. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.5 <[email protected]> Co-authored-by: Falko Schindler <[email protected]>
### Motivation The bundled Mermaid 11.12.0 includes `dagre-d3-es` 7.0.9, which is affected by a prototype pollution vulnerability (CVE-2025-57347). This was reported privately by @henriknoren via GHSA-mp6h-mc3x-8v69. But since it is in an upstream dependency, not in NiceGUI itself, and is already public knowledge, we decided to fix it in a public PR rather than a GHSA. ### Implementation Bump `mermaid` from 11.12.0 to 11.12.2 and rebuild the bundle. ### Progress - [x] I chose a meaningful title that completes the sentence: "If applied, this PR will..." - [x] The implementation is complete. - [x] Since this PR addresses a security issue, it has been coordinated via the [security advisory](https://github.com/zauberzeug/nicegui/security/advisories/new) process. - [x] Pytests have been added (or are not necessary). - [x] Documentation has been added (or is not necessary).
### Motivation Claude Code doesn't read `AGENTS.md` natively — it only loads `CLAUDE.md` on startup. Two earlier PRs explored ways to bridge this gap: - **zauberzeug#5720** — symlink (`ln -s AGENTS.md CLAUDE.md`) — closed because symlinks [break on Windows](zauberzeug#5720 (comment)) - **zauberzeug#5722** — full copy with pre-commit sync hook — works but duplicates the entire file and adds a Python hook Inspired by [this recommendation](anthropics/claude-code#6235 (comment)). ### Implementation A minimal `CLAUDE.md` containing just `@AGENTS.md`. Claude Code's native `@file` directive inlines the referenced file into the system prompt at session start. This keeps `AGENTS.md` as the single source of truth — no duplication, no sync hooks, no symlinks. Works cross-platform. Supersedes zauberzeug#5720 and zauberzeug#5722. ### Progress - [x] I chose a meaningful title that completes the sentence: "If applied, this PR will..." - [x] The implementation is complete. - [x] If this PR addresses a security issue, it has been coordinated via the [security advisory](https://github.com/zauberzeug/nicegui/security/advisories/new) process. - [x] Pytests have been added (or are not necessary). - [x] Documentation has been added (or is not necessary). Co-authored-by: Claude Opus 4.6 <[email protected]>
### Motivation This PR addresses multiple Dependabot security alerts by bumping vulnerable dependencies to their patched versions: - [#67](https://github.com/zauberzeug/nicegui/security/dependabot/67) - `lodash-es` for vanilla-jsoneditor (json_editor element) - [#68](https://github.com/zauberzeug/nicegui/security/dependabot/68) - `fonttools` for matplotlib - [#72](https://github.com/zauberzeug/nicegui/security/dependabot/72) - `aiohttp` ≥3.13.3 - [#80](https://github.com/zauberzeug/nicegui/security/dependabot/80) - `urllib3` ≥2.6.3 - [#83](https://github.com/zauberzeug/nicegui/security/dependabot/83) - `orjson` ≥3.11.5 ### Implementation - Updated pyproject.toml with new minimum versions for `aiohttp`, `orjson`, `urllib3`, and added `fonttools` to the matplotlib extra - Pinned `lodash-es` ^4.17.23 in package.json for two elements to override vulnerable transitive dependencies - Regenerated package-lock.json files and uv.lock (`npm run build` didn't change anything in the generated bundles) ### Progress - [x] I chose a meaningful title that completes the sentence: "If applied, this PR will..." - [x] The implementation is complete. - [x] This is not a security issue in NiceGUI itself, but updating dependencies with already-public CVEs. - [x] Pytests are not necessary. - [x] Documentation is not necessary.
Motivation
Implementation
Progress