Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(show): serve shared vendor via proxy; retire per-session dep re-sharing (#537)

Call White9126ee725a15
diff --git a/core/show_runtime.py b/core/show_runtime.py
index 6dde4e5a4..cbccd6138 100644
--- a/core/show_runtime.py
+++ b/core/show_runtime.py
@@ -1071,9 +1071,8 @@ def _show_runtime_prewarm_runtime_path(
if raw_path.startswith(prefix):
asset_path = raw_path[len(prefix):]
return _join_show_runtime_prewarm_path(runtime_path, asset_path, separator, query)
- if raw_path.startswith("/_show-runtime/deps/"):
- asset_path = raw_path.lstrip("/")
- return _join_show_runtime_prewarm_path(runtime_path, asset_path, separator, query)
+ # The shared vendor bundle (`/_show-runtime/vendor/...`) is session-independent and
+ # the runtime warms it itself, so it is intentionally not prewarmed per session here.
if raw_path.startswith("/src/") or raw_path.startswith("/@") or raw_path.startswith("/node_modules/"):
return _join_show_runtime_prewarm_path(runtime_path, raw_path.lstrip("/"), separator, query)
if raw_path.startswith("./"):
diff --git a/docs/plans/show-runtime-dependency-architecture.md b/docs/plans/show-runtime-dependency-architecture.md
new file mode 100644
index 000000000..2fdeee4a6
--- /dev/null
+++ b/docs/plans/show-runtime-dependency-architecture.md
@@ -0,0 +1,55 @@
+# Show Runtime Dependencies — Radical Redesign (vendor externalization + per-session deps)
+
+Status: **locked — implementing** · Date: 2026-06-09
+Repos: `vibe-show-runtime` (Node runtime) + `avibe` (Python serving)
+Branches: `vibe-show-runtime@feat/vendor-prebuild` (from `origin/main`, post-#19) · `avibe@feat/show-vendor-deps` (from `origin/master`)
+
+## Decisions (locked by Alex)
+1. **Radical, no historical compatibility.** Retire the existing `/_show-runtime/deps/` registry + import-rewriting + `no-store` band-aid entirely. **No fallback code paths.**
+2. **Shared deps are externalized**, served from ONE unified public vendor URL and referenced by every Show Page via a browser **import map**. Shared deps are **never** copied/linked under a session dir.
+3. **v1: a single, runtime-provided React** (and provided toolkit). No per-session React-version override in v1 (architecture leaves room to add later). Per-session **extra** deps are allowed, **no gating / no limits**.
+4. Build on the runtime's current `main` (which already includes #19's shared cache + source scanner + `dependencySignature`); the old quick-fix branch `fix/show-immutable-cache-clobber` is abandoned (never pushed).
+
+## Why the old approach was awkward (root cause, verified)
+- Deployed runtime (**#15**) keyed Vite's `cacheDir` by **sessionId** → every session re-optimized the *same* shared `node_modules` into its own dir → per-session chunk hashes for identical bytes.
+- The Python layer then built an indirection (`/_show-runtime/deps/r9-<v>/<name>` + in-memory registry + import rewriting) purely to *re-share* those per-session URLs, and could only mark them `no-store` (a single public URL could map to different sessions' bytes → the cross-session poisoning [P1]).
+- **#19 (already in `main`, not yet deployed)** removed sessionId from the cache key (shared, signature-keyed cache), pinned `optimizeDeps.include`, and added a source-import scanner + `dependencySignature`. This already fixes the per-session divergence for the common case — but still relies on per-session Vite optimization of the vendor set, and the Python band-aid still exists.
+
+## Target architecture (3 tiers)
+| Tier | What | URL | Cache | Shared? |
+| --- | --- | --- | --- | --- |
+| **Vendor** | react, react-dom/client, react/jsx-runtime, `@avibe/show-ui/*`, lucide, framer-motion, … | `/_show-runtime/vendor/<runtimeVer>/<file>` | `immutable` 1y | ✅ all sessions/pages |
+| **Per-session extras** | a page's own installed npm deps (optional) | `/show/<id>/…` (that session's Vite) | `immutable`/ETag, per dep-set signature | ✅ only same extras |
+| **App code** | App.tsx + local files | `/show/<id>/app/…` | `no-store`/short (dev, HMR) | ❌ per session |
+
+- **Browser import map** (injected into each Show Page HTML server-side) maps bare specifiers (`react`, `@avibe/show-ui/`, …) → the vendor URLs.
+- Each session's Vite **externalizes** the vendor specifiers (a resolve plugin leaves them bare for the import map) → it only optimizes/serves the app's own code + that session's extras. React stays a singleton (everyone resolves to the one vendor React; `resolve.dedupe`).
+- Vendor is **built once per runtime version** at install/prepare time; the runtime install dir is already content-addressed (`versions/<sha>/…`) → a stable, version-keyed vendor URL. Runtime upgrade → new vendor URL → import map points to it on next load. **No per-session maintenance, nothing goes stale.**
+
+## Implementation stages
+### Runtime (`vibe-show-runtime`) — PR #1
+- **R-A. Vendor pre-build** (CLI, e.g. `vibe-show-runtime build-vendor`): bundle `defaultOptimizeDepsInclude(...)` (the provided set) into content-hashed ESM under `<runtime>/vendor/`, emit a manifest `{specifier → /…/<file>}`. One react instance. Runs at install/prepare.
+- **R-B. Dev externalization plugin**: resolve plugin in `warmSession`'s `viteConfig` that marks vendor specifiers external (leave bare) so the per-session Vite no longer optimizes them; drop them from `optimizeDeps.include` (keep only the app's `extraBareImports` that are NOT provided). `resolve.dedupe` for react/react-dom.
+- **R-C. Per-session install**: optional per-session `package.json`; install extras under the session dir (or a session-scoped store); widen `server.fs.allow`; the existing `dependencySignature` already keys their cache. Extras' `react` import → vendor (externalized).
+- Expose the vendor dir + manifest path so the Python side can serve/inject.
+
+### avibe (`avibe`) — PR #2 (depends on a runtime release with the above)
+- **A-A. Serve vendor**: `/_show-runtime/vendor/<runtimeVer>/<file>` → static, `immutable`. Serve the manifest.
+- **A-B. Inject import map**: into each Show Page document (extend `_inject_show_runtime_config` / `_show_page_runtime_response`), built from the vendor manifest for the active runtime version.
+- **A-C. Retire the band-aid (no fallback)**: delete `_should_redirect_to_public_show_runtime_dep`, `_register_public_show_runtime_dep`, the `/_show-runtime/deps/<v>/<name>` route, the sibling/private/dep rewriters, the `_SHOW_RUNTIME_PUBLIC_DEP_REGISTRY`, and the `no-store`/`_strip_mutated_*` cache dance for these. Keep only what the new model needs.
+- `core/show_runtime.py`: trigger vendor pre-build at `prepare()`; per-session install path.
+
+### Validation & ship
+- Unit/contract tests both repos (vendor manifest, externalization leaves bare imports, import-map injection, per-session extras isolation, vendor immutable headers).
+- **Local Incus regression**: real Show Page load — verify vendor served once + `immutable` + shared across sessions; verify a per-session extra dep works; verify HMR on app code still works. **Validate before cutover** (this is sequencing safety, not a code fallback).
+- Codex review each diff. **PR order: runtime first → release → avibe.** Review watches.
+
+## Key risks
+- **React singleton** — enforce dedupe + import map everywhere (incl. extras). #1 correctness risk.
+- **Dev externalization** is a small custom resolve plugin (not a config flag) — verify HMR + error overlay still behave.
+- **Per-session `npm install`** of agent-authored deps — no gating per decision; keep `server.fs.allow` scoped; watch resource use.
+- **Cross-repo sequencing** — runtime must ship before avibe can consume the vendor/manifest; regression-validate before cutover.
+
+## Open (non-blocking) follow-ups
+- Per-session React version (deferred from v1).
+- Whether to prune old per-session vite-cache dirs left by #15/#19 on upgrade.
diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.py
index 57d85029c..03f976359 100644
--- a/tests/test_ui_show_pages.py
+++ b/tests/test_ui_show_pages.py
@@ -22,13 +22,6 @@ from vibe import remote_access
from vibe.ui_server import app
[email protected](autouse=True)
-def _clear_show_runtime_public_dep_registry():
- from vibe import ui_server
-
- ui_server._SHOW_RUNTIME_PUBLIC_DEP_REGISTRY.clear()
-
-
class _FakeShowRuntimeManager:
def __init__(
self,
@@ -338,802 +331,41 @@ def test_private_show_page_does_not_inject_runtime_event_config_into_ranged_html
assert response.status_code == 206
assert response.content == body
- assert "globalThis.__AVIBE_SHOW__" not in response.content.decode("utf-8")
- assert response.headers["content-range"] == "bytes 0-63/128"
- assert manager.calls[0][2]["range"] == "bytes=0-63"
-
-
-def test_private_show_page_runtime_config_overrides_existing_client_defaults(monkeypatch, tmp_path):
- monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
- _save_config(tmp_path)
- _create_show_page("ses123", "private")
- monkeypatch.setattr("vibe.ui_server.show_event_write_token", lambda session_id: f"token-{session_id}")
- manager = _FakeShowRuntimeManager(
- body=b'<!doctype html><script>globalThis.__AVIBE_SHOW__={eventsPath:"runtime-only"}</script><script type="module" src="/src/main.tsx"></script>'
- )
- set_show_runtime_manager_for_tests(manager)
- try:
- response = app.test_client().get("/show/ses123/app/dashboard", base_url="http://127.0.0.1:5123")
- finally:
- set_show_runtime_manager_for_tests(None)
-
- assert response.status_code == 200
- body = response.content.decode("utf-8")
- assert '"eventsPath":"/show/ses123/__show/events"' in body
- assert '"writeToken":"token-ses123"' in body
-
-
-def test_show_runtime_vendor_deps_are_cacheable(monkeypatch, tmp_path):
- monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
- _save_config(tmp_path)
- _create_show_page("ses123", "private")
- manager = _FakeShowRuntimeManager(
- body=b"export default {}",
- extra_headers={
- "content-type": "text/javascript",
- "cache-control": "no-cache",
- },
- )
- set_show_runtime_manager_for_tests(manager)
- try:
- response = app.test_client().get(
- "/show/ses123/.vite/deps/react-dom_client.js?v=d6d38251",
- base_url="http://127.0.0.1:5123",
- )
- finally:
- set_show_runtime_manager_for_tests(None)
-
- assert response.status_code == 302
- assert response.headers["location"] == "/_show-runtime/deps/r9-d6d38251/react-dom_client.js"
- assert response.headers["cache-control"] == "no-store"
- assert "set-cookie" not in response.headers
-
-
-def test_show_runtime_public_dep_proxy_is_cacheable(monkeypatch, tmp_path):
- monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
- _save_config(tmp_path)
- _create_show_page("ses123", "private")
- manager = _FakeShowRuntimeManager(
- body=b"export default {}",
- extra_headers={
- "content-type": "text/javascript",
- "cache-control": "no-cache",
- },
- )
- set_show_runtime_manager_for_tests(manager)
- try:
- original = app.test_client().get(
- "/show/ses123/node_modules/.vite/deps/react.js?v=d6d38251",
- base_url="http://127.0.0.1:5123",
- )
- response = app.test_client().get(
- "/_show-runtime/deps/r9-d6d38251/react.js?v=d6d38251",
- base_url="http://127.0.0.1:5123",
- )
- finally:
- set_show_runtime_manager_for_tests(None)
-
- assert original.status_code == 302
- assert response.status_code == 200
- assert response.headers["cache-control"] == "public, max-age=31536000, immutable"
- assert "set-cookie" not in response.headers
- assert manager.calls[-1][1] == "/sessions/ses123/app/node_modules/.vite/deps/react.js?v=d6d38251"
-
-
-def test_show_runtime_public_dep_proxy_compresses_large_javascript(monkeypatch, tmp_path):
- monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
- _save_config(tmp_path)
- _create_show_page("ses123", "private")
- manager = _FakeShowRuntimeManager(
- body=(b"export const value = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';\n" * 200),
- extra_headers={
- "content-type": "text/javascript",
- "cache-control": "no-cache",
- "content-length": "12000",
- "etag": "source-etag",
- },
- )
- set_show_runtime_manager_for_tests(manager)
- try:
- app.test_client().get(
- "/show/ses123/node_modules/.vite/deps/react.js?v=d6d38251",
- base_url="http://127.0.0.1:5123",
- )
- response = app.test_client().get(
- "/_show-runtime/deps/r9-d6d38251/react.js?v=d6d38251",
- base_url="http://127.0.0.1:5123",
- headers={"Accept-Encoding": "gzip"},
- )
- finally:
- set_show_runtime_manager_for_tests(None)
-
- assert response.status_code == 200
- assert response.headers["content-encoding"] == "gzip"
- assert response.headers["vary"] == "Accept-Encoding"
- assert response.headers["content-length"] != "12000"
- assert "etag" not in response.headers
- assert response.content.startswith(b"export const value")
- assert "accept-encoding" not in manager.calls[-1][2]
-
-
-def test_show_runtime_public_dep_proxy_allows_scoped_package_names(monkeypatch, tmp_path):
- monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
- _save_config(tmp_path)
- _create_show_page("ses123", "private")
- manager = _FakeShowRuntimeManager(
- body=b"export default {}",
- extra_headers={
- "content-type": "text/javascript",
- "cache-control": "no-cache",
- },
- )
- set_show_runtime_manager_for_tests(manager)
- try:
- original = app.test_client().get(
- "/show/ses123/node_modules/.vite/deps/@avibe_show-ui_theme.js?v=d6d38251",
- base_url="http://127.0.0.1:5123",
- )
- response = app.test_client().get(
- "/_show-runtime/deps/r9-d6d38251/%40avibe_show-ui_theme.js?v=d6d38251",
- base_url="http://127.0.0.1:5123",
- )
- finally:
- set_show_runtime_manager_for_tests(None)
-
- assert original.status_code == 302
- assert original.headers["location"] == "/_show-runtime/deps/r9-d6d38251/%40avibe_show-ui_theme.js"
- assert response.status_code == 200
- assert response.headers["cache-control"] == "public, max-age=31536000, immutable"
- assert manager.calls[-1][1] == "/sessions/ses123/app/node_modules/.vite/deps/@avibe_show-ui_theme.js?v=d6d38251"
-
-
-def test_show_runtime_public_dep_proxy_registers_sibling_chunks(monkeypatch, tmp_path):
- monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
- _save_config(tmp_path)
- _create_show_page("ses123", "private")
- manager = _FakeShowRuntimeManager(
- body=b'import "./chunk-OUYO74D4.js?v=108951fb";\nexport default {}',
- bodies_by_path={
- "/sessions/ses123/app/node_modules/.vite/deps/chunk-OUYO74D4.js?v=108951fb": b"export const chunk = true;",
- },
- extra_headers={
- "content-type": "text/javascript",
- "cache-control": "no-cache",
- },
- )
- set_show_runtime_manager_for_tests(manager)
- try:
- original = app.test_client().get(
- "/show/ses123/node_modules/.vite/deps/react-dom_client.js?v=d6d38251",
- base_url="http://127.0.0.1:5123",
- )
- dep = app.test_client().get(
- "/_show-runtime/deps/r9-d6d38251/react-dom_client.js?v=d6d38251",
- base_url="http://127.0.0.1:5123",
- )
- chunk = app.test_client().get(
- "/_show-runtime/deps/r9-108951fb/chunk-OUYO74D4.js?v=108951fb",
- base_url="http://127.0.0.1:5123",
- )
- finally:
- set_show_runtime_manager_for_tests(None)
-
- assert original.status_code == 302
- assert dep.status_code == 200
- assert b'import "/_show-runtime/deps/r9-108951fb/chunk-OUYO74D4.js?v=108951fb"' in dep.content
- assert dep.headers["cache-control"] == "no-store"
- assert chunk.status_code == 200
- assert chunk.headers["cache-control"] == "public, max-age=31536000, immutable"
- assert manager.calls[-1][1] == "/sessions/ses123/app/node_modules/.vite/deps/chunk-OUYO74D4.js?v=108951fb"
-
-
-def test_show_runtime_public_dep_proxy_rewrites_private_chunk_imports(monkeypatch, tmp_path):
- monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
- _save_config(tmp_path)
- _create_show_page("ses123", "private")
- manager = _FakeShowRuntimeManager(
- body=(
- b'import "/show/ses123/@fs/home/avibe/.avibe/runtime/show-runtime/vite-cache/'
- b'abc123/ses123/deps/chunk-QA663NX4.js?v=108951fb";\nexport default {}'
- ),
- bodies_by_path={
- "/sessions/ses123/app/@fs/home/avibe/.avibe/runtime/show-runtime/vite-cache/"
- "abc123/ses123/deps/chunk-QA663NX4.js?v=108951fb": b"export const chunk = true;",
- },
- extra_headers={
- "content-type": "text/javascript",
- "cache-control": "no-cache",
- },
- )
- set_show_runtime_manager_for_tests(manager)
- try:
- original = app.test_client().get(
- "/show/ses123/node_modules/.vite/deps/react-dom_client.js?v=d6d38251",
- base_url="http://127.0.0.1:5123",
- )
- dep = app.test_client().get(
- "/_show-runtime/deps/r9-d6d38251/react-dom_client.js?v=d6d38251",
- base_url="http://127.0.0.1:5123",
- )
- chunk = app.test_client().get(
- "/_show-runtime/deps/r9-108951fb/chunk-QA663NX4.js?v=108951fb",
- base_url="http://127.0.0.1:5123",
- )
- finally:
- set_show_runtime_manager_for_tests(None)
-
- assert original.status_code == 302
- assert dep.status_code == 200
- assert b'import "/_show-runtime/deps/r9-108951fb/chunk-QA663NX4.js?v=108951fb"' in dep.content
- assert b'"/show/ses123/@fs/' not in dep.content
- assert dep.headers["cache-control"] == "no-store"
- assert chunk.status_code == 200
- assert manager.calls[-1][1] == (
- "/sessions/ses123/app/@fs/home/avibe/.avibe/runtime/show-runtime/vite-cache/"
- "abc123/ses123/deps/chunk-QA663NX4.js?v=108951fb"
- )
-
-
-def test_show_runtime_public_dep_proxy_refreshes_private_chunk_registry(monkeypatch, tmp_path):
- monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
- _save_config(tmp_path)
- _create_show_page("ses123", "private")
- _create_show_page("ses456", "private")
- manager = _FakeShowRuntimeManager(
- body=(
- b'import "/show/ses123/@fs/home/avibe/.avibe/runtime/show-runtime/vite-cache/'
- b'old/ses123/deps/chunk-QA663NX4.js?v=old111";'
- ),
- extra_headers={
- "content-type": "text/javascript",
- "cache-control": "no-cache",
- },
- )
- set_show_runtime_manager_for_tests(manager)
- try:
- first_original = app.test_client().get(
- "/show/ses123/node_modules/.vite/deps/react-dom_client.js?v=d6d38251",
- base_url="http://127.0.0.1:5123",
- )
- first_dep = app.test_client().get(
- "/_show-runtime/deps/r9-d6d38251/react-dom_client.js?v=d6d38251",
- base_url="http://127.0.0.1:5123",
- )
- manager.body = (
- b'import "/show/ses456/@fs/home/avibe/.avibe/runtime/show-runtime/vite-cache/'
- b'new/ses456/deps/chunk-QA663NX4.js?v=new222";'
- )
- second_original = app.test_client().get(
- "/show/ses456/node_modules/.vite/deps/react-dom_client.js?v=d6d38251",
- base_url="http://127.0.0.1:5123",
- )
- second_dep = app.test_client().get(
- "/_show-runtime/deps/r9-d6d38251/react-dom_client.js?v=d6d38251",
- base_url="http://127.0.0.1:5123",
- )
- chunk = app.test_client().get(
- "/_show-runtime/deps/r9-new222/chunk-QA663NX4.js?v=new222",
- base_url="http://127.0.0.1:5123",
- )
- finally:
- set_show_runtime_manager_for_tests(None)
-
- assert first_original.status_code == 302
- assert first_dep.status_code == 200
- assert first_dep.headers["cache-control"] == "no-store"
- assert second_original.status_code == 302
- assert second_dep.status_code == 200
- assert b"/_show-runtime/deps/r9-new222/chunk-QA663NX4.js?v=new222" in second_dep.content
- assert second_dep.headers["cache-control"] == "no-store"
- assert chunk.status_code == 200
- assert manager.calls[-1][1] == (
- "/sessions/ses456/app/@fs/home/avibe/.avibe/runtime/show-runtime/vite-cache/"
- "new/ses456/deps/chunk-QA663NX4.js?v=new222"
- )
-
-
-def test_show_runtime_public_dep_proxy_derives_chunk_paths_when_registry_is_cold(monkeypatch, tmp_path):
- monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
- _save_config(tmp_path)
- _create_show_page("ses123", "private")
- manager = _FakeShowRuntimeManager(
- body=b"export default {}",
- extra_headers={
- "content-type": "text/javascript",
- "cache-control": "no-cache",
- },
- )
- set_show_runtime_manager_for_tests(manager)
- try:
- original = app.test_client().get(
- "/show/ses123/node_modules/.vite/deps/react-dom_client.js?v=d6d38251",
- base_url="http://127.0.0.1:5123",
- )
- chunk = app.test_client().get(
- "/_show-runtime/deps/r9-d6d38251/chunk-OUYO74D4.js?v=108951fb",
- base_url="http://127.0.0.1:5123",
- )
- finally:
- set_show_runtime_manager_for_tests(None)
-
- assert original.status_code == 302
- assert chunk.status_code == 200
- assert manager.calls[-1][1] == "/sessions/ses123/app/node_modules/.vite/deps/chunk-OUYO74D4.js?v=108951fb"
-
-
-def test_show_runtime_unversioned_vendor_deps_stay_session_scoped(monkeypatch, tmp_path):
- monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
- _save_config(tmp_path)
- _create_show_page("ses123", "private")
- manager = _FakeShowRuntimeManager(
- body=b"export default {}",
- extra_headers={
- "content-type": "text/javascript",
- "cache-control": "no-cache",
- },
- )
- set_show_runtime_manager_for_tests(manager)
- try:
- response = app.test_client().get(
- "/show/ses123/node_modules/.vite/deps/react.js",
- base_url="http://127.0.0.1:5123",
- )
- finally:
- set_show_runtime_manager_for_tests(None)
-
- assert response.status_code == 200
- assert response.headers["cache-control"] == "no-cache"
- assert "location" not in response.headers
-
-
-def test_show_runtime_public_dep_rejects_unversioned_cache_key(monkeypatch, tmp_path):
- monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
- _save_config(tmp_path)
-
- response = app.test_client().get(
- "/_show-runtime/deps/unversioned/react.js",
- base_url="http://127.0.0.1:5123",
- )
-
- assert response.status_code == 404
- assert response.headers["cache-control"] == "no-store"
-
-
-def test_show_runtime_public_dep_rejects_unregistered_cache_key_without_cache(monkeypatch, tmp_path):
- monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
- _save_config(tmp_path)
-
- response = app.test_client().get(
- "/_show-runtime/deps/r9-d6d38251/react.js",
- base_url="http://127.0.0.1:5123",
- )
-
- assert response.status_code == 404
- assert response.headers["cache-control"] == "no-store"
-
-
-def test_show_runtime_relocated_vendor_deps_are_cacheable(monkeypatch, tmp_path):
- monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
- _save_config(tmp_path)
- _create_show_page("ses123", "private")
- manager = _FakeShowRuntimeManager(
- body=b"export default {}",
- extra_headers={
- "content-type": "text/javascript",
- "cache-control": "no-cache",
- },
- )
- set_show_runtime_manager_for_tests(manager)
- try:
- response = app.test_client().get(
- "/show/ses123/@fs/Users/cyh/.vibe_remote/runtime/show-runtime/vite-cache/abc123/ses123/deps/react-dom_client.js?v=d6d38251",
- base_url="http://127.0.0.1:5123",
- )
- finally:
- set_show_runtime_manager_for_tests(None)
-
- assert response.status_code == 302
- assert response.headers["location"] == "/_show-runtime/deps/r9-d6d38251/react-dom_client.js"
- assert "set-cookie" not in response.headers
-
-
-def test_show_runtime_vendor_dep_errors_are_not_marked_immutable(monkeypatch, tmp_path):
- monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
- _save_config(tmp_path)
- _create_show_page("ses123", "private")
- manager = _FakeShowRuntimeManager(
- body=b"missing",
- status_code=404,
- extra_headers={
- "content-type": "text/plain",
- "cache-control": "no-cache",
- },
- )
- set_show_runtime_manager_for_tests(manager)
- try:
- response = app.test_client().get(
- "/show/ses123/.vite/deps/react-dom_client.js?v=d6d38251",
- base_url="http://127.0.0.1:5123",
- )
- finally:
- set_show_runtime_manager_for_tests(None)
-
- assert response.status_code == 404
- assert response.headers["cache-control"] == "no-cache"
-
-
-def test_show_runtime_fs_dist_paths_are_not_marked_immutable(monkeypatch, tmp_path):
- monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
- _save_config(tmp_path)
- _create_show_page("ses123", "private")
- manager = _FakeShowRuntimeManager(
- body=b"export default {}",
- extra_headers={
- "content-type": "text/javascript",
- "cache-control": "no-cache",
- },
- )
- set_show_runtime_manager_for_tests(manager)
- try:
- response = app.test_client().get(
- "/show/ses123/@fs/Users/cyh/.vibe_remote/runtime/show-runtime/source/github/main/packages/ui/dist/theme.js",
- base_url="http://127.0.0.1:5123",
- )
- finally:
- set_show_runtime_manager_for_tests(None)
-
- assert response.status_code == 200
- assert response.headers["cache-control"] == "no-cache"
-
-
-def test_show_runtime_session_source_is_not_marked_immutable(monkeypatch, tmp_path):
- monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
- _save_config(tmp_path)
- _create_show_page("ses123", "private")
- manager = _FakeShowRuntimeManager(
- body=b"export default function App() {}",
- extra_headers={
- "content-type": "text/javascript",
- "cache-control": "no-cache",
- },
- )
- set_show_runtime_manager_for_tests(manager)
- try:
- response = app.test_client().get(
- "/show/ses123/src/App.tsx?t=1780732068677",
- base_url="http://127.0.0.1:5123",
- )
- finally:
- set_show_runtime_manager_for_tests(None)
-
- assert response.status_code == 200
- assert response.headers["cache-control"] == "no-cache"
-
-
-def test_show_runtime_source_rewrites_dep_imports_to_public_paths(monkeypatch, tmp_path):
- monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
- _save_config(tmp_path)
- _create_show_page("ses123", "private")
- manager = _FakeShowRuntimeManager(
- body=b'import "/node_modules/.vite/deps/react.js?v=d6d38251";\nimport "./App.tsx";',
- bodies_by_path={
- "/sessions/ses123/app/node_modules/.vite/deps/react.js?v=d6d38251": b"export default {}",
- },
- extra_headers={
- "content-type": "text/javascript",
- "cache-control": "no-cache",
- "etag": "source-etag",
- },
- )
- set_show_runtime_manager_for_tests(manager)
- try:
- response = app.test_client().get(
- "/show/ses123/src/main.tsx?t=1780732068677",
- base_url="http://127.0.0.1:5123",
- )
- public_dep = app.test_client().get(
- "/_show-runtime/deps/r9-d6d38251/react.js?v=d6d38251",
- base_url="http://127.0.0.1:5123",
- )
- finally:
- set_show_runtime_manager_for_tests(None)
-
- assert response.status_code == 200
- assert b'"/_show-runtime/deps/r9-d6d38251/react.js?v=d6d38251"' in response.content
- assert b'"./App.tsx"' in response.content
- assert response.headers["cache-control"] == "no-store"
- assert "etag" not in response.headers
- assert public_dep.status_code == 200
- assert public_dep.headers["cache-control"] == "public, max-age=31536000, immutable"
-
-
-def test_show_runtime_source_rewrites_prefixed_fs_vite_cache_dep_imports(monkeypatch, tmp_path):
- monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
- _save_config(tmp_path)
- share_id = _create_show_page("ses123", "public")
- manager = _FakeShowRuntimeManager(
- body=(
- f'import "/p/{share_id}/@fs/home/avibe/.avibe/runtime/show-runtime/vite-cache/'
- 'abc123/ses123/deps/react-dom_client.js?v=d6d38251";'
- ).encode("utf-8"),
- extra_headers={
- "content-type": "text/javascript",
- "cache-control": "no-cache",
- "etag": "source-etag",
- },
- )
- set_show_runtime_manager_for_tests(manager)
- try:
- response = app.test_client().get(
- f"/p/{share_id}/src/main.tsx?t=1780732068677",
- base_url="http://127.0.0.1:5123",
- )
- public_dep = app.test_client().get(
- "/_show-runtime/deps/r9-d6d38251/react-dom_client.js?v=d6d38251",
- base_url="http://127.0.0.1:5123",
- )
- finally:
- set_show_runtime_manager_for_tests(None)
-
- assert response.status_code == 200
- assert b'"/_show-runtime/deps/r9-d6d38251/react-dom_client.js?v=d6d38251"' in response.content
- assert response.headers["cache-control"] == "no-store"
- assert "etag" not in response.headers
- assert public_dep.status_code == 200
- assert manager.calls[-1][1] == (
- "/sessions/ses123/app/@fs/home/avibe/.avibe/runtime/show-runtime/vite-cache/"
- "abc123/ses123/deps/react-dom_client.js?v=d6d38251"
- )
-
-
-def test_public_show_runtime_source_rewrites_private_runtime_paths(monkeypatch, tmp_path):
- monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
- _save_config(tmp_path)
- share_id = _create_show_page("ses123", "public")
- manager = _FakeShowRuntimeManager(
- body=(
- b'import "/show/ses123/@vite/client";\n'
- b'import "/show/ses123/@react-refresh";\n'
- b'const socketPath = "/show/ses123/__vite_hmr";\n'
- ),
- extra_headers={
- "content-type": "text/javascript",
- "cache-control": "no-cache",
- "etag": "source-etag",
- },
- )
- set_show_runtime_manager_for_tests(manager)
- try:
- response = app.test_client().get(
- f"/p/{share_id}/src/App.tsx?t=1780732068677",
- base_url="http://127.0.0.1:5123",
- )
- finally:
- set_show_runtime_manager_for_tests(None)
-
- assert response.status_code == 200
- assert b'"/_show-runtime/client-shim-r9.js"' in response.content
- assert b'"/_show-runtime/react-refresh-shim-r9.js"' in response.content
- assert f'"/p/{share_id}/@vite/client"'.encode() not in response.content
- assert f'"/p/{share_id}/@react-refresh"'.encode() not in response.content
- assert f'"/p/{share_id}/__vite_hmr"'.encode() in response.content
- assert b'"/show/ses123/' not in response.content
- assert response.headers["cache-control"] == "no-store"
- assert "etag" not in response.headers
-
-
-def test_public_show_runtime_html_rewrites_private_runtime_client_paths(monkeypatch, tmp_path):
- monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
- _save_config(tmp_path)
- share_id = _create_show_page("ses123", "public")
- manager = _FakeShowRuntimeManager(
- body=(
- b'<script type="module">import { injectIntoGlobalHook } from "/show/ses123/@react-refresh";</script>'
- b'<script type="module" src="/show/ses123/@vite/client"></script>'
- b'<script type="module" src="/show/ses123/src/main.tsx"></script>'
- ),
- extra_headers={
- "content-type": "text/html; charset=utf-8",
- "cache-control": "no-cache",
- "etag": "source-etag",
- },
- )
- set_show_runtime_manager_for_tests(manager)
- try:
- response = app.test_client().get(
- f"/p/{share_id}/",
- base_url="http://127.0.0.1:5123",
- )
- finally:
- set_show_runtime_manager_for_tests(None)
-
- assert response.status_code == 200
- assert b'"/_show-runtime/client-shim-r9.js"' in response.content
- assert b'"/_show-runtime/react-refresh-shim-r9.js"' in response.content
- assert f'"/p/{share_id}/src/main.tsx"'.encode() in response.content
- assert b'"/show/ses123/' not in response.content
- assert f'"/p/{share_id}/@vite/client"'.encode() not in response.content
- assert f'"/p/{share_id}/@react-refresh"'.encode() not in response.content
- assert response.headers["cache-control"] == "no-store"
- assert "etag" not in response.headers
-
-
-def test_public_show_runtime_html_preloads_entry_direct_imports(monkeypatch, tmp_path):
- monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
- _save_config(tmp_path)
- share_id = _create_show_page("ses123", "public")
- package_path = "/@fs/home/avibe/.avibe/runtime/show-runtime/source/github/avibe-bot_vibe-show-runtime/main/packages/ui/dist/button.js"
- manager = _FakeShowRuntimeManager(
- body=b'<!doctype html><html><head></head><body><script type="module" src="./src/main.tsx"></script></body></html>',
- bodies_by_path={
- "/sessions/ses123/app/": b'<!doctype html><html><head></head><body><script type="module" src="./src/main.tsx"></script></body></html>',
- "/sessions/ses123/app/src/main.tsx": (
- b'import "/node_modules/.vite/deps/react-dom_client.js?v=d6d38251";'
- b'import "./styles.css";'
- b'import App from "./App.tsx";'
- ),
- "/sessions/ses123/app/src/App.tsx": f'import {{ Button }} from "{package_path}";'.encode("utf-8"),
- f"/sessions/ses123/app{package_path}": (
- b'import { motion } from "/node_modules/.vite/deps/motion_react.js?v=d8d245fb";'
- b'import { cn } from "./utils.js";'
- ),
- },
- headers_by_path={
- "/sessions/ses123/app/": {"content-type": "text/html; charset=utf-8"},
- "/sessions/ses123/app/src/main.tsx": {"content-type": "text/javascript"},
- "/sessions/ses123/app/src/App.tsx": {"content-type": "text/javascript"},
- f"/sessions/ses123/app{package_path}": {"content-type": "text/javascript"},
- },
- extra_headers={
- "cache-control": "no-cache",
- "etag": "source-etag",
- },
- )
- set_show_runtime_manager_for_tests(manager)
- try:
- response = app.test_client().get(
- f"/p/{share_id}/",
- base_url="http://127.0.0.1:5123",
- )
- finally:
- set_show_runtime_manager_for_tests(None)
-
- assert response.status_code == 200
- assert f'<link rel="modulepreload" href="/p/{share_id}/src/main.tsx">'.encode() in response.content
- assert b'<link rel="modulepreload" href="/_show-runtime/deps/r9-d6d38251/react-dom_client.js?v=d6d38251">' in response.content
- assert f'<link rel="modulepreload" href="/p/{share_id}/src/styles.css">'.encode() in response.content
- assert b'<link rel="modulepreload" href="/_show-runtime/deps/r9-m' in response.content
- assert b'/button.js">' in response.content
- assert b'<link rel="modulepreload" href="/_show-runtime/deps/r9-d8d245fb/motion_react.js?v=d8d245fb">' in response.content
- assert b"/utils.js" in response.content
- assert response.content.index(b'rel="modulepreload"') < response.content.index(b"</head>")
- assert package_path.encode() not in response.content
- assert response.headers["cache-control"] == "no-store"
- assert "etag" not in response.headers
-
-
-def test_public_show_runtime_javascript_strips_inline_source_map(monkeypatch, tmp_path):
- monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
- _save_config(tmp_path)
- share_id = _create_show_page("ses123", "public")
- manager = _FakeShowRuntimeManager(
- body=b"export const ok = true;\n//# sourceMappingURL=data:application/json;base64,AAAA",
- extra_headers={
- "content-type": "text/javascript",
- "cache-control": "no-cache",
- "etag": "source-etag",
- "sourcemap": "app.js.map",
- "x-sourcemap": "app.js.map",
- },
- )
- set_show_runtime_manager_for_tests(manager)
- try:
- response = app.test_client().get(
- f"/p/{share_id}/src/App.tsx?t=1780732068677",
- base_url="http://127.0.0.1:5123",
- )
- finally:
- set_show_runtime_manager_for_tests(None)
-
- assert response.status_code == 200
- assert b"export const ok = true;" in response.content
- assert b"sourceMappingURL=data:" not in response.content
- assert response.headers["cache-control"] == "no-store"
- assert "etag" not in response.headers
- assert "sourcemap" not in response.headers
- assert "x-sourcemap" not in response.headers
-
-
-def test_show_runtime_public_dep_strips_inline_source_map_without_disabling_cache(monkeypatch, tmp_path):
- monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
- _save_config(tmp_path)
- share_id = _create_show_page("ses123", "public")
- manager = _FakeShowRuntimeManager(
- body=b"export const ok = true;\n//# sourceMappingURL=data:application/json;base64,AAAA",
- extra_headers={
- "content-type": "text/javascript",
- "cache-control": "no-cache",
- "etag": "source-etag",
- "sourcemap": "react-dom_client.js.map",
- },
- )
- set_show_runtime_manager_for_tests(manager)
- try:
- source = app.test_client().get(
- f"/p/{share_id}/node_modules/.vite/deps/react-dom_client.js?v=d6d38251",
- base_url="http://127.0.0.1:5123",
- )
- public_dep = app.test_client().get(
- "/_show-runtime/deps/r9-d6d38251/react-dom_client.js",
- base_url="http://127.0.0.1:5123",
- )
- finally:
- set_show_runtime_manager_for_tests(None)
-
- assert source.status_code == 302
- assert public_dep.status_code == 200
- assert b"sourceMappingURL=data:" not in public_dep.content
- assert public_dep.headers["cache-control"] == "public, max-age=31536000, immutable"
- assert "etag" not in public_dep.headers
- assert "sourcemap" not in public_dep.headers
+ assert "globalThis.__AVIBE_SHOW__" not in response.content.decode("utf-8")
+ assert response.headers["content-range"] == "bytes 0-63/128"
+ assert manager.calls[0][2]["range"] == "bytes=0-63"
-def test_public_show_runtime_rewrites_package_dist_modules_to_public_deps(monkeypatch, tmp_path):
+def test_private_show_page_runtime_config_overrides_existing_client_defaults(monkeypatch, tmp_path):
monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
_save_config(tmp_path)
- share_id = _create_show_page("ses123", "public")
- package_path = "/@fs/home/avibe/.avibe/runtime/show-runtime/source/github/avibe-bot_vibe-show-runtime/main/packages/ui/dist/button.js"
+ _create_show_page("ses123", "private")
+ monkeypatch.setattr("vibe.ui_server.show_event_write_token", lambda session_id: f"token-{session_id}")
manager = _FakeShowRuntimeManager(
- body=f'import "{package_path}";'.encode("utf-8"),
- bodies_by_path={
- f"/sessions/ses123/app{package_path}": b'export { Button } from "./utils.js";',
- },
- extra_headers={
- "content-type": "text/javascript",
- "cache-control": "no-cache",
- "etag": "source-etag",
- },
+ body=b'<!doctype html><script>globalThis.__AVIBE_SHOW__={eventsPath:"runtime-only"}</script><script type="module" src="/src/main.tsx"></script>'
)
set_show_runtime_manager_for_tests(manager)
try:
- response = app.test_client().get(
- f"/p/{share_id}/src/App.tsx?t=1780732068677",
- base_url="http://127.0.0.1:5123",
- )
- public_path = response.content.decode("utf-8").split('"')[1]
- public_dep = app.test_client().get(
- public_path,
- base_url="http://127.0.0.1:5123",
- )
- sibling_path = public_dep.content.decode("utf-8").split('"')[1]
+ response = app.test_client().get("/show/ses123/app/dashboard", base_url="http://127.0.0.1:5123")
finally:
set_show_runtime_manager_for_tests(None)
assert response.status_code == 200
- assert public_path.startswith("/_show-runtime/deps/r9-m")
- assert public_path.endswith("/button.js")
- assert package_path.encode() not in response.content
- assert public_dep.status_code == 200
- assert public_dep.headers["cache-control"] == "no-store"
- assert sibling_path.startswith(public_path.rsplit("/", 1)[0])
- assert sibling_path.endswith("/utils.js")
- assert manager.calls[-1][1] == f"/sessions/ses123/app{package_path}"
+ body = response.content.decode("utf-8")
+ assert '"eventsPath":"/show/ses123/__show/events"' in body
+ assert '"writeToken":"token-ses123"' in body
-def test_show_runtime_public_package_dep_rewrites_private_client_imports(monkeypatch, tmp_path):
+def test_public_show_runtime_source_rewrites_private_runtime_paths(monkeypatch, tmp_path):
monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
_save_config(tmp_path)
share_id = _create_show_page("ses123", "public")
- package_path = "/@fs/home/avibe/.avibe/runtime/show-runtime/source/github/avibe-bot_vibe-show-runtime/main/packages/ui/dist/button.js"
manager = _FakeShowRuntimeManager(
- body=f'import "{package_path}";'.encode("utf-8"),
- bodies_by_path={
- f"/sessions/ses123/app{package_path}": (
- b'import { createHotContext as __vite__createHotContext } from "/show/ses123/@vite/client";'
- b'import * as RefreshRuntime from "/show/ses123/@react-refresh";'
- b"export const Button = true;"
- ),
- },
+ body=(
+ b'import "/show/ses123/@vite/client";\n'
+ b'import "/show/ses123/@react-refresh";\n'
+ b'const socketPath = "/show/ses123/__vite_hmr";\n'
+ ),
extra_headers={
"content-type": "text/javascript",
"cache-control": "no-cache",
@@ -1142,69 +374,64 @@ def test_show_runtime_public_package_dep_rewrites_private_client_imports(monkeyp
)
set_show_runtime_manager_for_tests(manager)
try:
- source = app.test_client().get(
+ response = app.test_client().get(
f"/p/{share_id}/src/App.tsx?t=1780732068677",
base_url="http://127.0.0.1:5123",
)
- public_path = source.content.decode("utf-8").split('"')[1]
- public_dep = app.test_client().get(
- public_path,
- base_url="http://127.0.0.1:5123",
- )
finally:
set_show_runtime_manager_for_tests(None)
- assert source.status_code == 200
- assert public_dep.status_code == 200
- assert b'"/_show-runtime/client-shim-r9.js"' in public_dep.content
- assert b'"/_show-runtime/react-refresh-shim-r9.js"' in public_dep.content
- assert b'"/show/ses123/@vite/client"' not in public_dep.content
- assert b'"/show/ses123/@react-refresh"' not in public_dep.content
- assert public_dep.headers["cache-control"] == "no-store"
+ assert response.status_code == 200
+ assert b'"/_show-runtime/client-shim-v1.js"' in response.content
+ assert b'"/_show-runtime/react-refresh-shim-v1.js"' in response.content
+ assert f'"/p/{share_id}/@vite/client"'.encode() not in response.content
+ assert f'"/p/{share_id}/@react-refresh"'.encode() not in response.content
+ assert f'"/p/{share_id}/__vite_hmr"'.encode() in response.content
+ assert b'"/show/ses123/' not in response.content
+ assert response.headers["cache-control"] == "no-store"
+ assert "etag" not in response.headers
-def test_show_runtime_public_package_dep_siblings_with_vite_version_use_shared_dep_namespace(monkeypatch, tmp_path):
+def test_public_show_runtime_html_rewrites_private_runtime_client_paths(monkeypatch, tmp_path):
monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
_save_config(tmp_path)
share_id = _create_show_page("ses123", "public")
- package_path = "/@fs/home/avibe/.avibe/runtime/show-runtime/source/github/avibe-bot_vibe-show-runtime/main/packages/ui/dist/card.js"
manager = _FakeShowRuntimeManager(
- body=f'import "{package_path}";'.encode("utf-8"),
- bodies_by_path={
- f"/sessions/ses123/app{package_path}": b'import "./react.js?v=d8d245fb";',
- "/sessions/ses123/app/@fs/home/avibe/.avibe/runtime/show-runtime/source/github/avibe-bot_vibe-show-runtime/main/packages/ui/dist/react.js": (
- b"export default {};"
- ),
- },
+ body=(
+ b'<script type="module">import { injectIntoGlobalHook } from "/show/ses123/@react-refresh";</script>'
+ b'<script type="module" src="/show/ses123/@vite/client"></script>'
+ b'<script type="module" src="/show/ses123/src/main.tsx"></script>'
+ ),
extra_headers={
- "content-type": "text/javascript",
+ "content-type": "text/html; charset=utf-8",
"cache-control": "no-cache",
+ "etag": "source-etag",
},
)
set_show_runtime_manager_for_tests(manager)
try:
- source = app.test_client().get(
- f"/p/{share_id}/src/App.tsx?t=1780732068677",
- base_url="http://127.0.0.1:5123",
- )
- package_public_path = source.content.decode("utf-8").split('"')[1]
- package_dep = app.test_client().get(
- package_public_path,
+ response = app.test_client().get(
+ f"/p/{share_id}/",
base_url="http://127.0.0.1:5123",
)
finally:
set_show_runtime_manager_for_tests(None)
- assert source.status_code == 200
- assert package_dep.status_code == 200
- assert b'"/_show-runtime/deps/r9-d8d245fb/react.js?v=d8d245fb"' in package_dep.content
- assert b"/_show-runtime/deps/r9-m" not in package_dep.content
+ assert response.status_code == 200
+ assert b'"/_show-runtime/client-shim-v1.js"' in response.content
+ assert b'"/_show-runtime/react-refresh-shim-v1.js"' in response.content
+ assert f'"/p/{share_id}/src/main.tsx"'.encode() in response.content
+ assert b'"/show/ses123/' not in response.content
+ assert f'"/p/{share_id}/@vite/client"'.encode() not in response.content
+ assert f'"/p/{share_id}/@react-refresh"'.encode() not in response.content
+ assert response.headers["cache-control"] == "no-store"
+ assert "etag" not in response.headers
def test_show_runtime_public_client_shims_are_cacheable():
client = app.test_client()
- vite_client = client.get("/_show-runtime/client-shim-r9.js", base_url="http://127.0.0.1:5123")
- react_refresh = client.get("/_show-runtime/react-refresh-shim-r9.js", base_url="http://127.0.0.1:5123")
+ vite_client = client.get("/_show-runtime/client-shim-v1.js", base_url="http://127.0.0.1:5123")
+ react_refresh = client.get("/_show-runtime/react-refresh-shim-v1.js", base_url="http://127.0.0.1:5123")
assert vite_client.status_code == 200
assert react_refresh.status_code == 200
@@ -1218,19 +445,6 @@ def test_show_runtime_public_client_shims_are_cacheable():
assert b"validateRefreshBoundaryAndEnqueueUpdate" in react_refresh.content
-def test_show_runtime_legacy_public_client_shims_are_non_cacheable():
- client = app.test_client()
- vite_client = client.get("/_show-runtime/client-shim-r8.js", base_url="http://127.0.0.1:5123")
- react_refresh = client.get("/_show-runtime/react-refresh-shim-r8.js", base_url="http://127.0.0.1:5123")
-
- assert vite_client.status_code == 200
- assert react_refresh.status_code == 200
- assert vite_client.headers["cache-control"] == "no-store"
- assert react_refresh.headers["cache-control"] == "no-store"
- assert b"export function createHotContext" in vite_client.content
- assert b"export function injectIntoGlobalHook" in react_refresh.content
-
-
def test_public_show_runtime_direct_client_paths_return_shims(monkeypatch, tmp_path):
monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
_save_config(tmp_path)
@@ -1256,89 +470,6 @@ def test_public_show_runtime_direct_client_paths_return_shims(monkeypatch, tmp_p
assert manager.calls == []
-def test_show_runtime_source_preserves_dot_vite_dep_import_paths(monkeypatch, tmp_path):
- monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
- _save_config(tmp_path)
- _create_show_page("ses123", "private")
- manager = _FakeShowRuntimeManager(
- body=b'import "/.vite/deps/react.js?v=d6d38251";',
- extra_headers={
- "content-type": "text/javascript",
- "cache-control": "no-cache",
- },
- )
- set_show_runtime_manager_for_tests(manager)
- try:
- response = app.test_client().get(
- "/show/ses123/src/main.tsx?t=1780732068677",
- base_url="http://127.0.0.1:5123",
- )
- public_dep = app.test_client().get(
- "/_show-runtime/deps/r9-d6d38251/react.js?v=d6d38251",
- base_url="http://127.0.0.1:5123",
- )
- finally:
- set_show_runtime_manager_for_tests(None)
-
- assert response.status_code == 200
- assert public_dep.status_code == 200
- assert manager.calls[-1][1] == "/sessions/ses123/app/.vite/deps/react.js?v=d6d38251"
-
-
-def test_show_runtime_source_keeps_unversioned_dep_imports_session_scoped(monkeypatch, tmp_path):
- monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
- _save_config(tmp_path)
- _create_show_page("ses123", "private")
- manager = _FakeShowRuntimeManager(
- body=b'import "/node_modules/.vite/deps/react.js";',
- extra_headers={
- "content-type": "text/javascript",
- "cache-control": "no-cache",
- },
- )
- set_show_runtime_manager_for_tests(manager)
- try:
- response = app.test_client().get(
- "/show/ses123/src/main.tsx?t=1780732068677",
- base_url="http://127.0.0.1:5123",
- )
- finally:
- set_show_runtime_manager_for_tests(None)
-
- assert response.status_code == 200
- assert response.content == b'import "/node_modules/.vite/deps/react.js";'
- assert response.headers["cache-control"] == "no-cache"
-
-
-def test_show_runtime_source_keeps_partial_js_responses_unmodified(monkeypatch, tmp_path):
- monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
- _save_config(tmp_path)
- _create_show_page("ses123", "private")
- manager = _FakeShowRuntimeManager(
- body=b'import "/node_modules/.vite/deps/react.js?v=d6d38251";',
- status_code=206,
- extra_headers={
- "content-type": "text/javascript",
- "cache-control": "no-cache",
- "content-range": "bytes 0-52/53",
- },
- )
- set_show_runtime_manager_for_tests(manager)
- try:
- response = app.test_client().get(
- "/show/ses123/src/main.tsx?t=1780732068677",
- base_url="http://127.0.0.1:5123",
- headers={"Range": "bytes=0-52"},
- )
- finally:
- set_show_runtime_manager_for_tests(None)
-
- assert response.status_code == 206
- assert response.content == b'import "/node_modules/.vite/deps/react.js?v=d6d38251";'
- assert response.headers["content-range"] == "bytes 0-52/53"
- assert response.headers["cache-control"] == "no-cache"
-
-
def test_public_show_page_does_not_inject_write_runtime_config(monkeypatch, tmp_path):
monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
_save_config(tmp_path)
@@ -1702,32 +833,6 @@ def test_public_show_page_clears_show_event_write_cookie(monkeypatch, tmp_path):
assert "Max-Age=0" in cookies
-def test_public_show_page_immutable_deps_do_not_clear_write_cookie(monkeypatch, tmp_path):
- monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
- _save_config(tmp_path)
- _create_agent_session("ses123")
- share_id = _create_show_page("ses123", "public")
- manager = _FakeShowRuntimeManager(
- body=b"export default {}",
- extra_headers={
- "content-type": "text/javascript",
- "cache-control": "no-cache",
- },
- )
- set_show_runtime_manager_for_tests(manager)
- try:
- response = app.test_client().get(
- f"/p/{share_id}/node_modules/.vite/deps/react.js?v=d6d38251",
- base_url="http://127.0.0.1:5123",
- )
- finally:
- set_show_runtime_manager_for_tests(None)
-
- assert response.status_code == 302
- assert response.headers["location"] == "/_show-runtime/deps/r9-d6d38251/react.js"
- assert "set-cookie" not in response.headers
-
-
def test_show_events_stream_replays_all_persisted_pages_before_live(monkeypatch, tmp_path):
from core.show_session_events import ShowSessionEventStore
from vibe.ui_server import _show_events_stream
@@ -3475,3 +2580,174 @@ def test_show_page_serves_assets_with_strict_headers(monkeypatch, tmp_path):
assert response.headers["X-Content-Type-Options"] == "nosniff"
assert response.headers["Referrer-Policy"] == "no-referrer"
assert b"window.showPage" in response.content
+
+
+def test_show_runtime_vendor_asset_proxy_is_immutable(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ manager = _FakeShowRuntimeManager(
+ body=b"export const React = {};",
+ extra_headers={
+ "content-type": "text/javascript; charset=utf-8",
+ "cache-control": "public, max-age=31536000, immutable",
+ },
+ )
+ set_show_runtime_manager_for_tests(manager)
+ try:
+ response = app.test_client().get(
+ "/_show-runtime/vendor/abc123/react.js",
+ base_url="http://127.0.0.1:5123",
+ )
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert response.status_code == 200
+ assert response.content == b"export const React = {};"
+ # The vendor prefix is forwarded verbatim, never under a per-session base path.
+ assert manager.calls[-1][0] == "GET"
+ assert manager.calls[-1][1] == "/_show-runtime/vendor/abc123/react.js"
+ assert response.headers["cache-control"] == "public, max-age=31536000, immutable"
+ assert response.headers["content-type"] == "text/javascript; charset=utf-8"
+ assert "set-cookie" not in response.headers
+ # The shared, anonymous vendor response must not carry a CSRF cookie that would
+ # defeat caching across users.
+ assert not any(
+ cookie.startswith("vibe_csrf_token=") for cookie in response.headers.getlist("set-cookie")
+ )
+
+
+def test_show_runtime_vendor_asset_proxy_forwards_query_and_is_public(monkeypatch, tmp_path):
+ # No remote login configured here: the vendor namespace is referenced by the
+ # anonymous public `/p/<share>/` surface via the runtime's import map, so it must be
+ # reachable without authentication just like the public surface itself.
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ manager = _FakeShowRuntimeManager(
+ body=b".vendor{}",
+ extra_headers={"content-type": "text/css; charset=utf-8"},
+ )
+ set_show_runtime_manager_for_tests(manager)
+ try:
+ response = app.test_client().get(
+ "/_show-runtime/vendor/abc123/index.css?v=1",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ follow_redirects=False,
+ )
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert response.status_code == 200
+ assert response.content == b".vendor{}"
+ assert manager.calls[-1][1] == "/_show-runtime/vendor/abc123/index.css?v=1"
+ assert response.headers["cache-control"] == "public, max-age=31536000, immutable"
+
+
+def test_show_runtime_vendor_asset_proxy_does_not_mark_errors_immutable(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ manager = _FakeShowRuntimeManager(
+ body=b'{"error":"Not found"}',
+ status_code=404,
+ extra_headers={"content-type": "application/json", "cache-control": "no-store"},
+ )
+ set_show_runtime_manager_for_tests(manager)
+ try:
+ response = app.test_client().get(
+ "/_show-runtime/vendor/abc123/missing.js",
+ base_url="http://127.0.0.1:5123",
+ )
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert response.status_code == 404
+ assert response.headers["cache-control"] == "no-store"
+
+
+def test_retired_show_runtime_deps_route_is_gone(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ manager = _FakeShowRuntimeManager(body=b"export default {}")
+ set_show_runtime_manager_for_tests(manager)
+ try:
+ response = app.test_client().get(
+ "/_show-runtime/deps/r9-d6d38251/react.js?v=d6d38251",
+ base_url="http://127.0.0.1:5123",
+ follow_redirects=False,
+ )
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ # The old per-session dep re-sharing layer is fully retired: there is no proxy route
+ # at this path anymore, so it falls through to the SPA static handler (404) and never
+ # touches the Show Runtime.
+ assert response.status_code == 404
+ assert manager.calls == []
+
+
+def test_private_show_page_passes_runtime_importmap_through(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_show_page("ses123", "private")
+ monkeypatch.setattr("vibe.ui_server.show_event_write_token", lambda session_id: f"token-{session_id}")
+ import_map = '{\n "imports": {\n "react": "/_show-runtime/vendor/abc123/react.js"\n }\n}'
+ vendor_link = '<link rel="stylesheet" href="/_show-runtime/vendor/abc123/index.css">'
+ body = (
+ "<!doctype html><html><head>"
+ f'<script type="importmap">{import_map}</script>'
+ f"{vendor_link}"
+ '</head><body><div id="root"></div>'
+ '<script type="module" src="/src/main.tsx"></script>'
+ "</body></html>"
+ ).encode("utf-8")
+ manager = _FakeShowRuntimeManager(body=body)
+ set_show_runtime_manager_for_tests(manager)
+ try:
+ response = app.test_client().get("/show/ses123/", base_url="http://127.0.0.1:5123")
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert response.status_code == 200
+ text = response.content.decode("utf-8")
+ # The runtime-injected import map + vendor link must survive untouched...
+ assert f'<script type="importmap">{import_map}</script>' in text
+ assert vendor_link in text
+ assert '"/_show-runtime/vendor/abc123/react.js"' in text
+ # ...while avibe still injects its private show config before the app module.
+ assert "globalThis.__AVIBE_SHOW__=Object.assign" in text
+ assert text.index("globalThis.__AVIBE_SHOW__") < text.index('src="/src/main.tsx"')
+ # The import map sits before the injected config (head-prepended by the runtime).
+ assert text.index('type="importmap"') < text.index("globalThis.__AVIBE_SHOW__")
+
+
+def test_public_show_page_passes_runtime_importmap_through_unmodified(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ share_id = _create_show_page("ses123", "public")
+ import_map = '{"imports":{"react":"/_show-runtime/vendor/abc123/react.js","@avibe/show-ui/":"/_show-runtime/vendor/abc123/@avibe_show-ui/"}}'
+ body = (
+ "<!doctype html><html><head>"
+ f'<script type="importmap">{import_map}</script>'
+ '<link rel="stylesheet" href="/_show-runtime/vendor/abc123/index.css">'
+ "</head><body>"
+ '<script type="module" src="/p/' + share_id + '/src/main.tsx"></script>'
+ "</body></html>"
+ ).encode("utf-8")
+ manager = _FakeShowRuntimeManager(
+ body=body,
+ extra_headers={"content-type": "text/html; charset=utf-8"},
+ )
+ set_show_runtime_manager_for_tests(manager)
+ try:
+ response = app.test_client().get(f"/p/{share_id}/", base_url="http://127.0.0.1:5123")
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert response.status_code == 200
+ text = response.content.decode("utf-8")
+ # The absolute, session-independent vendor URLs in the import map must pass through
+ # the public-surface rewriter untouched (they are not under the `/show/<id>/` base).
+ assert f'<script type="importmap">{import_map}</script>' in text
+ assert '<link rel="stylesheet" href="/_show-runtime/vendor/abc123/index.css">' in text
+ # Public pages never receive the private write-config injection.
+ assert "globalThis.__AVIBE_SHOW__=Object.assign" not in text
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index bb34807fc..edadd0893 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -2,7 +2,6 @@ import base64
import asyncio
import gzip
import hashlib
-import html
import hmac
import ipaddress
import json
@@ -16,12 +15,11 @@ import socket
import subprocess
import threading
import time
-from collections import deque
from contextlib import contextmanager
from datetime import datetime
from pathlib import Path
from typing import Any, Callable
-from urllib.parse import parse_qsl, quote, unquote, urlencode, urljoin, urlparse, urlsplit, urlunsplit
+from urllib.parse import parse_qsl, quote, unquote, urlencode, urlparse, urlsplit, urlunsplit
import psutil
from aiohttp import ClientSession, WSMsgType
@@ -88,35 +86,23 @@ _SHOW_RUNTIME_MODULE_SCRIPT_RE = re.compile(
r"<script\b(?=[^>]*\btype\s*=\s*['\"]module['\"])[^>]*>",
re.IGNORECASE,
)
-_SHOW_RUNTIME_MODULE_SCRIPT_SRC_RE = re.compile(
- r"<script\b(?=[^>]*\btype\s*=\s*['\"]module['\"])[^>]*\bsrc\s*=\s*(?P<quote>['\"])(?P<src>[^'\"]+)(?P=quote)[^>]*>",
- re.IGNORECASE,
-)
-_SHOW_RUNTIME_IMPORT_SPECIFIER_RE = re.compile(
- r"\bimport\s*(?:[^'\"\n;]*?\sfrom\s*)?(?P<quote>['\"])(?P<path>[^'\"]+)(?P=quote)"
- r"|\bimport\(\s*(?P<dynamic_quote>['\"])(?P<dynamic_path>[^'\"]+)(?P=dynamic_quote)\s*\)"
-)
-_SHOW_RUNTIME_INLINE_SOURCE_MAP_RE = re.compile(rb"\n?//# sourceMappingURL=data:[^\r\n]+")
_SHOW_RUNTIME_IMMUTABLE_CACHE_CONTROL = "public, max-age=31536000, immutable"
-_SHOW_RUNTIME_PUBLIC_DEP_RE = re.compile(
- r"(?P<quote>['\"])(?P<path>(?:(?:\.?/)?(?:node_modules/)?\.vite/deps/|[^'\"?#]*@fs/[^'\"?#]*/(?:\.vite-cache|vite-cache)/[^'\"?#]*/deps/)[^'\"?#]+)(?:\?v=(?P<version>[A-Za-z0-9_-]+))?(?P<rest>[^'\"]*)(?P=quote)"
-)
-_SHOW_RUNTIME_PUBLIC_MODULE_RE = re.compile(
- r"(?P<quote>['\"])(?P<path>[^'\"?#]*@fs/[^'\"?#]*/packages/[^'\"?#]*/dist/[^'\"?#]+\.(?:css|js))(?:\?v=(?P<version>[A-Za-z0-9_-]+))?(?P<rest>[^'\"]*)(?P=quote)"
-)
-_SHOW_RUNTIME_PUBLIC_DEP_SIBLING_RE = re.compile(
- r"(?P<quote>['\"])\./(?P<name>[A-Za-z0-9_.-]+\.(?:css|js))(?:\?v=(?P<version>[A-Za-z0-9_-]+))?(?P<rest>[^'\"]*)(?P=quote)"
-)
-_SHOW_RUNTIME_PUBLIC_DEP_PREFIX = "/_show-runtime/deps"
-_SHOW_RUNTIME_PUBLIC_DEP_CACHE_EPOCH = "r9"
-_SHOW_RUNTIME_PUBLIC_CLIENT_SHIM_PATH = f"/_show-runtime/client-shim-{_SHOW_RUNTIME_PUBLIC_DEP_CACHE_EPOCH}.js"
+# Shared, content-hashed vendor bundle. The runtime serves this at a
+# session-independent path (`/_show-runtime/vendor/<hash>/<file>`) and injects the
+# matching `<script type="importmap">` + vendor CSS `<link>` into every Show Page it
+# serves, so the avibe proxy only has to forward this prefix verbatim (never under a
+# per-session base) and mark 2xx responses immutable.
+_SHOW_RUNTIME_VENDOR_PREFIX = "/_show-runtime/vendor"
+# HMR-neutralizing shims for the public `/p/` surface. Anonymous viewers must not open
+# a live Vite HMR websocket or run React Fast Refresh, so the runtime's `@vite/client`
+# and `@react-refresh` references are rewritten to these inert modules. Independent of
+# the vendor bundle; the version only busts the shim cache when the shim source changes.
+_SHOW_RUNTIME_PUBLIC_SHIM_VERSION = "v1"
+_SHOW_RUNTIME_PUBLIC_CLIENT_SHIM_PATH = f"/_show-runtime/client-shim-{_SHOW_RUNTIME_PUBLIC_SHIM_VERSION}.js"
_SHOW_RUNTIME_PUBLIC_REACT_REFRESH_SHIM_PATH = (
- f"/_show-runtime/react-refresh-shim-{_SHOW_RUNTIME_PUBLIC_DEP_CACHE_EPOCH}.js"
+ f"/_show-runtime/react-refresh-shim-{_SHOW_RUNTIME_PUBLIC_SHIM_VERSION}.js"
)
-_SHOW_RUNTIME_LEGACY_PUBLIC_CLIENT_SHIM_PATH = "/_show-runtime/client-shim-r8.js"
-_SHOW_RUNTIME_LEGACY_PUBLIC_REACT_REFRESH_SHIM_PATH = "/_show-runtime/react-refresh-shim-r8.js"
_SHOW_RUNTIME_COMPRESSIBLE_MIN_BYTES = 1024
-_SHOW_RUNTIME_PUBLIC_DEP_REGISTRY: dict[tuple[str, str], str] = {}
STRUCTURED_LOG_PATTERN = re.compile(r"^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3})\s+-\s+([\w.]+)\s+-\s+(\w+)\s+-\s+(.*)$")
LEVEL_HINT_PATTERN = re.compile(r"\b(DEBUG|INFO|WARNING|ERROR|CRITICAL)\b")
@@ -1008,13 +994,11 @@ def _remote_auth_exempt_path() -> bool:
or path == "/api/cloud/token"
or path == "/api/csrf-token"
or path.startswith("/assets/")
- or path.startswith("/_show-runtime/deps/")
+ or path.startswith(f"{_SHOW_RUNTIME_VENDOR_PREFIX}/")
or path
in {
_SHOW_RUNTIME_PUBLIC_CLIENT_SHIM_PATH,
_SHOW_RUNTIME_PUBLIC_REACT_REFRESH_SHIM_PATH,
- _SHOW_RUNTIME_LEGACY_PUBLIC_CLIENT_SHIM_PATH,
- _SHOW_RUNTIME_LEGACY_PUBLIC_REACT_REFRESH_SHIM_PATH,
}
or path.startswith("/p/")
or path == "/favicon.ico"
@@ -1026,13 +1010,11 @@ def _remote_auth_exempt_before_host_validation() -> bool:
return (
request.path in {"/auth/callback", "/auth/logout", "/api/session", "/api/csrf-token"}
or request.path.startswith("/assets/")
- or request.path.startswith("/_show-runtime/deps/")
+ or request.path.startswith(f"{_SHOW_RUNTIME_VENDOR_PREFIX}/")
or request.path
in {
_SHOW_RUNTIME_PUBLIC_CLIENT_SHIM_PATH,
_SHOW_RUNTIME_PUBLIC_REACT_REFRESH_SHIM_PATH,
- _SHOW_RUNTIME_LEGACY_PUBLIC_CLIENT_SHIM_PATH,
- _SHOW_RUNTIME_LEGACY_PUBLIC_REACT_REFRESH_SHIM_PATH,
}
or request.path == "/favicon.ico"
)
@@ -5565,16 +5547,19 @@ async def show_session_prewarm(session_id: str):
return jsonify({"ok": result.available, "reason": result.reason, "base_url": result.base_url}), status_code
[email protected]("/_show-runtime/deps/<version>/<path:asset_name>", methods=["GET", "HEAD"])
-async def show_runtime_public_dep(version: str, asset_name: str):
- if not re.fullmatch(r"[A-Za-z0-9_-]+", version or "") or version == "unversioned":
- return _show_runtime_public_dep_not_found_response()
- if not re.fullmatch(r"[[email protected]]+", asset_name or ""):
- return _show_runtime_public_dep_not_found_response()
- runtime_path = _public_show_runtime_dep_runtime_path(version, asset_name)
- if not runtime_path:
- return _show_runtime_public_dep_not_found_response()
- if request._request.url.query and "?" not in runtime_path:
[email protected](f"{_SHOW_RUNTIME_VENDOR_PREFIX}/<path:vendor_path>", methods=["GET", "HEAD"])
+async def show_runtime_vendor_asset(vendor_path: str):
+ """Proxy the runtime's shared, content-hashed vendor bundle.
+
+ The runtime serves the vendor at the session-independent path
+ `/_show-runtime/vendor/<hash>/<file>` and references it from the import map it
+ injects into every Show Page, so the same URL is requested by both the authed
+ `/show/<id>/` surface and the anonymous public `/p/<share>/` surface. We forward
+ this prefix verbatim (never under a per-session base) and, because the content
+ hash is in the path, mark successful responses immutable for a year.
+ """
+ runtime_path = f"{_SHOW_RUNTIME_VENDOR_PREFIX}/{quote(vendor_path, safe='/@:-._~')}"
+ if request._request.url.query:
runtime_path = f"{runtime_path}?{request._request.url.query}"
from core.show_runtime import get_show_runtime_manager
@@ -5603,31 +5588,11 @@ async def show_runtime_public_dep(version: str, asset_name: str):
_remove_response_header(response_headers, "cache-control")
_remove_response_header(response_headers, "set-cookie")
response_headers["Cache-Control"] = _SHOW_RUNTIME_IMMUTABLE_CACHE_CONTROL
- content = proxied.content
- if proxied.status_code == 200:
- content = _rewrite_public_show_runtime_dep_siblings(
- proxied.content,
- response_headers,
- version=version,
- runtime_path=runtime_path,
- )
- content = _rewrite_public_show_runtime_dep_client(content, response_headers, runtime_path=runtime_path)
- content = _strip_public_show_runtime_inline_source_maps(content, response_headers)
- content = _compress_show_runtime_response(content, response_headers, request._request)
+ content = _compress_show_runtime_response(proxied.content, response_headers, request._request)
return FastAPIResponse(content=content, status_code=proxied.status_code, headers=response_headers)
-def _show_runtime_public_dep_not_found_response():
- return FastAPIResponse(
- content=b'{"error":"not_found"}',
- status_code=404,
- media_type="application/json",
- headers={"Cache-Control": "no-store"},
- )
-
-
@app.route(_SHOW_RUNTIME_PUBLIC_CLIENT_SHIM_PATH, methods=["GET", "HEAD"])
[email protected](_SHOW_RUNTIME_LEGACY_PUBLIC_CLIENT_SHIM_PATH, methods=["GET", "HEAD"])
def show_runtime_public_client_shim():
content = b"""
const styles = new Map();
@@ -5665,16 +5630,11 @@ export function removeStyle(id) {
}
}
"""
- cache_control = (
- "no-store"
- if request.path == _SHOW_RUNTIME_LEGACY_PUBLIC_CLIENT_SHIM_PATH
- else _SHOW_RUNTIME_IMMUTABLE_CACHE_CONTROL
- )
return FastAPIResponse(
content=content.strip(),
media_type="text/javascript",
headers={
- "Cache-Control": cache_control,
+ "Cache-Control": _SHOW_RUNTIME_IMMUTABLE_CACHE_CONTROL,
"X-Content-Type-Options": "nosniff",
"Referrer-Policy": "no-referrer",
},
@@ -5682,7 +5642,6 @@ export function removeStyle(id) {
@app.route(_SHOW_RUNTIME_PUBLIC_REACT_REFRESH_SHIM_PATH, methods=["GET", "HEAD"])
[email protected](_SHOW_RUNTIME_LEGACY_PUBLIC_REACT_REFRESH_SHIM_PATH, methods=["GET", "HEAD"])
def show_runtime_public_react_refresh_shim():
content = b"""
function identity(type) {
@@ -5706,16 +5665,11 @@ export const __hmr_import = () => Promise.resolve({});
export const registerExportsForReactRefresh = noop;
export const validateRefreshBoundaryAndEnqueueUpdate = () => undefined;
"""
- cache_control = (
- "no-store"
- if request.path == _SHOW_RUNTIME_LEGACY_PUBLIC_REACT_REFRESH_SHIM_PATH
- else _SHOW_RUNTIME_IMMUTABLE_CACHE_CONTROL
- )
return FastAPIResponse(
content=content.strip(),
media_type="text/javascript",
headers={
- "Cache-Control": cache_control,
+ "Cache-Control": _SHOW_RUNTIME_IMMUTABLE_CACHE_CONTROL,
"X-Content-Type-Options": "nosniff",
"Referrer-Policy": "no-referrer",
},
@@ -5788,40 +5742,27 @@ async def _show_page_runtime_response(
response_headers["X-Content-Type-Options"] = "nosniff"
response_headers["Referrer-Policy"] = "no-referrer"
content = proxied.content
- if _should_redirect_to_public_show_runtime_dep(asset_path, starlette_request, proxied.status_code):
- public_path = _register_public_show_runtime_dep(asset_path, starlette_request.url.query, runtime_path)
- response_headers.clear()
- response_headers["location"] = public_path
- response_headers["Cache-Control"] = "no-store"
- return FastAPIResponse(content=b"", status_code=302, headers=response_headers)
- if _should_inject_show_runtime_config(proxied.status_code, response_headers, inject_private_config=inject_private_config):
- content = _inject_show_runtime_config(content, session_id)
- _strip_mutated_show_runtime_headers(response_headers)
- else:
- if proxied.status_code == 200:
- content = _rewrite_public_show_runtime_private_paths(
- content,
- response_headers,
- session_id=session_id,
- external_prefix=external_prefix,
- )
- content = _rewrite_public_show_runtime_client(content, response_headers, external_prefix=external_prefix)
- content = _rewrite_show_runtime_public_deps(content, response_headers, session_id=session_id)
- content = await _inject_public_show_runtime_preloads(
- content,
- response_headers,
- session_id=session_id,
- asset_path=asset_path,
- external_prefix=external_prefix,
- forwarded_headers=forwarded_headers,
- )
- content = _strip_public_show_runtime_inline_source_maps(content, response_headers)
- _apply_show_runtime_cache_headers(
- asset_path,
+ if proxied.status_code == 200 and external_prefix:
+ # Public `/p/<share>/` surface only: rewrite the runtime's internal
+ # `/show/<id>/` paths to the public base and neutralize Vite's HMR client /
+ # React Fast Refresh so anonymous viewers don't open a live dev socket. The
+ # shared vendor bundle is referenced via the runtime's import map at the
+ # session-independent `/_show-runtime/vendor/...` path, so it is untouched here.
+ content = _rewrite_public_show_runtime_private_paths(
+ content,
response_headers,
- status_code=proxied.status_code,
- query=starlette_request.url.query,
+ session_id=session_id,
+ external_prefix=external_prefix,
)
+ content = _rewrite_public_show_runtime_client(content, response_headers, external_prefix=external_prefix)
+ if _should_inject_show_runtime_config(proxied.status_code, response_headers, inject_private_config=inject_private_config):
+ content = _inject_show_runtime_config(content, session_id)
+ _mark_show_runtime_document_no_store(response_headers)
+ elif _is_show_page_entry_asset(asset_path) and 200 <= proxied.status_code < 300:
+ # The entry document is per-session/per-share dynamic (it embeds the import map
+ # and base path); never let it be cached. App modules and per-session deps keep
+ # the runtime's own cache headers (Vite marks optimized deps immutable).
+ _mark_show_runtime_document_no_store(response_headers)
content = _compress_show_runtime_response(content, response_headers, starlette_request)
return FastAPIResponse(content=content, status_code=proxied.status_code, headers=response_headers)
@@ -5839,7 +5780,7 @@ def _should_inject_show_runtime_config(
return _show_response_is_html(_response_header(headers, "content-type"))
-def _strip_mutated_show_runtime_headers(headers: dict[str, str]) -> None:
+def _mark_show_runtime_document_no_store(headers: dict[str, str]) -> None:
for name in ("cache-control", "etag", "expires", "last-modified", "content-length"):
_remove_response_header(headers, name)
headers["Cache-Control"] = "no-store"
@@ -5890,299 +5831,10 @@ def _show_response_is_compressible(content_type: str | None) -> bool:
)
-def _apply_show_runtime_cache_headers(asset_path: str, headers: dict[str, str], *, status_code: int, query: str | None) -> None:
- relative = (asset_path or "").strip("/")
- if not relative or relative == "index.html":
- _remove_response_header(headers, "cache-control")
- headers["Cache-Control"] = "no-store"
- return
- if status_code < 200 or status_code >= 300:
- return
- if _is_show_runtime_immutable_asset(relative):
- if not _show_runtime_dep_version(query):
- return
- _remove_response_header(headers, "cache-control")
- _remove_response_header(headers, "set-cookie")
- headers["Cache-Control"] = _SHOW_RUNTIME_IMMUTABLE_CACHE_CONTROL
-
-
-def _should_redirect_to_public_show_runtime_dep(asset_path: str, starlette_request: FastAPIRequest, status_code: int) -> bool:
- return (
- starlette_request.method == "GET"
- and 200 <= status_code < 300
- and _is_show_runtime_immutable_asset_path(asset_path)
- and bool(_show_runtime_dep_version(starlette_request.url.query))
- and bool(_public_show_runtime_dep_path(asset_path, starlette_request.url.query))
- )
-
-
-def _register_public_show_runtime_dep(asset_path: str, query: str | None, runtime_path: str) -> str:
- public_path = _public_show_runtime_dep_path(asset_path, query)
- version, name = _public_show_runtime_dep_key(asset_path, query)
- _SHOW_RUNTIME_PUBLIC_DEP_REGISTRY[(version, name)] = runtime_path
- return public_path
-
-
-def _public_show_runtime_dep_runtime_path(version: str, asset_name: str) -> str | None:
- runtime_path = _SHOW_RUNTIME_PUBLIC_DEP_REGISTRY.get((version, asset_name))
- if runtime_path:
- return runtime_path
- if not re.fullmatch(r"chunk-[A-Za-z0-9_-]+\.js", asset_name or ""):
- return None
- for (registered_version, _registered_name), registered_path in _SHOW_RUNTIME_PUBLIC_DEP_REGISTRY.items():
- if registered_version != version:
- continue
- base_path = registered_path.split("?", 1)[0].rsplit("/", 1)[0]
- return f"{base_path}/{quote(asset_name, safe='')}"
- return None
-
-
-def _public_show_runtime_dep_path(asset_path: str, query: str | None = None) -> str:
- version, name = _public_show_runtime_dep_key(asset_path, query)
- if not version or not name:
- return ""
- return f"{_SHOW_RUNTIME_PUBLIC_DEP_PREFIX}/{quote(version, safe='')}/{quote(name, safe='')}"
-
-
-def _public_show_runtime_dep_key(asset_path: str, query: str | None = None) -> tuple[str, str]:
- relative = (asset_path or "").strip("/")
- if not _is_show_runtime_immutable_asset_path(relative):
- return "", ""
- name = Path(relative).name
- version = _show_runtime_dep_version(query)
- if not version:
- return "", ""
- return _public_show_runtime_dep_version(version), name
-
-
-def _public_show_runtime_dep_version(vite_version: str) -> str:
- return f"{_SHOW_RUNTIME_PUBLIC_DEP_CACHE_EPOCH}-{vite_version}"
-
-
-def _public_show_runtime_module_version(module_path: str) -> str:
- digest = hashlib.sha256(module_path.encode("utf-8")).hexdigest()[:12]
- return f"{_SHOW_RUNTIME_PUBLIC_DEP_CACHE_EPOCH}-m{digest}"
-
-
-def _show_runtime_dep_version(query: str | None) -> str | None:
- if not query:
- return None
- parsed = dict(parse_qsl(query, keep_blank_values=True))
- value = parsed.get("v")
- if not value:
- return None
- if not re.fullmatch(r"[A-Za-z0-9_-]+", value):
- return None
- return value
-
-
def _show_response_is_rewritable_show_runtime_source(content_type: str | None) -> bool:
return _show_response_is_javascript(content_type) or _show_response_is_html(content_type)
-def _strip_public_show_runtime_inline_source_maps(content: bytes, headers: dict[str, str]) -> bytes:
- content_type = _response_header(headers, "content-type") or ""
- if not _show_response_is_javascript(content_type):
- return content
- stripped = _SHOW_RUNTIME_INLINE_SOURCE_MAP_RE.sub(b"", content)
- if stripped == content:
- return content
- for name in ("content-length", "etag", "sourcemap", "x-sourcemap"):
- _remove_response_header(headers, name)
- if _response_header(headers, "cache-control") != _SHOW_RUNTIME_IMMUTABLE_CACHE_CONTROL:
- _remove_response_header(headers, "cache-control")
- headers["Cache-Control"] = "no-store"
- return stripped
-
-
-async def _inject_public_show_runtime_preloads(
- content: bytes,
- headers: dict[str, str],
- *,
- session_id: str,
- asset_path: str,
- external_prefix: str | None,
- forwarded_headers: dict[str, str],
-) -> bytes:
- if not external_prefix or asset_path.strip("/"):
- return content
- content_type = _response_header(headers, "content-type") or ""
- if not _show_response_is_html(content_type):
- return content
- try:
- text = content.decode("utf-8")
- except UnicodeDecodeError:
- return content
- if 'rel="modulepreload"' in text or "rel='modulepreload'" in text:
- return content
- preload_urls = await _public_show_runtime_preload_urls(
- text,
- session_id=session_id,
- external_prefix=external_prefix,
- forwarded_headers=forwarded_headers,
- )
- if not preload_urls:
- return content
- tags = "\n".join(_public_show_runtime_preload_tag(url) for url in preload_urls)
- injection = f"\n{tags}\n"
- if "</head>" in text:
- rewritten = text.replace("</head>", f"{injection}</head>", 1)
- else:
- rewritten = f"{injection}{text}"
- _strip_mutated_show_runtime_headers(headers)
- return rewritten.encode("utf-8")
-
-
-async def _public_show_runtime_preload_urls(
- html_text: str,
- *,
- session_id: str,
- external_prefix: str,
- forwarded_headers: dict[str, str],
-) -> list[str]:
- urls: list[str] = []
- seen: set[str] = set()
- import_scan_queue: deque[tuple[str, int]] = deque()
- scanned_imports: set[str] = set()
-
- def add_url(url: str) -> None:
- if url and url not in seen and not url.endswith("/@vite/client") and "/@react-refresh" not in url:
- seen.add(url)
- urls.append(url)
-
- def queue_import_scan(url: str, depth: int) -> None:
- if depth < 0 or not _should_scan_public_show_runtime_imports(url, external_prefix=external_prefix):
- return
- if url not in scanned_imports:
- import_scan_queue.append((url, depth))
-
- for match in _SHOW_RUNTIME_MODULE_SCRIPT_SRC_RE.finditer(html_text):
- src = html.unescape(match.group("src"))
- normalized = _resolve_public_show_runtime_url(src, base_url=f"{external_prefix.rstrip('/')}/")
- add_url(normalized)
- queue_import_scan(normalized, 1)
- if normalized.endswith("/src/main.tsx"):
- queue_import_scan(_resolve_public_show_runtime_url("./App.tsx", base_url=normalized), 1)
- while import_scan_queue and len(urls) < 32:
- scan_url, depth = import_scan_queue.popleft()
- if scan_url in scanned_imports:
- continue
- scanned_imports.add(scan_url)
- for imported_url in await _public_show_runtime_direct_import_urls(
- scan_url,
- session_id=session_id,
- external_prefix=external_prefix,
- forwarded_headers=forwarded_headers,
- ):
- add_url(imported_url)
- if depth > 0:
- queue_import_scan(imported_url, depth - 1)
- return urls[:32]
-
-
-async def _public_show_runtime_direct_import_urls(
- public_url: str,
- *,
- session_id: str,
- external_prefix: str,
- forwarded_headers: dict[str, str],
-) -> list[str]:
- asset_path = _public_show_runtime_asset_path(public_url, external_prefix=external_prefix)
- runtime_path = None
- if asset_path:
- runtime_path = f"/sessions/{quote(session_id, safe='')}/app/{quote(asset_path, safe='/@:-._~')}"
- else:
- runtime_path = _public_show_runtime_dep_asset_path(public_url)
- if not runtime_path:
- return []
- from core.show_runtime import get_show_runtime_manager
-
- try:
- proxied = await get_show_runtime_manager().request(
- "GET",
- runtime_path,
- headers=forwarded_headers,
- body=None,
- )
- except Exception:
- logger.debug("Failed to inspect Show Runtime preload imports for %s", public_url, exc_info=True)
- return []
- if proxied.status_code != 200:
- return []
- response_headers = {
- key: value
- for key, value in proxied.headers.items()
- if key.lower() in _SHOW_RUNTIME_RESPONSE_HEADER_ALLOWLIST
- }
- import_content = _rewrite_public_show_runtime_private_paths(
- proxied.content,
- response_headers,
- session_id=session_id,
- external_prefix=external_prefix,
- )
- import_content = _rewrite_public_show_runtime_client(import_content, response_headers, external_prefix=external_prefix)
- import_content = _rewrite_show_runtime_public_deps(import_content, response_headers, session_id=session_id)
- try:
- text = import_content.decode("utf-8")
- except UnicodeDecodeError:
- return []
- urls: list[str] = []
- for match in _SHOW_RUNTIME_IMPORT_SPECIFIER_RE.finditer(text):
- import_path = match.group("path") or match.group("dynamic_path")
- if not import_path:
- continue
- if import_path.startswith(("http://", "https://")):
- continue
- urls.append(_resolve_public_show_runtime_url(import_path, base_url=public_url))
- return urls
-
-
-def _resolve_public_show_runtime_url(value: str, *, base_url: str) -> str:
- if value.startswith("/"):
- return value
- base = base_url.split("?", 1)[0].split("#", 1)[0]
- base_dir = base if base.endswith("/") else base.rsplit("/", 1)[0] + "/"
- return urljoin(base_dir, value)
-
-
-def _is_public_show_runtime_local_source_url(url: str, *, external_prefix: str) -> bool:
- public_prefix = f"{external_prefix.rstrip('/')}/"
- return url.startswith(public_prefix) and ("/src/" in url or url.endswith("/src/main.tsx"))
-
-
-def _should_scan_public_show_runtime_imports(url: str, *, external_prefix: str) -> bool:
- if _is_public_show_runtime_local_source_url(url, external_prefix=external_prefix):
- return True
- parsed = urlparse(url)
- path = parsed.path
- return path.startswith(f"{_SHOW_RUNTIME_PUBLIC_DEP_PREFIX}/{_SHOW_RUNTIME_PUBLIC_DEP_CACHE_EPOCH}-m")
-
-
-def _public_show_runtime_asset_path(public_url: str, *, external_prefix: str) -> str | None:
- public_prefix = f"{external_prefix.rstrip('/')}/"
- normalized = public_url.split("?", 1)[0].split("#", 1)[0]
- if not normalized.startswith(public_prefix):
- return None
- return normalized[len(public_prefix) :]
-
-
-def _public_show_runtime_dep_asset_path(public_url: str) -> str | None:
- parsed = urlparse(public_url)
- parts = [unquote(part) for part in parsed.path.strip("/").split("/")]
- if len(parts) < 4 or parts[0] != "_show-runtime" or parts[1] != "deps":
- return None
- version = parts[2]
- asset_name = "/".join(parts[3:])
- if not re.fullmatch(r"[A-Za-z0-9_-]+", version or "") or not re.fullmatch(r"[A-Za-z0-9_@./-]+", asset_name or ""):
- return None
- return _public_show_runtime_dep_runtime_path(version, asset_name)
-
-
-def _public_show_runtime_preload_tag(url: str) -> str:
- escaped = html.escape(url, quote=True)
- return f'<link rel="modulepreload" href="{escaped}">'
-
-
def _rewrite_public_show_runtime_client(
content: bytes,
headers: dict[str, str],
@@ -6203,68 +5855,7 @@ def _rewrite_public_show_runtime_client(
rewritten = rewritten.replace(f"{public_prefix}@react-refresh", _SHOW_RUNTIME_PUBLIC_REACT_REFRESH_SHIM_PATH)
if rewritten == text:
return content
- _strip_mutated_show_runtime_headers(headers)
- return rewritten.encode("utf-8")
-
-
-def _rewrite_public_show_runtime_dep_client(
- content: bytes,
- headers: dict[str, str],
- *,
- runtime_path: str,
-) -> bytes:
- content_type = _response_header(headers, "content-type") or ""
- if not _show_response_is_rewritable_show_runtime_source(content_type):
- return content
- if "/sessions/" not in runtime_path or "/app/" not in runtime_path:
- return content
- try:
- text = content.decode("utf-8")
- except UnicodeDecodeError:
- return content
- session_part = runtime_path.split("/sessions/", 1)[1].split("/app/", 1)[0]
- session_id = unquote(session_part)
- private_prefix = f"/show/{quote(session_id, safe='')}/"
- rewritten = text.replace(f"{private_prefix}@vite/client", _SHOW_RUNTIME_PUBLIC_CLIENT_SHIM_PATH)
- rewritten = rewritten.replace(f"{private_prefix}@react-refresh", _SHOW_RUNTIME_PUBLIC_REACT_REFRESH_SHIM_PATH)
- if rewritten == text:
- return content
- _strip_mutated_show_runtime_headers(headers)
- return rewritten.encode("utf-8")
-
-
-def _rewrite_show_runtime_public_deps(content: bytes, headers: dict[str, str], *, session_id: str) -> bytes:
- content_type = _response_header(headers, "content-type") or ""
- if not _show_response_is_javascript(content_type):
- return content
- try:
- text = content.decode("utf-8")
- except UnicodeDecodeError:
- return content
-
- mutated = False
-
- def register_dep(match: re.Match[str], *, allow_unversioned: bool) -> str:
- nonlocal mutated
- vite_version = match.group("version")
- dep_path = _normalize_show_runtime_dep_import_path(match.group("path"))
- if vite_version:
- version = _public_show_runtime_dep_version(vite_version)
- elif allow_unversioned:
- version = _public_show_runtime_module_version(dep_path)
- else:
- return match.group(0)
- name = Path(match.group("path")).name
- _SHOW_RUNTIME_PUBLIC_DEP_REGISTRY[(version, name)] = f"/sessions/{quote(session_id, safe='')}/app/{quote(dep_path, safe='/@:-._~')}"
- mutated = True
- public_path = _public_show_runtime_dep_import_url(version, name, vite_version)
- return f"{match.group('quote')}{public_path}{match.group('rest')}{match.group('quote')}"
-
- rewritten = _SHOW_RUNTIME_PUBLIC_DEP_RE.sub(lambda match: register_dep(match, allow_unversioned=False), text)
- rewritten = _SHOW_RUNTIME_PUBLIC_MODULE_RE.sub(lambda match: register_dep(match, allow_unversioned=True), rewritten)
- if not mutated:
- return content
- _strip_mutated_show_runtime_headers(headers)
+ _mark_show_runtime_document_no_store(headers)
return rewritten.encode("utf-8")
@@ -6289,80 +5880,10 @@ def _rewrite_public_show_runtime_private_paths(
rewritten = text.replace(private_prefix, public_prefix)
if rewritten == text:
return content
- _strip_mutated_show_runtime_headers(headers)
- return rewritten.encode("utf-8")
-
-
-def _normalize_show_runtime_dep_import_path(dep_path: str) -> str:
- marker_index = dep_path.find("@fs/")
- if marker_index >= 0:
- return dep_path[marker_index:]
- if dep_path.startswith("/"):
- return dep_path[1:]
- if dep_path.startswith("./"):
- return dep_path[2:]
- return dep_path
-
-
-def _rewrite_public_show_runtime_dep_siblings(
- content: bytes,
- headers: dict[str, str],
- *,
- version: str,
- runtime_path: str,
-) -> bytes:
- content_type = _response_header(headers, "content-type") or ""
- if not _show_response_is_javascript(content_type):
- return content
- try:
- text = content.decode("utf-8")
- except UnicodeDecodeError:
- return content
- base_runtime_path = runtime_path.split("?", 1)[0].rsplit("/", 1)[0]
- runtime_app_prefix = runtime_path.split("?", 1)[0].split("/app/", 1)[0] + "/app/"
- mutated = False
-
- def register_public_dep(dep_path: str, dep_version: str | None) -> str:
- nonlocal mutated
- name = Path(dep_path).name
- normalized_dep_path = _normalize_show_runtime_dep_import_path(dep_path)
- registered_version = _public_show_runtime_dep_version(dep_version) if dep_version else _public_show_runtime_module_version(normalized_dep_path)
- registered_runtime_path = f"{runtime_app_prefix}{quote(normalized_dep_path, safe='/@:-._~')}"
- _SHOW_RUNTIME_PUBLIC_DEP_REGISTRY[(registered_version, name)] = registered_runtime_path
- mutated = True
- return _public_show_runtime_dep_import_url(registered_version, name, dep_version)
-
- def replace_relative_sibling(match: re.Match[str]) -> str:
- nonlocal mutated
- sibling_name = match.group("name")
- sibling_runtime_path = f"{base_runtime_path}/{quote(sibling_name, safe='')}"
- sibling_version = match.group("version")
- registered_version = _public_show_runtime_dep_version(sibling_version) if sibling_version else version
- _SHOW_RUNTIME_PUBLIC_DEP_REGISTRY[(registered_version, sibling_name)] = sibling_runtime_path
- mutated = True
- public_path = _public_show_runtime_dep_import_url(registered_version, sibling_name, sibling_version)
- return f"{match.group('quote')}{public_path}{match.group('rest')}{match.group('quote')}"
-
- def replace_absolute_dep(match: re.Match[str]) -> str:
- public_path = register_public_dep(match.group("path"), match.group("version"))
- return f"{match.group('quote')}{public_path}{match.group('rest')}{match.group('quote')}"
-
- rewritten = _SHOW_RUNTIME_PUBLIC_DEP_SIBLING_RE.sub(replace_relative_sibling, text)
- rewritten = _SHOW_RUNTIME_PUBLIC_DEP_RE.sub(replace_absolute_dep, rewritten)
- rewritten = _SHOW_RUNTIME_PUBLIC_MODULE_RE.sub(replace_absolute_dep, rewritten)
- if not mutated:
- return content
- _strip_mutated_show_runtime_headers(headers)
+ _mark_show_runtime_document_no_store(headers)
return rewritten.encode("utf-8")
-def _public_show_runtime_dep_import_url(version: str, asset_name: str, dep_version: str | None) -> str:
- public_path = f"{_SHOW_RUNTIME_PUBLIC_DEP_PREFIX}/{quote(version, safe='')}/{quote(asset_name, safe='')}"
- if dep_version:
- return f"{public_path}?v={quote(dep_version, safe='')}"
- return public_path
-
-
def _show_response_is_javascript(content_type: str | None) -> bool:
if not content_type:
return False
@@ -6395,9 +5916,9 @@ def _is_show_runtime_immutable_asset_path(asset_path: str) -> bool:
def _is_current_show_runtime_immutable_asset_request() -> bool:
- path = (request.path or "").strip("/")
- if path.startswith("_show-runtime/deps/"):
+ if (request.path or "").startswith(f"{_SHOW_RUNTIME_VENDOR_PREFIX}/"):
return True
+ path = (request.path or "").strip("/")
parts = path.split("/", 2)
if len(parts) < 3 or parts[0] not in {"show", "p"}:
return False