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-pages): support History router deep links (#980)

Call White18690130618e
diff --git a/core/show_pages.py b/core/show_pages.py
index 17db6e3f3..87bcf3736 100644
--- a/core/show_pages.py
+++ b/core/show_pages.py
@@ -1055,12 +1055,14 @@ def show_page_payload(page: ShowPage, *, config: V2Config | None = None) -> dict
def _write_default_runtime_files(page_dir: Path, session_id: str) -> None:
+ app_path = page_dir / "src" / "App.tsx"
+ fresh_workspace = not app_path.exists()
# Runtime-owned app shell + always-present workspace files. Each is written
# once and skipped if it already exists, so an existing workspace keeps its
# own copies (see the skip-if-exists loop below).
files: dict[str, str] = {
"index.html": _default_index_html(session_id),
- "src/main.tsx": _default_main_tsx(),
+ "src/main.tsx": _default_main_tsx(include_legacy_hash_redirect=fresh_workspace),
"src/styles.css": _default_styles_css(),
"api/health.ts": _default_api_health_ts(),
}
@@ -1073,13 +1075,15 @@ def _write_default_runtime_files(page_dir: Path, session_id: str) -> None:
# starting point to extend or replace, not a required structure. Adding a page
# later is just a new file under ``src/pages/`` — the router discovers it and
# the runtime-owned shell (``index.html`` / ``src/main.tsx``) is never touched.
- if not (page_dir / "src" / "App.tsx").exists():
+ if fresh_workspace:
files.update(
{
- "src/App.tsx": _default_app_tsx(),
"src/router.tsx": _default_router_tsx(),
"src/pages/index.tsx": _default_page_home_tsx(),
"src/pages/second.tsx": _default_page_second_tsx(),
+ # App imports the router, so publish it after every generated
+ # dependency. A partial write remains recognizable as fresh.
+ "src/App.tsx": _default_app_tsx(),
}
)
for relative_path, contents in files.items():
@@ -1097,6 +1101,7 @@ def _default_index_html(session_id: str) -> str:
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
+ <base href="%BASE_URL%">
<title>Show Page {escaped}</title>
<!-- App icon (Avibe Dock / App Library): to give this app an icon, place a
favicon FILE in this workspace — either `favicon.svg` (or .png/.ico) at the
@@ -1352,8 +1357,30 @@ def _escape_html(value: str) -> str:
return value.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
-def _default_main_tsx() -> str:
- return """import React from "react"
+def _default_main_tsx(*, include_legacy_hash_redirect: bool) -> str:
+ legacy_hash_redirect = (
+ """
+function redirectLegacyHashRoute() {
+ if (!window.location.hash.startsWith("#/")) return
+ const configuredBase = globalThis.__AVIBE_SHOW__?.basePath || "/"
+ const basePathname = new URL(configuredBase, window.location.origin).pathname
+ const baseParts = basePathname.split("/").filter(Boolean)
+ const base = baseParts.length ? "/" + baseParts.join("/") + "/" : "/"
+ const legacy = new URL(window.location.hash.slice(1), window.location.origin)
+ const target = new URL(window.location.href)
+ target.pathname = base + legacy.pathname.replace(/^\\/+/, "")
+ for (const [key, value] of legacy.searchParams) target.searchParams.set(key, value)
+ target.hash = legacy.hash
+ window.history.replaceState(window.history.state, "", target)
+}
+
+redirectLegacyHashRoute()
+"""
+ if include_legacy_hash_redirect
+ else ""
+ )
+ return (
+ """import React from "react"
import { createRoot } from "react-dom/client"
import "@avibe/show-ui/styles.css"
import "./styles.css"
@@ -1393,13 +1420,16 @@ globalThis.__AVIBE_SHOW__ = {
streamPath: injected.streamPath ?? "__show/events?stream=1",
writeToken: injected.writeToken ?? readCookie("vibe_show_event_token")
}
-
+"""
+ + legacy_hash_redirect
+ + """
createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<App />
</React.StrictMode>
)
"""
+ )
def _default_app_tsx() -> str:
@@ -1424,21 +1454,17 @@ export default function App() {
def _default_router_tsx() -> str:
- # A tiny, dependency-free hash router with file-based page discovery.
+ # A tiny, dependency-free History router with file-based page discovery.
#
- # Why hash routing: a Show Page is served as a client-only app mounted under a
- # path prefix (/show/<id>/ privately, /p/<share>/ publicly, both proxied to the
- # same managed Vite dev server). With hash routes the browser only ever requests
- # the app root, so deep-linking and refreshing a nested route work identically in
- # both serving modes with no server cooperation, and relative URLs (assets,
- # ./api/* handlers, event endpoints) always resolve. The trade-off is a "#" in
- # the URL, which stays bookmarkable and PWA-installable.
+ # The injected basePath is the authority for both private /show/<id>/ and public
+ # /p/<share>/ surfaces. Their servers provide the matching entry-document
+ # fallback, so clean nested URLs remain refreshable and shareable.
#
# Why file-based discovery: adding a route is just adding a file under src/pages/.
# A folder becomes a nested path segment and a [param] file becomes a dynamic
# segment, so the scaffold is not locked into a flat page list. Nothing here or in
# the app shell needs editing to add a page.
- return """import type { ComponentType, ReactNode } from "react"
+ return """import type { ComponentType, MouseEvent, ReactNode } from "react"
import { useSyncExternalStore } from "react"
export type PageProps = {
@@ -1520,7 +1546,7 @@ export const routes: Route[] = Object.entries(modules)
})
// decodeURIComponent throws on a malformed escape (e.g. a link built with a raw
-// "%", like #/items/50%); fall back to the raw segment so a bad param degrades to
+// "%", like /items/50%); fall back to the raw segment so a bad param degrades to
// that page instead of throwing during render and blanking the whole app.
function safeDecode(value: string): string {
try {
@@ -1539,7 +1565,7 @@ function matchRoute(path: string): { route: Route | null; params: Record<string,
for (let i = 0; i < parts.length; i++) {
const segment = route.segments[i]
if (segment.dynamic) params[segment.name] = safeDecode(parts[i])
- else if (segment.name !== parts[i]) {
+ else if (segment.name !== safeDecode(parts[i])) {
matched = false
break
}
@@ -1549,36 +1575,64 @@ function matchRoute(path: string): { route: Route | null; params: Record<string,
return { route: null, params: {} }
}
-function readHashPath(): string {
- const hash = window.location.hash
- const raw = (hash.startsWith("#") ? hash.slice(1) : hash).split("?")[0]
- if (!raw) return "/"
- const path = raw.startsWith("/") ? raw : "/" + raw
- // Normalize a trailing slash so "/items/" matches the "/items" route.
- return path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path
+function basePath(): string {
+ const configured = globalThis.__AVIBE_SHOW__?.basePath
+ const fallback = window.location.pathname.match(/^\\/(?:show|p)\\/[^/]+\\//)?.[0] || "/"
+ const pathname = new URL(configured || fallback, window.location.origin).pathname
+ const parts = pathname.split("/").filter(Boolean)
+ return parts.length ? "/" + parts.join("/") + "/" : "/"
+}
+
+function normalizeRoutePath(path: string): string {
+ const withLeadingSlash = path.startsWith("/") ? path : "/" + path
+ return withLeadingSlash.length > 1 && withLeadingSlash.endsWith("/")
+ ? withLeadingSlash.slice(0, -1)
+ : withLeadingSlash
+}
+
+function readRoutePath(): string {
+ const base = basePath()
+ const pathname = window.location.pathname
+ if (!pathname.startsWith(base)) return "/"
+ const routePath = normalizeRoutePath("/" + pathname.slice(base.length))
+ return routePath === "/index.html" ? "/" : routePath
}
function subscribe(onChange: () => void): () => void {
- window.addEventListener("hashchange", onChange)
- return () => window.removeEventListener("hashchange", onChange)
+ window.addEventListener("popstate", onChange)
+ return () => window.removeEventListener("popstate", onChange)
}
export function useRoutePath(): string {
- return useSyncExternalStore(subscribe, readHashPath, () => "/")
+ return useSyncExternalStore(subscribe, readRoutePath, () => "/")
+}
+
+function routeUrl(to: string): URL {
+ const normalizedTo = to.startsWith("/") ? to : "/" + to
+ const route = new URL(normalizedTo, window.location.origin)
+ const current = new URL(window.location.href)
+ const target = new URL(basePath(), window.location.origin)
+ const embed = current.searchParams.get("vibe-embed")
+ target.pathname = basePath() + route.pathname.replace(/^\\/+/, "")
+ target.search = route.search
+ if (embed && !target.searchParams.has("vibe-embed")) target.searchParams.set("vibe-embed", embed)
+ target.hash = route.hash
+ return target
}
export function navigate(to: string): void {
- window.location.hash = to.startsWith("/") ? to : "/" + to
+ const target = routeUrl(to)
+ window.history.pushState({}, "", target)
+ window.dispatchEvent(new PopStateEvent("popstate"))
}
export function Link({ to, className, children }: { to: string; className?: string; children: ReactNode }) {
- // A plain hash anchor: the browser updates the fragment and fires "hashchange"
- // without a full navigation, so no click handler or pushState is needed.
- return (
- <a href={"#" + to} className={className}>
- {children}
- </a>
- )
+ function onClick(event: MouseEvent<HTMLAnchorElement>) {
+ if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return
+ event.preventDefault()
+ navigate(to)
+ }
+ return <a href={routeUrl(to).toString()} className={className} onClick={onClick}>{children}</a>
}
export function RouterView() {
@@ -1592,7 +1646,7 @@ export function RouterView() {
No route matches <code className="rounded bg-muted px-1.5 py-0.5">{path}</code>.
</p>
<p className="mt-4 text-sm">
- <a className="font-medium underline underline-offset-4" href="#/">Back to Home</a>
+ <Link className="font-medium underline underline-offset-4" to="/">Back to Home</Link>
</p>
</div>
)
diff --git a/tests/test_show_pages.py b/tests/test_show_pages.py
index fb9fd0710..9862bafe1 100644
--- a/tests/test_show_pages.py
+++ b/tests/test_show_pages.py
@@ -1610,9 +1610,13 @@ def test_fresh_workspace_scaffolds_placeholder_and_minimal_router(monkeypatch, t
assert "import.meta.glob" in router
assert '"./pages/**/*.tsx"' in router
assert "eager: true" in router
- # Hash-based client routing: nested deep-link + refresh work in both private
- # /show/ and public /p/ serving modes with no server cooperation.
- assert "hashchange" in router
+ # History routing derives its mount point from the injected basePath and uses
+ # clean URLs while preserving iframe mode across client navigation.
+ assert "globalThis.__AVIBE_SHOW__?.basePath" in router
+ assert "popstate" in router
+ assert "pushState" in router
+ assert 'searchParams.get("vibe-embed")' in router
+ assert "hashchange" not in router
assert "useSyncExternalStore" in router
# A concrete path wins over a matching [param] route of the same length.
assert "routeSpecificity" in router
@@ -1626,6 +1630,14 @@ def test_fresh_workspace_scaffolds_placeholder_and_minimal_router(monkeypatch, t
assert "activeLocale" not in router
assert "navItems" not in router
+ # Only the fresh scaffold translates its legacy #/ links once at entry.
+ main = (page_dir / "src" / "main.tsx").read_text(encoding="utf-8")
+ assert "redirectLegacyHashRoute" in main
+ assert 'startsWith("#/")' in main
+ assert "history.replaceState" in main
+ index = (page_dir / "index.html").read_text(encoding="utf-8")
+ assert '<base href="%BASE_URL%">' in index
+
# The home page is the user-facing "building" placeholder: a pulsing dot, and a
# nudge prompt revealed only after a delay. It hints the built-in UI by rendering
# Card + Button, leaving Badge as a commented import.
@@ -1684,10 +1696,32 @@ def test_existing_single_page_workspace_is_preserved(monkeypatch, tmp_path):
# Missing shell/workspace files are still materialized.
assert (page_dir / "index.html").exists()
assert (page_dir / "src" / "main.tsx").exists()
+ assert "redirectLegacyHashRoute" not in (page_dir / "src" / "main.tsx").read_text(encoding="utf-8")
assert (page_dir / "src" / "styles.css").exists()
assert (page_dir / "api" / "health.ts").exists()
+def test_existing_hash_router_workspace_is_preserved(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ page_dir = paths.get_show_page_dir("seshashlegacy")
+ (page_dir / "src").mkdir(parents=True, exist_ok=True)
+ existing = {
+ "index.html": '<div id="root"></div>\n',
+ "src/main.tsx": 'import "./router"\n',
+ "src/App.tsx": "export default function App() { return null }\n",
+ "src/router.tsx": 'window.addEventListener("hashchange", () => {})\n',
+ }
+ for relative, contents in existing.items():
+ target = page_dir / relative
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(contents, encoding="utf-8")
+
+ ensure_show_page_dir("seshashlegacy")
+
+ for relative, contents in existing.items():
+ assert (page_dir / relative).read_text(encoding="utf-8") == contents
+
+
def test_show_path_cli_json_creates_page(monkeypatch, tmp_path, capsys):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
paths.ensure_data_dirs()
diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.py
index 673091bee..77f6b946c 100644
--- a/tests/test_ui_show_pages.py
+++ b/tests/test_ui_show_pages.py
@@ -48,6 +48,7 @@ class _FakeShowRuntimeManager:
extra_headers: dict[str, str] | None = None,
headers_by_path: dict[str, dict[str, str]] | None = None,
bodies_by_path: dict[str, bytes] | None = None,
+ status_by_path: dict[str, int] | None = None,
):
self.body = body
self.fail = fail
@@ -55,6 +56,7 @@ class _FakeShowRuntimeManager:
self.extra_headers = extra_headers or {}
self.headers_by_path = headers_by_path or {}
self.bodies_by_path = bodies_by_path or {}
+ self.status_by_path = status_by_path or {}
self.calls = []
self.websocket_paths = []
self.stopped = False
@@ -70,7 +72,11 @@ class _FakeShowRuntimeManager:
"set-cookie": "__Host-vibe_remote_session=attacker",
"x-runtime-private-header": "secret",
} | self.extra_headers | self.headers_by_path.get(path, {})
- return httpx.Response(self.status_code, content=self.bodies_by_path.get(path, self.body), headers=headers)
+ return httpx.Response(
+ self.status_by_path.get(path, self.status_code),
+ content=self.bodies_by_path.get(path, self.body),
+ headers=headers,
+ )
async def websocket_url(self, path):
self.websocket_paths.append(path)
@@ -377,6 +383,170 @@ def test_private_show_page_uses_runtime_when_available(monkeypatch, tmp_path):
assert "x-vibe-csrf-token" not in manager.calls[0][2]
[email protected]("surface", ["private", "public"])
[email protected]("route_path", ["reports/daily", "users/[email protected]"])
+def test_show_page_history_route_retries_entry_after_runtime_404(monkeypatch, tmp_path, surface, route_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ if surface == "private":
+ _create_show_page("ses123", "private")
+ public_path = f"/show/ses123/{route_path}"
+ expected_base = "/show/ses123/"
+ request_kwargs = {"base_url": "http://127.0.0.1:5123"}
+ else:
+ share_id = _create_show_page("ses123", "public")
+ public_path = f"/p/{share_id}/{route_path}"
+ expected_base = f"/p/{share_id}/"
+ request_kwargs = {
+ "base_url": "https://alex.avibe.bot",
+ "environ_base": _remote_peer(),
+ }
+
+ route_runtime_path = f"/sessions/ses123/app/{route_path}?vibe-embed=1"
+ entry_runtime_path = "/sessions/ses123/app/?vibe-embed=1"
+ entry = (
+ '<!doctype html><html><head><base href="/show/ses123/"></head><body>'
+ '<script type="module" src="/show/ses123/src/main.tsx"></script></body></html>'
+ ).encode()
+ manager = _FakeShowRuntimeManager(
+ status_code=404,
+ status_by_path={entry_runtime_path: 200},
+ bodies_by_path={entry_runtime_path: entry},
+ )
+ set_show_runtime_manager_for_tests(manager)
+ try:
+ response = app.test_client().get(
+ f"{public_path}?vibe-embed=1",
+ headers={"Accept": "text/html"},
+ **request_kwargs,
+ )
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert response.status_code == 200
+ body = response.content.decode()
+ assert f'<base href="{expected_base}">' in body
+ assert f'"basePath":"{expected_base}"' in body
+ assert response.headers["cache-control"] == "no-store"
+ assert [call[1] for call in manager.calls] == [route_runtime_path, entry_runtime_path]
+ if surface == "public":
+ assert all(call[2]["x-vibe-show-base"] == expected_base for call in manager.calls)
+
+
[email protected]("surface", ["private", "public"])
+def test_show_page_history_route_uses_recovery_when_runtime_unavailable(monkeypatch, tmp_path, surface):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ if surface == "private":
+ _create_show_page("ses123", "private")
+ public_path = "/show/ses123/reports/daily"
+ request_kwargs = {"base_url": "http://127.0.0.1:5123"}
+ else:
+ share_id = _create_show_page("ses123", "public")
+ public_path = f"/p/{share_id}/reports/daily"
+ request_kwargs = {
+ "base_url": "https://alex.avibe.bot",
+ "environ_base": _remote_peer(),
+ }
+
+ manager = _FakeShowRuntimeManager(fail=True)
+ set_show_runtime_manager_for_tests(manager)
+ try:
+ response = app.test_client().get(
+ public_path,
+ headers={"Accept": "text/html"},
+ **request_kwargs,
+ )
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert response.status_code == 200
+ assert b"Loading Show Page" in response.content
+ assert b"Ready to visualize" in response.content
+ assert [call[1] for call in manager.calls] == ["/sessions/ses123/app/reports/daily"]
+
+
+ ("asset_path", "accept"),
+ [
+ ("assets/missing.js", "application/javascript"),
+ ("api/missing", "text/html"),
+ ("__show/unknown", "text/html"),
+ ("__show/annotation.js", "text/html"),
+ ],
+)
+def test_private_show_page_does_not_spa_fallback_asset_or_reserved_misses(
+ monkeypatch, tmp_path, asset_path, accept
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_show_page("ses123", "private")
+ manager = _FakeShowRuntimeManager(
+ status_code=404,
+ status_by_path={"/sessions/ses123/app/": 200},
+ bodies_by_path={"/sessions/ses123/app/": b"<html>entry</html>"},
+ )
+ set_show_runtime_manager_for_tests(manager)
+ try:
+ response = app.test_client().get(
+ f"/show/ses123/{asset_path}",
+ base_url="http://127.0.0.1:5123",
+ headers={"Accept": accept},
+ )
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert response.status_code == 404
+ assert [call[1] for call in manager.calls] == [f"/sessions/ses123/app/{asset_path}"]
+
+
+def test_private_show_page_real_extensionless_asset_precedes_spa_fallback(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_show_page("ses123", "private")
+ asset_runtime_path = "/sessions/ses123/app/robots"
+ manager = _FakeShowRuntimeManager(
+ status_code=404,
+ status_by_path={asset_runtime_path: 200, "/sessions/ses123/app/": 200},
+ bodies_by_path={asset_runtime_path: b"real extensionless asset"},
+ headers_by_path={asset_runtime_path: {"content-type": "text/plain"}},
+ )
+ set_show_runtime_manager_for_tests(manager)
+ try:
+ response = app.test_client().get(
+ "/show/ses123/robots",
+ base_url="http://127.0.0.1:5123",
+ headers={"Accept": "text/html"},
+ )
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert response.status_code == 200
+ assert response.content == b"real extensionless asset"
+ assert [call[1] for call in manager.calls] == [asset_runtime_path]
+
+
+def test_private_show_page_real_extensionless_asset_survives_runtime_failure(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_show_page("ses123", "private")
+ (paths.get_show_page_dir("ses123") / "robots").write_text("real extensionless asset", encoding="utf-8")
+ manager = _FakeShowRuntimeManager(fail=True)
+ set_show_runtime_manager_for_tests(manager)
+ try:
+ response = app.test_client().get(
+ "/show/ses123/robots",
+ base_url="http://127.0.0.1:5123",
+ headers={"Accept": "text/html"},
+ )
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert response.status_code == 200
+ assert response.content == b"real extensionless asset"
+ assert [call[1] for call in manager.calls] == ["/sessions/ses123/app/robots"]
+
+
def _icon_token(session_id: str) -> str:
# The correct ?v= token the frontend would send (same source as the payload).
from core.show_pages import show_page_icon_version
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index f356f7203..027ac4ae4 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -8665,6 +8665,24 @@ def _is_show_page_entry_asset(asset_path: str) -> bool:
return relative in {"", "index.html"}
+def _is_show_page_spa_route_request(asset_path: str, starlette_request: FastAPIRequest) -> bool:
+ if starlette_request.method not in {"GET", "HEAD"}:
+ return False
+ relative = _decode_show_page_asset_path(asset_path)
+ if relative in {"", "index.html"}:
+ return True
+ segments = [segment for segment in relative.split("/") if segment]
+ if not segments or segments[0] in {"api", "__show"}:
+ return False
+ if "." not in segments[-1]:
+ return True
+
+ # The runtime gets first refusal for real files. After a 404, Accept is the
+ # remaining distinction between a dotted route parameter (document navigation)
+ # and a missing script/style/image asset.
+ return "text/html" in starlette_request.headers.get("accept", "").lower()
+
+
def _decode_show_page_asset_path(asset_path: str) -> str:
decoded = (asset_path or "").strip("/")
for _ in range(3):
@@ -8814,6 +8832,21 @@ def _show_page_file_response(root: Path, asset_path: str):
return response
+def _show_page_runtime_failure_response(
+ page_dir: Path,
+ session_id: str,
+ asset_path: str,
+ starlette_request: FastAPIRequest,
+):
+ if not _is_show_page_spa_route_request(asset_path, starlette_request):
+ return None
+ if not _is_show_page_entry_asset(asset_path):
+ static_response = _show_page_file_response(page_dir, asset_path)
+ if static_response.status_code != 404:
+ return static_response
+ return _show_page_recovery_response(session_id)
+
+
def _show_session_event_error_response(exc: Exception):
code = getattr(exc, "code", "show_session_event_failed")
status = 404 if code == "session_not_found" else 400
@@ -9481,12 +9514,17 @@ async def _show_page_runtime_response(
from core.show_runtime import get_show_runtime_manager
session_part = quote(session_id, safe="")
- asset_part = quote(asset_path.lstrip("/"), safe="/@:-._~")
- runtime_path = f"/sessions/{session_part}/app/"
- if asset_part:
- runtime_path = f"{runtime_path}{asset_part}"
- if starlette_request.url.query:
- runtime_path = f"{runtime_path}?{starlette_request.url.query}"
+
+ def runtime_app_path(relative_asset_path: str) -> str:
+ asset_part = quote(relative_asset_path.lstrip("/"), safe="/@:-._~")
+ path = f"/sessions/{session_part}/app/"
+ if asset_part:
+ path = f"{path}{asset_part}"
+ if starlette_request.url.query:
+ path = f"{path}?{starlette_request.url.query}"
+ return path
+
+ runtime_path = runtime_app_path(asset_path)
forwarded_headers = {
key: value
for key, value in starlette_request.headers.items()
@@ -9496,14 +9534,32 @@ async def _show_page_runtime_response(
forwarded_headers["x-vibe-show-base"] = f"{external_prefix.rstrip('/')}/"
body = await starlette_request.body()
request_started = time.monotonic()
- proxied = await get_show_runtime_manager().request(
+ manager = get_show_runtime_manager()
+ proxied = await manager.request(
starlette_request.method,
runtime_path,
headers=forwarded_headers,
body=body or None,
)
+ served_entry_fallback = False
+ if proxied.status_code == 404 and _is_show_page_spa_route_request(asset_path, starlette_request):
+ # Compatibility fallback for runtimes predating History-mode serving.
+ # The requested file/handler had first refusal above; only a route-shaped
+ # miss retries the entry document under the same private/public base.
+ runtime_path = runtime_app_path("")
+ proxied = await manager.request(
+ starlette_request.method,
+ runtime_path,
+ headers=forwarded_headers,
+ body=body or None,
+ )
+ served_entry_fallback = True
proxy_duration_ms = int((time.monotonic() - request_started) * 1000)
- if proxy_duration_ms >= SHOW_RUNTIME_SLOW_REQUEST_MS or _is_show_page_entry_asset(asset_path):
+ if (
+ proxy_duration_ms >= SHOW_RUNTIME_SLOW_REQUEST_MS
+ or _is_show_page_entry_asset(asset_path)
+ or served_entry_fallback
+ ):
logger.info(
"Show Runtime proxy %s %s session=%s asset=%s status=%s duration_ms=%s",
starlette_request.method,
@@ -9556,7 +9612,7 @@ async def _show_page_runtime_response(
if external_prefix:
response_headers["Referrer-Policy"] = "same-origin"
_mark_show_runtime_document_no_store(response_headers)
- elif _is_show_page_entry_asset(asset_path) and 200 <= proxied.status_code < 300:
+ elif (_is_show_page_entry_asset(asset_path) or served_entry_fallback) 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).
@@ -10040,9 +10096,14 @@ async def serve_private_show_page(session_id, asset_path):
except Exception:
if _is_show_api_asset(asset_path) or _is_show_annotation_asset(asset_path):
return _show_page_runtime_unavailable_response()
- if _is_show_page_entry_asset(asset_path):
- response = _show_page_recovery_response(page.session_id)
- logger.debug("Show runtime unavailable; serving recovery Show Page", exc_info=True)
+ response = _show_page_runtime_failure_response(
+ page_dir,
+ page.session_id,
+ asset_path,
+ request._request,
+ )
+ if response is not None:
+ logger.debug("Show runtime unavailable; serving fallback Show Page response", exc_info=True)
else:
logger.debug("Show runtime unavailable; serving static Show Page", exc_info=True)
if response is None:
@@ -10173,9 +10234,14 @@ async def serve_public_show_page(share_id, asset_path):
except Exception:
if _is_show_api_asset(asset_path) or _is_show_annotation_asset(asset_path):
return _show_page_runtime_unavailable_response()
- if _is_show_page_entry_asset(asset_path):
- response = _show_page_recovery_response(page.session_id)
- logger.debug("Show runtime unavailable; serving recovery public Show Page", exc_info=True)
+ response = _show_page_runtime_failure_response(
+ page_dir,
+ page.session_id,
+ asset_path,
+ request._request,
+ )
+ if response is not None:
+ logger.debug("Show runtime unavailable; serving fallback public Show Page response", exc_info=True)
else:
logger.debug("Show runtime unavailable; serving static public Show Page", exc_info=True)
if response is None: