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.

fix(show-pages): repair scaffolded subroute Markdown rendering (#1989)

Call White7f3070863440
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 000000000..8cc1428c9
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,3 @@
+# Byte-exact generated resource and released-template migration fixture.
+vibe/show_router.tsx text eol=lf
+tests/fixtures/show_pages/router-history-pre-ssr.tsx text eol=lf
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml
index a71daab54..58ebdf7ed 100644
--- a/.github/workflows/lint.yml
+++ b/.github/workflows/lint.yml
@@ -61,6 +61,43 @@ jobs:
npm run test:inbox-return
npm run test:badge-triggers
+ show-router-integration:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
+ - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
+ with:
+ repository: avibe-bot/vibe-show-runtime
+ # Producer of the checked-in generated router. Release builds export
+ # it again from the same Runtime source as their platform archives.
+ ref: 5a9a6a52f2ae03611d617a659bfd0c1c32389478
+ path: .show-runtime-test
+ - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5
+ with:
+ node-version: "22.14.0"
+ cache: npm
+ cache-dependency-path: .show-runtime-test/package-lock.json
+ - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6
+ with:
+ python-version: "3.12"
+ - name: Install pinned uv
+ run: |
+ python -m pip install --disable-pip-version-check --only-binary=:all: --no-deps uv==0.12.10
+ - uses: actions/cache/restore@caa296126883cff596d87d8935842f9db880ef25 # v5
+ with:
+ path: ~/.cache/uv
+ key: ${{ runner.os }}-${{ runner.arch }}-ci-uv-0.12.10-py3.12-${{ hashFiles('pyproject.toml', 'uv.lock') }}
+ - run: uv sync --frozen --no-install-project
+ - name: Build the real Runtime
+ working-directory: .show-runtime-test
+ run: |
+ npm ci
+ npm run build -w @avibe/show-sdk
+ npm run build -w @avibe/show-ui
+ npm run build -w @avibe/show-runtime
+ - name: Check Python scaffold through Runtime HTTP
+ run: node scripts/check_show_router.mjs --runtime-root .show-runtime-test --python .venv/bin/python
+
build-linux-artifacts:
runs-on: ubuntu-latest
steps:
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
index e30865887..110f3c1f0 100644
--- a/.github/workflows/publish.yml
+++ b/.github/workflows/publish.yml
@@ -124,12 +124,26 @@ jobs:
cache: "npm"
- name: Build Show Runtime bundle
+ shell: bash
run: |
npm ci
npm run build
npm run bundle:vibe-remote
cp dist/vibe-show-runtime-node-*.tgz .
git rev-parse HEAD > show-runtime-ref-${{ matrix.artifact }}.txt
+ node --input-type=module <<'JS'
+ import { mkdtemp, copyFile, rm } from "node:fs/promises"
+ import { tmpdir } from "node:os"
+ import { join } from "node:path"
+ import { ensureSessionTemplate } from "./packages/runtime/dist/templates.js"
+ const workspace = await mkdtemp(join(tmpdir(), "show-router-export-"))
+ try {
+ await ensureSessionTemplate(workspace)
+ await copyFile(join(workspace, "src/router.tsx"), "show-router-${{ matrix.artifact }}.tsx")
+ } finally {
+ await rm(workspace, { recursive: true, force: true })
+ }
+ JS
- name: Upload Show Runtime bundle
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6
@@ -138,6 +152,7 @@ jobs:
path: |
vibe-show-runtime-node-*.tgz
show-runtime-ref-${{ matrix.artifact }}.txt
+ show-router-${{ matrix.artifact }}.tsx
memory-runtime-bundles:
needs: resolve-tag
@@ -224,7 +239,8 @@ jobs:
--tag "${{ needs.resolve-tag.outputs.tag }}" \
--repo "${{ github.repository }}" \
--runtime-ref-file 'runtime-artifacts/show-runtime-ref-*.txt' \
- --output vibe/show_runtime_manifest.json
+ --output vibe/show_runtime_manifest.json \
+ --router-output vibe/show_router.tsx
cp vibe/show_runtime_manifest.json runtime-artifacts/show-runtime-manifest.json
- name: Download Memory Runtime bundles
diff --git a/.github/workflows/release_ai.yml b/.github/workflows/release_ai.yml
index 55f95c850..83b21d3a3 100644
--- a/.github/workflows/release_ai.yml
+++ b/.github/workflows/release_ai.yml
@@ -75,12 +75,26 @@ jobs:
node-version: "22.14.0"
cache: "npm"
- name: Build Show Runtime bundle
+ shell: bash
run: |
npm ci
npm run build
npm run bundle:vibe-remote
cp dist/vibe-show-runtime-node-*.tgz .
git rev-parse HEAD > show-runtime-ref-${{ matrix.artifact }}.txt
+ node --input-type=module <<'JS'
+ import { mkdtemp, copyFile, rm } from "node:fs/promises"
+ import { tmpdir } from "node:os"
+ import { join } from "node:path"
+ import { ensureSessionTemplate } from "./packages/runtime/dist/templates.js"
+ const workspace = await mkdtemp(join(tmpdir(), "show-router-export-"))
+ try {
+ await ensureSessionTemplate(workspace)
+ await copyFile(join(workspace, "src/router.tsx"), "show-router-${{ matrix.artifact }}.tsx")
+ } finally {
+ await rm(workspace, { recursive: true, force: true })
+ }
+ JS
- name: Upload Show Runtime bundle
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6
with:
@@ -88,6 +102,7 @@ jobs:
path: |
vibe-show-runtime-node-*.tgz
show-runtime-ref-${{ matrix.artifact }}.txt
+ show-router-${{ matrix.artifact }}.tsx
memory-runtime-bundles:
runs-on: ${{ matrix.os }}
@@ -170,7 +185,8 @@ jobs:
--tag "${{ github.event.inputs.tag || github.ref_name }}" \
--repo "${{ github.repository }}" \
--runtime-ref-file 'runtime-artifacts/show-runtime-ref-*.txt' \
- --output vibe/show_runtime_manifest.json
+ --output vibe/show_runtime_manifest.json \
+ --router-output vibe/show_router.tsx
- name: Download Memory Runtime bundles
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
diff --git a/core/show_pages.py b/core/show_pages.py
index 0152b8923..72ddcbc6d 100644
--- a/core/show_pages.py
+++ b/core/show_pages.py
@@ -21,6 +21,7 @@ from sqlalchemy.exc import IntegrityError
from config import paths
from config.v2_config import V2Config, config_file_lock
from core.avibe_cloud import avibe_cloud_connect_guidance, base_public_url
+from core.show_router import default_show_router
from core.show_runtime_failures import (
ShowRuntimeFailureClass,
ShowRuntimeRecoveryAction,
@@ -2205,7 +2206,7 @@ def _write_default_runtime_files(page_dir: Path, session_id: str) -> None:
if fresh_workspace:
files.update(
{
- "src/router.tsx": _default_router_tsx(),
+ "src/router.tsx": default_show_router(),
"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
@@ -2218,7 +2219,13 @@ def _write_default_runtime_files(page_dir: Path, session_id: str) -> None:
if target.exists():
continue
target.parent.mkdir(parents=True, exist_ok=True)
- target.write_text(contents, encoding="utf-8")
+ try:
+ # An editor may create a source after the existence check. Seeding
+ # is create-only, never permission to replace authored content.
+ with target.open("x", encoding="utf-8") as handle:
+ handle.write(contents)
+ except FileExistsError:
+ continue
def _default_index_html(session_id: str) -> str:
@@ -2660,210 +2667,6 @@ export default function App() {
"""
-def _default_router_tsx() -> str:
- # A tiny, dependency-free History router with file-based page discovery.
- #
- # 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, MouseEvent, ReactNode } from "react"
-import { useSyncExternalStore } from "react"
-
-export type PageProps = {
- // Values captured from [param] segments, e.g. { id: "42" } for /items/42.
- params: Record<string, string>
-}
-
-type PageModule = { default: ComponentType<PageProps> }
-
-type Segment = { name: string; dynamic: boolean }
-type Route = {
- path: string
- segments: Segment[]
- Component: ComponentType<PageProps>
- dynamic: boolean
-}
-
-const PAGES_PREFIX = "./pages/"
-const PAGE_SUFFIX = ".tsx"
-
-// Eagerly import every page module at build time. This is the discovery
-// mechanism: a new file under src/pages/ automatically registers a route.
-const modules = import.meta.glob<PageModule>("./pages/**/*.tsx", { eager: true })
-
-// "./pages/items/[id].tsx" -> "/items/:id"; "./pages/index.tsx" -> "/".
-// Returns null for framework files (any segment starting with "_"), which lets
-// an agent colocate non-page helpers under src/pages/ without creating a route.
-function filePathToRoute(file: string): string | null {
- const relative = file.slice(PAGES_PREFIX.length, file.length - PAGE_SUFFIX.length)
- const parts = relative.split("/")
- if (parts[parts.length - 1] === "index") parts.pop()
- if (parts.some((part) => part.startsWith("_"))) return null
- const path = parts
- .map((part) => (part.startsWith("[") && part.endsWith("]") ? ":" + part.slice(1, -1) : part))
- .join("/")
- return path ? "/" + path : "/"
-}
-
-function toSegments(path: string): Segment[] {
- if (path === "/") return []
- return path
- .slice(1)
- .split("/")
- .map((part) => (part.startsWith(":") ? { name: part.slice(1), dynamic: true } : { name: part, dynamic: false }))
-}
-
-// Per-segment specificity mask: "0" for a static segment, "1" for a dynamic one.
-// Routes are sorted ascending by this mask (compared left to right), so among
-// routes of the same length a static segment always beats a [param] at the same
-// position — e.g. /items/new wins over /items/:id, and /users/:id/edit wins over
-// /users/:id/:action.
-function routeSpecificity(segments: Segment[]): string {
- return segments.map((segment) => (segment.dynamic ? "1" : "0")).join("")
-}
-
-// A page's default export is renderable if it is a function component or a React
-// "exotic" component (memo/forwardRef/lazy/…) — an object carrying $$typeof.
-// Rejecting by `typeof === "function"` alone would drop memo()/forwardRef() pages.
-function isRenderablePage(value: unknown): value is ComponentType<PageProps> {
- return (
- typeof value === "function" ||
- (typeof value === "object" && value !== null && "$$typeof" in value)
- )
-}
-
-export const routes: Route[] = Object.entries(modules)
- .map(([file, mod]): Route | null => {
- const path = filePathToRoute(file)
- if (!path || !isRenderablePage(mod.default)) return null
- const segments = toSegments(path)
- return { path, segments, Component: mod.default, dynamic: segments.some((s) => s.dynamic) }
- })
- .filter((route): route is Route => route !== null)
- .sort((a, b) => {
- const specA = routeSpecificity(a.segments)
- const specB = routeSpecificity(b.segments)
- if (specA !== specB) return specA < specB ? -1 : 1
- return a.path.localeCompare(b.path)
- })
-
-// 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
-// that page instead of throwing during render and blanking the whole app.
-function safeDecode(value: string): string {
- try {
- return decodeURIComponent(value)
- } catch {
- return value
- }
-}
-
-function matchRoute(path: string): { route: Route | null; params: Record<string, string> } {
- const parts = path === "/" ? [] : path.slice(1).split("/")
- for (const route of routes) {
- if (route.segments.length !== parts.length) continue
- const params: Record<string, string> = {}
- let matched = true
- 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 !== safeDecode(parts[i])) {
- matched = false
- break
- }
- }
- if (matched) return { route, params }
- }
- return { route: null, params: {} }
-}
-
-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("popstate", onChange)
- return () => window.removeEventListener("popstate", onChange)
-}
-
-export function useRoutePath(): string {
- 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 {
- 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 }) {
- 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() {
- const path = useRoutePath()
- const { route, params } = matchRoute(path)
- if (!route) {
- return (
- <div className="rounded-lg border border-border bg-card p-6 text-card-foreground">
- <h1 className="text-lg font-semibold">Page not found</h1>
- <p className="mt-2 text-sm text-muted-foreground">
- No route matches <code className="rounded bg-muted px-1.5 py-0.5">{path}</code>.
- </p>
- <p className="mt-4 text-sm">
- <Link className="font-medium underline underline-offset-4" to="/">Back to Home</Link>
- </p>
- </div>
- )
- }
- const Page = route.Component
- return <Page params={params} />
-}
-"""
-
-
def _default_page_home_tsx() -> str:
# Default landing page: a live "building" placeholder the user sees right after
# clicking "Visualize". A pulsing dot signals work in progress; after a delay
diff --git a/core/show_router.py b/core/show_router.py
new file mode 100644
index 000000000..334fe484d
--- /dev/null
+++ b/core/show_router.py
@@ -0,0 +1,9 @@
+"""Load the Runtime-authored router for new Show Page workspaces."""
+
+from __future__ import annotations
+
+from importlib.resources import files
+
+
+def default_show_router() -> str:
+ return files("vibe").joinpath("show_router.tsx").read_text(encoding="utf-8")
diff --git a/docs/plans/show-router-ssr-scaffold.md b/docs/plans/show-router-ssr-scaffold.md
new file mode 100644
index 000000000..052ecd335
--- /dev/null
+++ b/docs/plans/show-router-ssr-scaffold.md
@@ -0,0 +1,128 @@
+# Show Page router SSR contract
+
+Issue: avibe-bot/avibe#1984.
+
+## Outcome and ownership
+
+Fresh Python-created Show Pages must render their actual nested route as Markdown.
+The Runtime's `packages/runtime/src/templates.ts` owns the router implementation.
+Avibe ships its generated `src/router.tsx` as a package resource, rather than
+maintaining another implementation in a Python string. The existing Runtime
+`ensureSessionTemplate()` API produces that resource; no new Runtime API or
+unmerged dependency is required.
+
+Release builds export the router from the same Runtime build as their archives
+and require identical output across platforms. A checked-in generated resource
+keeps source checkouts and offline creation usable. A cross-repository test uses
+the real Python initializer and the real Runtime Markdown endpoint, and checks
+the packaged resource against the Runtime generator.
+
+## Existing workspaces
+
+Never rewrite an existing editable router during initialization or a request.
+An editor does not participate in Avibe's locks, and a final comparison followed
+by rename cannot prevent overwriting a save in that window.
+
+Runtime's existing SSR module plugin supplies its current generated router only
+when the module source exactly matches the released Python History-router
+template. Match complete source fingerprints, not the absence of an SSR export.
+The released LF and Windows CRLF SHA-256 values are respectively
+`1154739b3e21e2f1c7f45e3d0b7454dc5541fdf15e2c79bbc2f96f766338706e` and
+`ed7cbd0aa11a491ac8b7621b8a7ea64d7c83c0b53ec46e950cca95b7f4d0079e`.
+Fingerprint the exact source being transformed, rather than rereading a path
+whose contents may change. Reuse the authored Runtime template without copying
+its implementation or creating temporary workspaces.
+
+This compatibility applies only to the Markdown SSR environment of the ordinary
+workspace router module. Ordinary API SSR, browser HTML/client modules, and files
+on disk remain unchanged. Unknown/custom,
+hash, routerless, and symlink routers retain existing behavior. Module
+invalidation must observe later custom edits. Exercise HTML-first and
+Markdown-first requests, LF/CRLF, non-ASCII routes, and concurrent edits.
+Retain the legacy router's existing exported fields and semantics, including
+`routes[].dynamic`, when adding SSR support. Legacy-compatible root renders keep
+their existing request-scoped read-only location facade and static Motion
+configuration; genuinely modern providers do not acquire browser globals.
+An internal compatibility variant may extend the shared Runtime author without
+changing its default fresh-scaffold output or creating another implementation.
+Avibe's fresh scaffold works with the existing default-branch Runtime contract;
+old-stock SSR compatibility additionally requires Runtime companion PR #70.
+
+### Review scope decision
+
+The first reviewed Avibe head, `638b7a78ec`, received three findings: the
+check/rename race, read-only filesystem errors, and blocking request-path I/O.
+There is one findings-bearing head and no repeated-class circuit-breaker trigger.
+The orchestrator removes the source migration rather than adding further
+checks or locks that external editors cannot honor. Loading compatibility in
+Runtime preserves the intended old-page SSR outcome without mutation, and
+removes the other two findings at their source. No database or public protocol
+changes are required. Runtime owns the compatibility implementation; Avibe owns
+the generated resource, packaging, and cross-repository acceptance.
+
+The Runtime compatibility rewrite subsequently received findings on two reviewed
+heads: `17637f8477` changed ordinary API router exports, and `0c9d99c0a7` still
+changed those exports for Markdown consumers and removed the legacy root location
+facade. These share a root cause: treating a legacy-compatible router as a wholly
+modern router. The repeated-class circuit breaker stopped further edits/pushes.
+Independent HTTP comparison additionally found that the same transition removed
+the legacy static Motion configuration. The orchestrator's scope decision retains
+all three existing contracts inside the shared template and entry/worker flow,
+without filesystem migration, a second module graph, broader sandbox globals, or
+new invalidation behavior. Real legacy page consumers in the combined integration
+test verify route fields, root location, and static rendering against the released
+producer as well as the Runtime companion.
+
+## Runtime error boundary
+
+The worker rejects a non-root request without a renderable `SsrRouterProvider`
+with the stable code `router_not_ssr_capable`. The parent recognizes this typed
+worker error and returns HTTP 502 with that code and the fixed public message:
+
+> This Show Page router does not support Markdown for subpages. Export an SSR-capable SsrRouterProvider from src/router.tsx.
+
+The structured failure log records the same code and message. Never expose an
+arbitrary workspace error or stack. Root-only fallback remains supported. The
+Runtime error improvement is independently deployable; the Python scaffold fix
+works with the already released SSR provider contract.
+Avibe's HTTP error allowlist also recognizes `router_not_ssr_capable`, so the
+fixed Runtime message reaches both private and public callers unchanged.
+
+## Regenerating and checking the source resource
+
+The checked-in resource was generated from Runtime commit
+`5a9a6a52f2ae03611d617a659bfd0c1c32389478`. After building the Runtime checkout:
+
+```sh
+node scripts/sync_show_router.mjs --runtime-module ../vibe-show-runtime/packages/runtime/dist/templates.js
+node scripts/check_show_router.mjs --runtime-root ../vibe-show-runtime --python .venv/bin/python
+```
+
+The `show-router-integration` CI job pins that producer and checks byte parity,
+then runs the real HTTP renderer for fresh nested SSR and legacy root/HTML
+fallback while asserting that no source files change. Combined acceptance
+against Runtime companion PR #70 adds `--legacy-router-ssr` to the same command
+to require legacy LF/CRLF nested SSR as well. The default-branch CI does not
+pretend that the old producer implements this new compatibility behavior.
+When intentionally refreshing this resource,
+update that producer pin too. Official and GitHub-only releases export the router
+from each actual platform build, verify parity, and package that output alongside
+the matching generated manifest. No Node process is needed to create a page.
+
+## Acceptance
+
+- Real Markdown renders for root, static and dynamic routes, query strings,
+ non-ASCII values, and private/public bases; generated links retain their base.
+- Real HTML remains available for the same workspace.
+- Known old stock routers render nested Markdown through Runtime compatibility
+ while retaining their bytes and metadata. Initialization and requests never
+ rewrite existing routers, including unknown/custom/legacy/symlink routers.
+- Custom non-SSR routers receive an actionable, sanitized error for subpages.
+- Legacy pages consuming exported route fields and the root-only location facade
+ keep working; root Motion rendering remains static. Private/public requests do
+ not reuse another request's location. Fresh scaffold output remains unchanged.
+- Wheel and sdist contain the generated router resource.
+- Release export and integration checks detect future template drift.
+
+No database migration, runtime restart, production update, or bulk live-workspace
+rewrite is part of this change.
diff --git a/hatch_build.py b/hatch_build.py
index 108492863..beaa6a662 100644
--- a/hatch_build.py
+++ b/hatch_build.py
@@ -8,6 +8,7 @@ from hatchling.builders.hooks.plugin.interface import BuildHookInterface
MANIFEST_SOURCE = Path("vibe/show_runtime_manifest.json")
MANIFEST_WHEEL_PATH = "vibe/show_runtime_manifest.json"
+ROUTER_PATH = "vibe/show_router.tsx"
_VALIDATION = run_path(str(Path(__file__).parent / "scripts" / "show_runtime_manifest_asset.py"))
validate_manifest_bytes = _VALIDATION["validate_manifest_bytes"]
validate_manifest_file = _VALIDATION["validate_manifest_file"]
@@ -21,6 +22,8 @@ class CustomBuildHook(BuildHookInterface):
if version == "editable":
return
validate_manifest_file(Path(self.root) / MANIFEST_SOURCE)
+ if not (Path(self.root) / ROUTER_PATH).is_file():
+ raise RuntimeError(f"Cannot build Avibe without the generated {ROUTER_PATH}")
def finalize(self, version: str, build_data: dict, artifact_path: str) -> None:
if version == "editable":
@@ -31,6 +34,12 @@ class CustomBuildHook(BuildHookInterface):
content = wheel.read(MANIFEST_WHEEL_PATH)
except KeyError as exc:
raise RuntimeError(f"Built wheel is missing {MANIFEST_WHEEL_PATH}") from exc
+ try:
+ router = wheel.read(ROUTER_PATH)
+ except KeyError as exc:
+ raise RuntimeError(f"Built wheel is missing {ROUTER_PATH}") from exc
+ if router != (Path(self.root) / ROUTER_PATH).read_bytes():
+ raise RuntimeError(f"Built wheel contains a stale {ROUTER_PATH}")
try:
validate_manifest_bytes(content)
except ValueError as exc:
diff --git a/scripts/check_show_router.mjs b/scripts/check_show_router.mjs
new file mode 100644
index 000000000..867f65811
--- /dev/null
+++ b/scripts/check_show_router.mjs
@@ -0,0 +1,149 @@
+#!/usr/bin/env node
+// Exercise the real Python initializer against the real Runtime HTTP renderer.
+import assert from "node:assert/strict"
+import { execFileSync } from "node:child_process"
+import { mkdtemp, readFile, rm, writeFile, mkdir, stat } from "node:fs/promises"
+import { tmpdir } from "node:os"
+import { dirname, join, resolve } from "node:path"
+import { fileURLToPath, pathToFileURL } from "node:url"
+import { parseArgs } from "node:util"
+
+const repository = resolve(dirname(fileURLToPath(import.meta.url)), "..")
+const { values } = parseArgs({
+ options: {
+ "runtime-root": { type: "string" },
+ python: { type: "string", default: "python3" },
+ "legacy-router-ssr": { type: "boolean", default: false }
+ }
+})
+if (!values["runtime-root"]) throw new Error("--runtime-root is required")
+const runtimeRoot = resolve(values["runtime-root"])
+const { startShowRuntimeServer } = await import(pathToFileURL(join(runtimeRoot, "packages/runtime/dist/server.js")).href)
+const temporary = await mkdtemp(join(tmpdir(), "avibe-python-router-check-"))
+const workspaceRoot = join(temporary, "show")
+const sessions = ["sesfresh", "seslegacylf", "seslegacycrlf"]
+const originalRouters = new Map()
+let server
+async function routerSnapshot(workspace) {
+ const path = join(workspace, "src/router.tsx")
+ const info = await stat(path)
+ return {
+ source: await readFile(path, "utf8"),
+ inode: info.ino,
+ mode: info.mode,
+ mtimeMs: info.mtimeMs
+ }
+}
+function initialize(sessionId) {
+ execFileSync(values.python, [
+ "-c",
+ "import sys; from core.show_pages import ensure_show_page_dir; ensure_show_page_dir(sys.argv[1])",
+ sessionId
+ ], { cwd: repository, env: { ...process.env, AVIBE_HOME: temporary }, stdio: "pipe" })
+}
+try {
+ execFileSync(process.execPath, [
+ join(repository, "scripts/sync_show_router.mjs"),
+ "--runtime-module", join(runtimeRoot, "packages/runtime/dist/templates.js"),
+ "--check"
+ ], { stdio: "inherit" })
+ for (const sessionId of sessions) {
+ initialize(sessionId)
+ const workspace = join(workspaceRoot, sessionId)
+ if (sessionId !== "sesfresh") {
+ const legacy = await readFile(
+ join(repository, "tests/fixtures/show_pages/router-history-pre-ssr.tsx"), "utf8"
+ )
+ await writeFile(join(workspace, "src/router.tsx"),
+ sessionId === "seslegacycrlf" ? legacy.replaceAll("\n", "\r\n") : legacy)
+ }
+ originalRouters.set(sessionId, await routerSnapshot(workspace))
+ // Exercise initialization for LF; CRLF is a Markdown-first legacy access.
+ if (sessionId === "seslegacylf") initialize(sessionId)
+ if (sessionId !== "sesfresh") {
+ // Stock routers can have pages that consume the released exports and
+ // root fallback. Compatibility must preserve those existing callers.
+ await writeFile(join(workspace, "src/pages/index.tsx"), `
+import { useContext } from "react"
+import { MotionConfigContext } from "motion/react"
+import { routes } from "../router"
+export default function Home() {
+ const motion = useContext(MotionConfigContext)
+ return <main><h1>Building your Show Page</h1>
+ <p>Dynamic routes: {routes.filter((route) => route.dynamic).length}</p>
+ <p>Root location: {window.location.pathname}</p>
+ <p>Root query: {new URLSearchParams(window.location.search).get("period")}</p>
+ <p>Read-only location: {String(Object.isFrozen(window) && Object.isFrozen(window.location))}</p>
+ <p>Static motion: {String(motion.isStatic)}</p></main>
+}
+`)
+ }
+ await mkdir(join(workspace, "src/pages/items"), { recursive: true })
+ await writeFile(join(workspace, "src/pages/items/[id].tsx"), `
+import { Link, ${sessionId === "sesfresh" ? "" : "routes, "}type PageProps } from "../../router"
+export default function Item({ params, query }: PageProps) {
+ return <main><h1>Item {params.id}</h1><p>View {query.get("view")}</p>
+ ${sessionId === "sesfresh" ? "" : '<p>Legacy dynamic field: {String(routes.find((route) => route.path === "/items/:id")?.dynamic)}</p>'}
+ <Link to="/second?from=detail">Second page</Link></main>
+}
+`)
+ }
+ server = await startShowRuntimeServer({
+ workspaceRoot,
+ dependencyRoot: runtimeRoot,
+ cacheRoot: join(temporary, "cache"),
+ idlePruneIntervalMs: 0
+ })
+ for (const sessionId of sessions) {
+ for (const basePath of [`/show/${sessionId}/`, "/p/public-share/"]) {
+ const headers = {
+ "x-vibe-show-base": basePath,
+ "x-avibe-show-protocol": "1",
+ "x-avibe-show-context": basePath.startsWith("/p/") ? "shared" : "private"
+ }
+ const rootPeriod = basePath.startsWith("/p/") ? "一季度" : "四季度"
+ const targets = [
+ [`/?period=${encodeURIComponent(rootPeriod)}`, "Building your Show Page"],
+ ["/second", "# A second page"],
+ ["/items/%E4%B8%AD%E6%96%87?view=%E5%91%A8&vibe-embed=1", "# Item 中文"]
+ ]
+ // Default-branch compatibility does not claim legacy nested SSR support.
+ // The opt-in mode is the combined acceptance gate with Runtime PR #70.
+ const nestedSupported = sessionId === "sesfresh" || values["legacy-router-ssr"]
+ for (const [target, expected] of nestedSupported ? targets : targets.slice(0, 1)) {
+ const response = await fetch(`${server.url}/sessions/${sessionId}/render-markdown`, {
+ headers: { ...headers, "x-vibe-show-target": target }
+ })
+ const markdown = await response.text()
+ assert.equal(response.status, 200, markdown)
+ assert.match(response.headers.get("content-type"), /^text\/markdown/)
+ assert(markdown.includes(expected), markdown)
+ if (sessionId !== "sesfresh" && target.startsWith("/?")) {
+ assert(markdown.includes("Dynamic routes: 1"), markdown)
+ assert(markdown.includes(`Root location: ${basePath}`), markdown)
+ assert(markdown.includes(`Root query: ${rootPeriod}`), markdown)
+ assert(markdown.includes("Read-only location: true"), markdown)
+ assert(markdown.includes("Static motion: true"), markdown)
+ }
+ if (target.startsWith("/items/")) {
+ assert(markdown.includes("View 周"), markdown)
+ assert(markdown.includes(`${basePath}second?from=detail&vibe-embed=1`), markdown)
+ if (sessionId !== "sesfresh") {
+ assert(markdown.includes("Legacy dynamic field: true"), markdown)
+ }
+ }
+ }
+ const html = await fetch(`${server.url}/sessions/${sessionId}/app/second`, {
+ headers: { ...headers, Accept: "text/html" }
+ })
+ assert.equal(html.status, 200, await html.text())
+ assert.match(html.headers.get("content-type"), /^text\/html/)
+ }
+ assert.deepEqual(await routerSnapshot(join(workspaceRoot, sessionId)), originalRouters.get(sessionId),
+ `${sessionId}: initialization or rendering changed the editable router`)
+ }
+ console.log(`Show router integration passed: fresh nested SSR, Unicode, queries, links, HTML, private + public; legacy LF/CRLF ${values["legacy-router-ssr"] ? "nested SSR" : "root fallback"}, route fields, read-only root location + static motion; source files unchanged.`)
+} finally {
+ await server?.close()
+ await rm(temporary, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 })
+}
diff --git a/scripts/generate_show_runtime_manifest.py b/scripts/generate_show_runtime_manifest.py
index 4a474b366..06a7bc7b5 100644
--- a/scripts/generate_show_runtime_manifest.py
+++ b/scripts/generate_show_runtime_manifest.py
@@ -41,7 +41,25 @@ def _read_runtime_ref(value: str | None, patterns: list[str]) -> str:
return next(iter(refs))
-def build_manifest(*, archive_dir: Path, tag: str, repo: str, runtime_ref: str, output: Path) -> dict:
+def _generated_router(archive_dir: Path, platforms: set[str]) -> bytes:
+ """Require the template exported by every exact Runtime archive build."""
+ routers = []
+ for platform in sorted(platforms):
+ path = archive_dir / f"show-router-{platform}.tsx"
+ if not path.is_file():
+ raise SystemExit(f"Missing Show Runtime router template: {path.name}")
+ routers.append(path.read_bytes())
+ if len(set(routers)) != 1:
+ raise SystemExit("Show Runtime router templates differ across platforms")
+ router = routers[0]
+ if b"export function SsrRouterProvider" not in router:
+ raise SystemExit("Show Runtime router template does not support SSR Markdown subroutes")
+ return router
+
+
+def build_manifest(
+ *, archive_dir: Path, tag: str, repo: str, runtime_ref: str, output: Path, router_output: Path | None = None
+) -> dict:
archives: dict[str, dict[str, object]] = {}
base_url = f"https://github.com/{repo}/releases/download/{tag}"
for archive in sorted(archive_dir.glob(f"{ARCHIVE_PREFIX}*{ARCHIVE_SUFFIX}")):
@@ -65,6 +83,7 @@ def build_manifest(*, archive_dir: Path, tag: str, repo: str, runtime_ref: str,
if missing:
raise SystemExit("Missing Show Runtime archives: " + ", ".join(missing))
+ router = _generated_router(archive_dir, expected) if router_output is not None else None
manifest = {
"schema_version": 1,
"runtime_version": runtime_ref,
@@ -76,6 +95,9 @@ def build_manifest(*, archive_dir: Path, tag: str, repo: str, runtime_ref: str,
"archives": archives,
}
output.parent.mkdir(parents=True, exist_ok=True)
+ if router_output is not None and router is not None:
+ router_output.parent.mkdir(parents=True, exist_ok=True)
+ router_output.write_bytes(router)
output.write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8")
return manifest
@@ -94,6 +116,7 @@ def main() -> int:
help="Glob pattern for files containing the Show Runtime commit used to build the archives.",
)
parser.add_argument("--output", required=True, type=Path)
+ parser.add_argument("--router-output", required=True, type=Path)
args = parser.parse_args()
runtime_ref = _read_runtime_ref(args.runtime_ref, args.runtime_ref_file)
manifest = build_manifest(
@@ -102,6 +125,7 @@ def main() -> int:
repo=args.repo,
runtime_ref=runtime_ref,
output=args.output,
+ router_output=args.router_output,
)
print(json.dumps({"ok": True, "platforms": sorted(manifest["archives"])}, indent=2))
return 0
diff --git a/scripts/sync_show_router.mjs b/scripts/sync_show_router.mjs
new file mode 100644
index 000000000..da2544ff4
--- /dev/null
+++ b/scripts/sync_show_router.mjs
@@ -0,0 +1,35 @@
+#!/usr/bin/env node
+// The Runtime generator is the only authored implementation of the Show router.
+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"
+import { tmpdir } from "node:os"
+import { dirname, join, resolve } from "node:path"
+import { fileURLToPath, pathToFileURL } from "node:url"
+import { parseArgs } from "node:util"
+
+const repository = resolve(dirname(fileURLToPath(import.meta.url)), "..")
+const { values } = parseArgs({
+ options: {
+ "runtime-module": { type: "string" },
+ output: { type: "string", default: join(repository, "vibe", "show_router.tsx") },
+ check: { type: "boolean", default: false }
+ }
+})
+if (!values["runtime-module"]) throw new Error("--runtime-module must name the built Runtime templates.js")
+const { ensureSessionTemplate } = await import(pathToFileURL(resolve(values["runtime-module"])).href)
+const workspace = await mkdtemp(join(tmpdir(), "avibe-show-router-export-"))
+try {
+ await ensureSessionTemplate(workspace)
+ const router = await readFile(join(workspace, "src", "router.tsx"), "utf8")
+ if (!router.includes("export function SsrRouterProvider")) {
+ throw new Error("The Runtime template must support SSR Markdown subroutes")
+ }
+ if (values.check) {
+ if (await readFile(values.output, "utf8") !== router) {
+ throw new Error("The packaged Show router differs from the Runtime template; run sync_show_router.mjs")
+ }
+ } else {
+ await writeFile(values.output, router, "utf8")
+ }
+} finally {
+ await rm(workspace, { recursive: true, force: true })
+}
diff --git a/tests/fixtures/show_pages/router-history-pre-ssr.tsx b/tests/fixtures/show_pages/router-history-pre-ssr.tsx
new file mode 100644
index 000000000..a5b46b49b
--- /dev/null
+++ b/tests/fixtures/show_pages/router-history-pre-ssr.tsx
@@ -0,0 +1,190 @@
+import type { ComponentType, MouseEvent, ReactNode } from "react"
+import { useSyncExternalStore } from "react"
+
+export type PageProps = {
+ // Values captured from [param] segments, e.g. { id: "42" } for /items/42.
+ params: Record<string, string>
+}
+
+type PageModule = { default: ComponentType<PageProps> }
+
+type Segment = { name: string; dynamic: boolean }
+type Route = {
+ path: string
+ segments: Segment[]
+ Component: ComponentType<PageProps>
+ dynamic: boolean
+}
+
+const PAGES_PREFIX = "./pages/"
+const PAGE_SUFFIX = ".tsx"
+
+// Eagerly import every page module at build time. This is the discovery
+// mechanism: a new file under src/pages/ automatically registers a route.
+const modules = import.meta.glob<PageModule>("./pages/**/*.tsx", { eager: true })
+
+// "./pages/items/[id].tsx" -> "/items/:id"; "./pages/index.tsx" -> "/".
+// Returns null for framework files (any segment starting with "_"), which lets
+// an agent colocate non-page helpers under src/pages/ without creating a route.
+function filePathToRoute(file: string): string | null {
+ const relative = file.slice(PAGES_PREFIX.length, file.length - PAGE_SUFFIX.length)
+ const parts = relative.split("/")
+ if (parts[parts.length - 1] === "index") parts.pop()
+ if (parts.some((part) => part.startsWith("_"))) return null
+ const path = parts
+ .map((part) => (part.startsWith("[") && part.endsWith("]") ? ":" + part.slice(1, -1) : part))
+ .join("/")
+ return path ? "/" + path : "/"
+}
+
+function toSegments(path: string): Segment[] {
+ if (path === "/") return []
+ return path
+ .slice(1)
+ .split("/")
+ .map((part) => (part.startsWith(":") ? { name: part.slice(1), dynamic: true } : { name: part, dynamic: false }))
+}
+
+// Per-segment specificity mask: "0" for a static segment, "1" for a dynamic one.
+// Routes are sorted ascending by this mask (compared left to right), so among
+// routes of the same length a static segment always beats a [param] at the same
+// position — e.g. /items/new wins over /items/:id, and /users/:id/edit wins over
+// /users/:id/:action.
+function routeSpecificity(segments: Segment[]): string {
+ return segments.map((segment) => (segment.dynamic ? "1" : "0")).join("")
+}
+
+// A page's default export is renderable if it is a function component or a React
+// "exotic" component (memo/forwardRef/lazy/…) — an object carrying $$typeof.
+// Rejecting by `typeof === "function"` alone would drop memo()/forwardRef() pages.
+function isRenderablePage(value: unknown): value is ComponentType<PageProps> {
+ return (
+ typeof value === "function" ||
+ (typeof value === "object" && value !== null && "$$typeof" in value)
+ )
+}
+
+export const routes: Route[] = Object.entries(modules)
+ .map(([file, mod]): Route | null => {
+ const path = filePathToRoute(file)
+ if (!path || !isRenderablePage(mod.default)) return null
+ const segments = toSegments(path)
+ return { path, segments, Component: mod.default, dynamic: segments.some((s) => s.dynamic) }
+ })
+ .filter((route): route is Route => route !== null)
+ .sort((a, b) => {
+ const specA = routeSpecificity(a.segments)
+ const specB = routeSpecificity(b.segments)
+ if (specA !== specB) return specA < specB ? -1 : 1
+ return a.path.localeCompare(b.path)
+ })
+
+// 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
+// that page instead of throwing during render and blanking the whole app.
+function safeDecode(value: string): string {
+ try {
+ return decodeURIComponent(value)
+ } catch {
+ return value
+ }
+}
+
+function matchRoute(path: string): { route: Route | null; params: Record<string, string> } {
+ const parts = path === "/" ? [] : path.slice(1).split("/")
+ for (const route of routes) {
+ if (route.segments.length !== parts.length) continue
+ const params: Record<string, string> = {}
+ let matched = true
+ 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 !== safeDecode(parts[i])) {
+ matched = false
+ break
+ }
+ }
+ if (matched) return { route, params }
+ }
+ return { route: null, params: {} }
+}
+
+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("popstate", onChange)
+ return () => window.removeEventListener("popstate", onChange)
+}
+
+export function useRoutePath(): string {
+ 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 {
+ 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 }) {
+ 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() {
+ const path = useRoutePath()
+ const { route, params } = matchRoute(path)
+ if (!route) {
+ return (
+ <div className="rounded-lg border border-border bg-card p-6 text-card-foreground">
+ <h1 className="text-lg font-semibold">Page not found</h1>
+ <p className="mt-2 text-sm text-muted-foreground">
+ No route matches <code className="rounded bg-muted px-1.5 py-0.5">{path}</code>.
+ </p>
+ <p className="mt-4 text-sm">
+ <Link className="font-medium underline underline-offset-4" to="/">Back to Home</Link>
+ </p>
+ </div>
+ )
+ }
+ const Page = route.Component
+ return <Page params={params} />
+}
diff --git a/tests/test_ci_pipeline.py b/tests/test_ci_pipeline.py
index 20ecd2987..310b00ba8 100644
--- a/tests/test_ci_pipeline.py
+++ b/tests/test_ci_pipeline.py
@@ -75,6 +75,7 @@ def test_ci_uv_installation_is_exact_and_cache_ownership_is_preserved():
}
assert set(owners) == {
"unit-test-shards", "migration-release-guard", "install-upgrade-shards", "memory-insight-contract",
+ "show-router-integration",
}
cache_keys = {}
for name, job in owners.items():
@@ -89,7 +90,9 @@ def test_ci_uv_installation_is_exact_and_cache_ownership_is_preserved():
assert any(step.get("uses", "").startswith("actions/setup-python@") for step in steps[:steps.index(install)])
assert not any(step.get("uses", "").startswith("astral-sh/setup-uv@") for step in steps)
cache, = [step for step in steps if step.get("uses", "").startswith("actions/cache")]
- action = "actions/cache/restore" if name in {"unit-test-shards", "migration-release-guard"} else "actions/cache"
+ action = "actions/cache/restore" if name in {
+ "unit-test-shards", "migration-release-guard", "show-router-integration",
+ } else "actions/cache"
assert cache["uses"] == f"{action}@caa296126883cff596d87d8935842f9db880ef25"
assert cache["with"]["path"] == "~/.cache/uv"
key = cache["with"]["key"]
diff --git a/tests/test_memory_distribution.py b/tests/test_memory_distribution.py
index 63318af13..5ec65368e 100644
--- a/tests/test_memory_distribution.py
+++ b/tests/test_memory_distribution.py
@@ -96,6 +96,15 @@ def _wheel_metadata(wheel: Path) -> tuple[set[str], Any]:
return names, metadata
+def test_core_distributions_ship_the_generated_show_router() -> None:
+ core_wheel = _wheel_path("AVIBE_CORE_WHEEL")
+ expected = (ROOT / "vibe" / "show_router.tsx").read_bytes()
+ with zipfile.ZipFile(core_wheel) as archive:
+ assert archive.read("vibe/show_router.tsx") == expected
+ with tarfile.open(_sdist_path(core_wheel, "avibe_os"), "r:gz") as archive:
+ assert _sdist_member(archive, "show_router.tsx") == expected
+
+
def _sdist_metadata(wheel: Path, distribution: str) -> Any:
sdist = _sdist_path(wheel, distribution)
with tarfile.open(sdist, "r:gz") as archive:
diff --git a/tests/test_show_pages.py b/tests/test_show_pages.py
index 401e20e04..6dc87b9a1 100644
--- a/tests/test_show_pages.py
+++ b/tests/test_show_pages.py
@@ -2515,7 +2515,7 @@ def test_fresh_workspace_scaffolds_placeholder_and_minimal_router(monkeypatch, t
assert "globalThis.__AVIBE_SHOW__?.basePath" in router
assert "popstate" in router
assert "pushState" in router
- assert 'searchParams.get("vibe-embed")' in router
+ assert '.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.
diff --git a/tests/test_show_router.py b/tests/test_show_router.py
new file mode 100644
index 000000000..93803d76f
--- /dev/null
+++ b/tests/test_show_router.py
@@ -0,0 +1,138 @@
+from __future__ import annotations
+
+import errno
+from pathlib import Path
+
+import pytest
+
+from core.show_pages import ensure_show_page_dir, show_page_dir
+from core.show_router import default_show_router
+
+
+LEGACY_ROUTER = Path(__file__).parent / "fixtures" / "show_pages" / "router-history-pre-ssr.tsx"
+
+
+def test_fresh_router_comes_from_the_packaged_runtime_template():
+ page = ensure_show_page_dir("sesfresh")
+ assert (page / "src" / "router.tsx").read_text() == default_show_router()
+ assert "export function SsrRouterProvider" in default_show_router()
+
+
[email protected]("newline", [b"\n", b"\r\n"], ids=["lf", "windows-crlf"])
+def test_ensure_never_rewrites_the_old_router(newline):
+ page = ensure_show_page_dir("sesupgrade")
+ router = page / "src" / "router.tsx"
+ original = LEGACY_ROUTER.read_bytes().replace(b"\n", newline)
+ router.write_bytes(original)
+ router.chmod(0o640)
+ before = router.stat()
+ others = {
+ path.relative_to(page): path.read_bytes()
+ for path in page.rglob("*")
+ if path.is_file() and path != router
+ }
+
+ assert ensure_show_page_dir("sesupgrade") == page
+ assert router.stat() == before
+ assert router.read_bytes() == original
+ ensure_show_page_dir("sesupgrade")
+ assert router.stat().st_mtime_ns == before.st_mtime_ns
+ assert router.stat().st_ino == before.st_ino
+ assert all((page / path).read_bytes() == content for path, content in others.items())
+
+
+ "contents",
+ [
+ b"// Authored by the user\n" + LEGACY_ROUTER.read_bytes(),
+ b'export function RouterView() { return <h1>Custom</h1> }\n',
+ b'window.addEventListener("hashchange", () => {})\n',
+ b"// Non-UTF8 custom source: \xff",
+ ],
+)
+def test_unknown_routers_are_never_rewritten(contents):
+ page = ensure_show_page_dir("sescustom")
+ router = page / "src" / "router.tsx"
+ router.write_bytes(contents)
+ assert ensure_show_page_dir("sescustom") == page
+ assert router.read_bytes() == contents
+
+
+def test_routerless_workspace_is_not_rewritten():
+ page = show_page_dir("sesrouterless")
+ (page / "src").mkdir(parents=True)
+ (page / "src" / "App.tsx").write_text("export default function App() { return null }\n")
+ ensure_show_page_dir("sesrouterless")
+ assert not (page / "src" / "router.tsx").exists()
+
+
[email protected]("linked_component", ["router", "src", "workspace"])
+def test_initialization_does_not_rewrite_symlink_routers(tmp_path, linked_component):
+ page = show_page_dir("seslinked")
+ page.parent.mkdir(parents=True, exist_ok=True)
+ outside = tmp_path / "outside"
+ (outside / "src").mkdir(parents=True)
+ target = outside / "src" / "router.tsx"
+ target.write_bytes(LEGACY_ROUTER.read_bytes())
+ if linked_component == "workspace":
+ page.symlink_to(outside, target_is_directory=True)
+ elif linked_component == "src":
+ page.mkdir()
+ (page / "src").symlink_to(outside / "src", target_is_directory=True)
+ else:
+ (page / "src").mkdir(parents=True)
+ (page / "src" / "router.tsx").symlink_to(target)
+ ensure_show_page_dir("seslinked")
+ assert target.read_bytes() == LEGACY_ROUTER.read_bytes()
+
+
+def test_concurrent_edit_is_preserved(monkeypatch):
+ page = ensure_show_page_dir("sesediting")
+ router = page / "src" / "router.tsx"
+ router.write_bytes(LEGACY_ROUTER.read_bytes())
+ authored = b"// Editor saved while migration was preparing\n" + LEGACY_ROUTER.read_bytes()
+
+ from core import show_pages
+ write_defaults = show_pages._write_default_runtime_files
+
+ def defaults_during_edit(*args):
+ write_defaults(*args)
+ router.write_bytes(authored)
+
+ monkeypatch.setattr(show_pages, "_write_default_runtime_files", defaults_during_edit)
+ ensure_show_page_dir("sesediting")
+ assert router.read_bytes() == authored
+
+
+def test_fresh_scaffold_does_not_replace_a_concurrently_created_router(monkeypatch):
+ page = show_page_dir("sescreation")
+ router = page / "src" / "router.tsx"
+ authored = b"// Created by the editor during initialization\n"
+ original_open = Path.open
+
+ def create_before_open(path, mode="r", *args, **kwargs):
+ if path == router and mode == "x":
+ with original_open(path, "wb") as handle:
+ handle.write(authored)
+ return original_open(path, mode, *args, **kwargs)
+
+ monkeypatch.setattr(Path, "open", create_before_open)
+ ensure_show_page_dir("sescreation")
+ assert router.read_bytes() == authored
+
+
[email protected]("error", [PermissionError("fixture permission"), OSError(errno.EROFS, "fixture read-only mount")])
+def test_existing_router_is_not_opened_for_migration(monkeypatch, error):
+ page = ensure_show_page_dir("sesreadonly")
+ router = page / "src" / "router.tsx"
+ router.write_bytes(LEGACY_ROUTER.read_bytes())
+
+ original_open = Path.open
+
+ def readonly_router(path, *args, **kwargs):
+ if path == router:
+ raise error
+ return original_open(path, *args, **kwargs)
+
+ monkeypatch.setattr(Path, "open", readonly_router)
+ assert ensure_show_page_dir("sesreadonly") == page
diff --git a/tests/test_show_runtime_manifest.py b/tests/test_show_runtime_manifest.py
index ba4bb0497..eacaa4ff0 100644
--- a/tests/test_show_runtime_manifest.py
+++ b/tests/test_show_runtime_manifest.py
@@ -56,3 +56,38 @@ def test_generate_show_runtime_manifest_fails_when_platform_archive_missing(tmp_
runtime_ref="runtime-sha",
output=tmp_path / "manifest.json",
)
+
+
[email protected]("failure", [None, "missing", "different", "no_ssr"])
+def test_release_uses_one_router_from_the_actual_runtime_builds(tmp_path: Path, failure) -> None:
+ router = b"export function SsrRouterProvider() { return null }\n"
+ for platform in PLATFORMS:
+ (tmp_path / f"vibe-show-runtime-node-{platform}.tgz").write_bytes(b"runtime")
+ (tmp_path / f"show-router-{platform}.tsx").write_bytes(router)
+ candidate = tmp_path / "show-router-win32-arm64.tsx"
+ if failure == "missing":
+ candidate.unlink()
+ elif failure == "different":
+ candidate.write_bytes(router + b"// drift\n")
+ elif failure == "no_ssr":
+ for platform in PLATFORMS:
+ (tmp_path / f"show-router-{platform}.tsx").write_bytes(b"export function RouterView() {}\n")
+ output = tmp_path / "package/show_runtime_manifest.json"
+ router_output = tmp_path / "package/show_router.tsx"
+ kwargs = dict(
+ archive_dir=tmp_path,
+ tag="v3.0.15",
+ repo="avibe-bot/avibe",
+ runtime_ref="runtime-sha",
+ output=output,
+ router_output=router_output,
+ )
+ if failure:
+ with pytest.raises(SystemExit, match="router template"):
+ build_manifest(**kwargs)
+ assert not output.exists()
+ assert not router_output.exists()
+ else:
+ build_manifest(**kwargs)
+ assert router_output.read_bytes() == router
+ assert output.exists()
diff --git a/tests/test_terminal_backend.py b/tests/test_terminal_backend.py
index 63e1b3bc7..7c1b28156 100644
--- a/tests/test_terminal_backend.py
+++ b/tests/test_terminal_backend.py
@@ -240,6 +240,11 @@ async def _open_spawns_with_start_new_session_not_preexec(monkeypatch, tmp_path)
monkeypatch.setattr(terminal_service.asyncio, "create_subprocess_exec", fake_spawn)
monkeypatch.setattr(terminal_service.os, "openpty", fake_openpty)
+ # The process is fake; its PID may belong to the runner or a user's real
+ # process. Keep shutdown's group lookup and signal delivery fake as well.
+ signals: list[tuple[int, signal.Signals]] = []
+ monkeypatch.setattr(terminal_service.os, "getpgid", lambda pid: pid)
+ monkeypatch.setattr(terminal_service.os, "killpg", lambda pid, signum: signals.append((pid, signum)))
service = TerminalService(idle_timeout_seconds=60, max_sessions=1)
try:
@@ -250,6 +255,7 @@ async def _open_spawns_with_start_new_session_not_preexec(monkeypatch, tmp_path)
await service.shutdown()
for fd in opened_fds:
terminal_service._close_fd(fd)
+ assert signals == [(4321, signal.SIGTERM)]
def test_terminal_reconnect_replaces_session(monkeypatch, tmp_path):
diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.py
index 38bb4373d..54cf0e275 100644
--- a/tests/test_ui_show_pages.py
+++ b/tests/test_ui_show_pages.py
@@ -1950,6 +1950,45 @@ def _markdown_runtime_manager(
)
[email protected]("surface", ["private", "public"])
[email protected]("customized", [False, True])
+def test_markdown_first_read_never_rewrites_the_router_before_runtime_load(
+ monkeypatch, tmp_path, surface, customized
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ share_id = _create_show_page("ses123", surface)
+ router = ensure_show_page_dir("ses123") / "src" / "router.tsx"
+ old = (Path(__file__).parent / "fixtures/show_pages/router-history-pre-ssr.tsx").read_bytes()
+ authored = b"// User customization\n" + old if customized else old
+ router.write_bytes(authored)
+ before = router.stat()
+ manager = _markdown_runtime_manager()
+ original_request = manager.request
+
+ async def assert_router_ready(*args, **kwargs):
+ assert router.stat().st_ino == before.st_ino
+ assert router.stat().st_mtime_ns == before.st_mtime_ns
+ assert router.read_bytes() == authored
+ return await original_request(*args, **kwargs)
+
+ manager.request = assert_router_ready
+ set_show_runtime_manager_for_tests(manager)
+ try:
+ response = app.test_client().get(
+ f"/p/{share_id}/second" if surface == "public" else "/show/ses123/second",
+ base_url="https://alex.avibe.bot" if surface == "public" else "http://127.0.0.1:5123",
+ environ_base=_remote_peer() if surface == "public" else {},
+ headers={"Accept": "text/markdown"},
+ )
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert response.status_code == 200
+ assert len(manager.calls) == 1
+ assert router.read_bytes() == authored
+
+
def _assert_markdown_response_headers(response, *, success: bool) -> None:
vary = {item.strip().lower() for item in response.headers["vary"].split(",")}
assert "accept" in vary
@@ -2910,6 +2949,7 @@ def test_offline_show_page_markdown_maps_to_page_offline(monkeypatch, tmp_path,
(504, "render_timeout"),
(502, "output_too_large"),
(502, "render_failed"),
+ (502, "router_not_ssr_capable"),
],
)
@pytest.mark.parametrize("surface", ["private", "public"])
diff --git a/vibe/show_router.tsx b/vibe/show_router.tsx
new file mode 100644
index 000000000..07116bf07
--- /dev/null
+++ b/vibe/show_router.tsx
@@ -0,0 +1,210 @@
+import type { ComponentType, MouseEvent, ReactNode } from "react"
+import { createContext, useContext, useSyncExternalStore } from "react"
+
+export type PageProps = {
+ params: Record<string, string>
+ query: URLSearchParams
+}
+
+export type SsrRouteLocation = {
+ pathname: string
+ search: string
+ origin: string
+ basePath: string
+}
+
+type PageModule = { default: ComponentType<PageProps> }
+type Segment = { name: string; dynamic: boolean }
+type Route = {
+ path: string
+ segments: Segment[]
+ Component: ComponentType<PageProps>
+}
+
+const PAGES_PREFIX = "./pages/"
+const PAGE_SUFFIX = ".tsx"
+const modules = import.meta.glob<PageModule>("./pages/**/*.tsx", { eager: true })
+const SsrRouterContext = createContext<SsrRouteLocation | null>(null)
+
+export function SsrRouterProvider({
+ location,
+ children
+}: {
+ location: SsrRouteLocation
+ children: ReactNode
+}) {
+ return <SsrRouterContext.Provider value={location}>{children}</SsrRouterContext.Provider>
+}
+
+function filePathToRoute(file: string): string | null {
+ const relative = file.slice(PAGES_PREFIX.length, file.length - PAGE_SUFFIX.length)
+ const parts = relative.split("/")
+ if (parts[parts.length - 1] === "index") parts.pop()
+ if (parts.some((part) => part.startsWith("_"))) return null
+ const path = parts
+ .map((part) => (part.startsWith("[") && part.endsWith("]") ? ":" + part.slice(1, -1) : part))
+ .join("/")
+ return path ? "/" + path : "/"
+}
+
+function toSegments(path: string): Segment[] {
+ if (path === "/") return []
+ return path.slice(1).split("/").map((part) =>
+ part.startsWith(":")
+ ? { name: part.slice(1), dynamic: true }
+ : { name: part, dynamic: false }
+ )
+}
+
+function routeSpecificity(segments: Segment[]): string {
+ return segments.map((segment) => (segment.dynamic ? "1" : "0")).join("")
+}
+
+function isRenderablePage(value: unknown): value is ComponentType<PageProps> {
+ return typeof value === "function" || (typeof value === "object" && value !== null && "$$typeof" in value)
+}
+
+export const routes: Route[] = Object.entries(modules)
+ .map(([file, mod]): Route | null => {
+ const path = filePathToRoute(file)
+ if (!path || !isRenderablePage(mod.default)) return null
+ return { path, segments: toSegments(path), Component: mod.default }
+ })
+ .filter((route): route is Route => route !== null)
+ .sort((a, b) => {
+ const specA = routeSpecificity(a.segments)
+ const specB = routeSpecificity(b.segments)
+ if (specA !== specB) return specA < specB ? -1 : 1
+ return a.path.localeCompare(b.path)
+ })
+
+function safeDecode(value: string): string {
+ try {
+ return decodeURIComponent(value)
+ } catch {
+ return value
+ }
+}
+
+function matchRoute(path: string): { route: Route | null; params: Record<string, string> } {
+ const parts = path === "/" ? [] : path.slice(1).split("/")
+ for (const route of routes) {
+ if (route.segments.length !== parts.length) continue
+ const params: Record<string, string> = {}
+ let matched = true
+ for (let index = 0; index < parts.length; index++) {
+ const segment = route.segments[index]
+ if (segment.dynamic) params[segment.name] = safeDecode(parts[index])
+ else if (segment.name !== safeDecode(parts[index])) {
+ matched = false
+ break
+ }
+ }
+ if (matched) return { route, params }
+ }
+ return { route: null, params: {} }
+}
+
+function basePath(location?: SsrRouteLocation | null): string {
+ if (location) {
+ const pathname = new URL(location.basePath, location.origin).pathname
+ const parts = pathname.split("/").filter(Boolean)
+ return parts.length ? "/" + parts.join("/") + "/" : "/"
+ }
+ 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(location?: SsrRouteLocation | null): string {
+ if (location) return normalizeRoutePath(location.pathname)
+ const base = basePath(location)
+ 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("popstate", onChange)
+ return () => window.removeEventListener("popstate", onChange)
+}
+
+function noSubscribe(): () => void {
+ return () => undefined
+}
+
+export function useRoutePath(): string {
+ const location = useContext(SsrRouterContext)
+ return useSyncExternalStore(
+ location ? noSubscribe : subscribe,
+ location ? () => readRoutePath(location) : readRoutePath,
+ () => readRoutePath(location)
+ )
+}
+
+export function useRouteQuery(): URLSearchParams {
+ const location = useContext(SsrRouterContext)
+ const search = useSyncExternalStore(
+ location ? noSubscribe : subscribe,
+ location ? () => location.search : () => window.location.search,
+ () => location?.search ?? ""
+ )
+ return new URLSearchParams(search)
+}
+
+function routeUrl(to: string, location?: SsrRouteLocation | null): URL {
+ const normalizedTo = to.startsWith("/") ? to : "/" + to
+ const origin = location?.origin ?? window.location.origin
+ const route = new URL(normalizedTo, origin)
+ const currentSearch = location?.search ?? new URL(window.location.href).search
+ const target = new URL(basePath(location), origin)
+ const embed = new URLSearchParams(currentSearch).get("vibe-embed")
+ target.pathname = basePath(location) + 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 {
+ 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 }) {
+ const location = useContext(SsrRouterContext)
+ 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, location).toString()} className={className} onClick={onClick}>{children}</a>
+}
+
+export function RouterView() {
+ const path = useRoutePath()
+ const query = useRouteQuery()
+ const { route, params } = matchRoute(path)
+ if (!route) {
+ return (
+ <div className="rounded-lg border border-border bg-card p-6 text-card-foreground">
+ <h1 className="text-lg font-semibold">Page not found</h1>
+ <p className="mt-2 text-sm text-muted-foreground">No route matches {path}.</p>
+ <p className="mt-4 text-sm"><Link className="font-medium underline" to="/">Back to Home</Link></p>
+ </div>
+ )
+ }
+ const Page = route.Component
+ return <Page params={params} query={query} />
+}
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 8d15bb895..f24bc562d 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -14733,7 +14733,7 @@ def _show_page_markdown_runtime_error_response(proxied: Any):
expected_codes = {
400: {"invalid_target"},
404: {"session_unknown"},
- 502: {"render_failed", "output_too_large"},
+ 502: {"render_failed", "output_too_large", "router_not_ssr_capable"},
503: {"renderer_unavailable"},
504: {"render_timeout"},
}