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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(show): default multi-page scaffold with nested routing (#877)
Call Whitec9fd9db8c983
diff --git a/core/show_pages.py b/core/show_pages.pyindex 01761a683..10efbcc9d 100644--- a/core/show_pages.py+++ b/core/show_pages.py@@ -523,13 +523,32 @@ def show_page_payload(page: ShowPage, *, config: V2Config | None = None) -> dictdef _write_default_runtime_files(page_dir: Path, session_id: str) -> None:- files = {+ # 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/App.tsx": _default_app_tsx(),"src/styles.css": _default_styles_css(),"api/health.ts": _default_api_health_ts(),}+ # Multi-page demo. Only seed it into a FRESH workspace — one that does not yet+ # have its own ``src/App.tsx``. This keeps existing single-page workspaces+ # byte-for-byte unchanged (we never drop router/pages files next to a page the+ # agent already authored) while a brand-new Show Page starts as a working+ # multi-page app the agent can inspect, run, extend, or replace. 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():+ files.update(+ {+ "src/App.tsx": _default_app_tsx(),+ "src/router.tsx": _default_router_tsx(),+ "src/pages/index.tsx": _default_page_home_tsx(),+ "src/pages/items/index.tsx": _default_page_items_index_tsx(),+ "src/pages/items/[id].tsx": _default_page_item_detail_tsx(),+ }+ )for relative_path, contents in files.items():target = page_dir / relative_pathif target.exists():@@ -837,266 +856,459 @@ createRoot(document.getElementById("root")!).render(def _default_app_tsx() -> str:- # Placeholder shown while the agent has not authored the page yet. On the- # private /show/ surface the Vite runtime hot-swaps this with the real page- # as soon as the agent rewrites src/App.tsx, so the copy says it appears- # automatically; the public /p/ surface serves a static build with HMR- # disabled, so there the copy asks the viewer to refresh instead. We also- # offer the same prompt we auto-send, in case the user wants to nudge.- return """import { useEffect, useState } from "react"-import { Button } from "@/components/ui/button"+ # The default multi-page demo (agent-editable). It composes the shared layout+ # (nav derived from the discovered pages) with the routed page. This file and+ # everything under src/pages/ + src/router.tsx are a starting point: the agent+ # can restyle the nav, add pages, or replace the whole thing. The runtime-owned+ # app shell (index.html + src/main.tsx) is never edited to add a page.+ return """import { useEffect } from "react"import { ThemeProvider } from "@avibe/show-ui/theme"+import { cn } from "@/lib/utils"+import { activeLocale, Link, RouterView, navItems, useRoutePath } from "./router"-const NUDGE_PROMPT = "Please visualize this session as a Show Page."--const COPY = {- en: {- lang: "en",- badge: "Show Page",- title: "Building your Show Page",- bodyLive: "Your agent is turning this session into a visual page. It will appear here automatically once it is ready.",- bodyStatic: "Your agent is turning this session into a visual page. Refresh this page once it is ready to see it.",- nudge: "Taking a while? Send this to your agent:",- copy: "Copy",- copied: "Copied",- },- zh: {- lang: "zh",- badge: "Show Page",- title: "正在生成 Show Page",- bodyLive: "Agent 正在把这次会话整理成一个可视化页面,完成后会自动显示在这里,不用刷新。",- bodyStatic: "Agent 正在把这次会话整理成一个可视化页面,完成后刷新一下页面就能看到。",- nudge: "等太久了?把这句话发给 Agent 催一下:",- copy: "复制",- copied: "已复制",- },-}--function pickCopy() {- const lang = (typeof navigator !== "undefined" && navigator.language) || "en"- return lang.toLowerCase().startsWith("zh") ? COPY.zh : COPY.en-}--// The private /show/ surface keeps Vite HMR, so the real page hot-swaps in on-// its own. The public /p/ surface serves a static build (HMR disabled), so a-// viewer there has to refresh to pick up the agent's page.-function isLiveSurface() {- return typeof window !== "undefined" && window.location.pathname.includes("/show/")+function Nav() {+ const path = useRoutePath()+ return (+ <nav className="flex flex-wrap items-center gap-1">+ {navItems.map((item) => {+ const active = path === item.to || (item.to !== "/" && path.startsWith(item.to + "/"))+ return (+ <Link+ key={item.to}+ to={item.to}+ className={cn(+ "rounded-md px-3 py-1.5 text-sm font-medium transition-colors",+ active+ ? "bg-primary text-primary-foreground"+ : "text-muted-foreground hover:bg-muted hover:text-foreground",+ )}+ >+ {item.label}+ </Link>+ )+ })}+ </nav>+ )}export default function App() {- const t = pickCopy()- const [copied, setCopied] = useState(false)- const live = isLiveSurface()-useEffect(() => {- document.documentElement.lang = t.lang- }, [t.lang])-- async function copyPrompt() {- let ok = false- try {- await navigator.clipboard.writeText(NUDGE_PROMPT)- ok = true- } catch {- const field = document.getElementById("show-nudge-prompt")- if (field instanceof HTMLInputElement) {- field.select()- ok = document.execCommand("copy")- }- }- if (!ok) return- setCopied(true)- window.setTimeout(() => setCopied(false), 2000)- }-+ document.documentElement.lang = activeLocale()+ }, [])return (<ThemeProvider preset="zinc">- <main className="show-shell">- <section className="show-card">- <div className="show-pulse" aria-hidden="true">- <span className="show-pulse-ring" />- <span className="show-pulse-ring delay" />- <span className="show-pulse-core" />- </div>- <span className="show-badge">{t.badge}</span>- <h1 className="show-title">{t.title}</h1>- <p className="show-body">{live ? t.bodyLive : t.bodyStatic}</p>- <div className="show-nudge">- <label className="show-nudge-label" htmlFor="show-nudge-prompt">- {t.nudge}- </label>- <div className="show-nudge-row">- <input- id="show-nudge-prompt"- className="show-nudge-input"- value={NUDGE_PROMPT}- readOnly- />- <Button className="show-nudge-copy" onClick={() => void copyPrompt()}>- {copied ? t.copied : t.copy}- </Button>- </div>+ <div className="min-h-screen bg-background text-foreground">+ <header className="sticky top-0 z-10 border-b border-border bg-background/85 backdrop-blur">+ <div className="mx-auto flex max-w-3xl flex-wrap items-center justify-between gap-3 px-4 py-3">+ <Link to="/" className="text-sm font-semibold tracking-tight">+ Show Page+ </Link>+ <Nav /></div>- </section>- </main>+ </header>+ <main className="mx-auto max-w-3xl px-4 py-8">+ <RouterView />+ </main>+ </div></ThemeProvider>)}"""-def _default_styles_css() -> str:- return """@import "tailwindcss";-@import "@avibe/show-ui/theme.css";+def _default_router_tsx() -> str:+ # A tiny, dependency-free hash 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.+ #+ # 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"+import { useSyncExternalStore } from "react"++// Locale-aware demo copy. The generated demo keeps a zh/en first-run experience+// (the previous scaffold did too) without pulling in an i18n framework. Language+// is read once from the browser. Replace or extend this however you localize.+export function activeLocale(): "en" | "zh" {+ const lang = (typeof navigator !== "undefined" && navigator.language) || "en"+ return lang.toLowerCase().startsWith("zh") ? "zh" : "en"+}-:root {- color-scheme: light;+export function t(en: string, zh: string): string {+ return activeLocale() === "zh" ? zh : en}-body {- margin: 0;- font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;- color: hsl(var(--avs-foreground));- background:- radial-gradient(130% 130% at 50% -20%, hsl(var(--avs-ring) / 0.10), transparent 55%),- hsl(var(--avs-muted));+export type PageMeta = {+ // Label shown in the nav. Falls back to a title-cased path when omitted.+ title?: string+ // Sort order within the nav (lower first).+ order?: number+ // Set false to keep a static page out of the nav (it stays directly linkable).+ nav?: boolean}-.show-shell {- min-height: 100vh;- display: grid;- place-items: center;- padding: 24px;- box-sizing: border-box;+export type PageProps = {+ // Values captured from [param] segments, e.g. { id: "42" } for /items/42.+ params: Record<string, string>}-.show-card {- width: min(440px, 100%);- box-sizing: border-box;- display: flex;- flex-direction: column;- align-items: center;- text-align: center;- gap: 14px;- padding: clamp(28px, 6vw, 44px);- border: 1px solid hsl(var(--avs-border));- border-radius: calc(var(--avs-radius, 0.5rem) + 10px);- background: hsl(var(--avs-background));- box-shadow: 0 24px 70px -32px hsl(var(--avs-foreground) / 0.30);+type PageModule = {+ default: ComponentType<PageProps>+ meta?: PageMeta}-.show-pulse {- position: relative;- width: 52px;- height: 52px;- display: grid;- place-items: center;+type Segment = { name: string; dynamic: boolean }+type Route = {+ path: string+ segments: Segment[]+ Component: ComponentType<PageProps>+ meta: PageMeta+ dynamic: boolean}-.show-pulse-core {- width: 13px;- height: 13px;- border-radius: 999px;- background: hsl(var(--avs-ring));- box-shadow: 0 0 0 4px hsl(var(--avs-ring) / 0.14);+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 : "/"}-.show-pulse-ring {- position: absolute;- inset: 0;- border-radius: 999px;- border: 2px solid hsl(var(--avs-ring));- opacity: 0;- animation: show-ping 1.8s cubic-bezier(0, 0, 0.2, 1) infinite;+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 }))}-.show-pulse-ring.delay {- animation-delay: 0.9s;+function titleCase(value: string): string {+ return value.replace(/[-_]/g, " ").replace(/\\b\\w/g, (c) => c.toUpperCase())}-.show-badge {- font-size: 12px;- font-weight: 600;- letter-spacing: 0.14em;- text-transform: uppercase;- color: hsl(var(--avs-muted-foreground));+// 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("")}-.show-title {- margin: 0;- font-size: clamp(20px, 4.5vw, 24px);- font-weight: 600;- letter-spacing: -0.01em;+// 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)+ )}-.show-body {- margin: 0;- max-width: 34ch;- line-height: 1.6;- color: hsl(var(--avs-muted-foreground));+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, meta: mod.meta ?? {}, 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)+ })++export const navItems: { to: string; label: string }[] = routes+ .filter((route) => !route.dynamic && route.meta.nav !== false)+ .sort((a, b) => (a.meta.order ?? 0) - (b.meta.order ?? 0) || a.path.localeCompare(b.path))+ .map((route) => ({+ to: route.path,+ label: route.meta.title ?? (route.path === "/" ? "Home" : titleCase(route.path.slice(1).split("/").pop() || "")),+ }))++// 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+ }}-.show-nudge {- width: 100%;- margin-top: 6px;- padding-top: 18px;- border-top: 1px solid hsl(var(--avs-border));- display: flex;- flex-direction: column;- gap: 8px;- text-align: left;+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 !== parts[i]) {+ matched = false+ break+ }+ }+ if (matched) return { route, params }+ }+ return { route: null, params: {} }}-.show-nudge-label {- font-size: 13px;- color: hsl(var(--avs-muted-foreground));+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}-.show-nudge-row {- display: flex;- gap: 8px;- align-items: stretch;+function subscribe(onChange: () => void): () => void {+ window.addEventListener("hashchange", onChange)+ return () => window.removeEventListener("hashchange", onChange)}-.show-nudge-input {- flex: 1 1 auto;- min-width: 0;- height: 38px;- padding: 0 12px;- border: 1px solid hsl(var(--avs-border));- border-radius: 8px;- background: hsl(var(--avs-muted));- color: hsl(var(--avs-foreground));- font-size: 13px;+export function useRoutePath(): string {+ return useSyncExternalStore(subscribe, readHashPath, () => "/")}-.show-nudge-input:focus-visible {- outline: 2px solid hsl(var(--avs-ring));- outline-offset: 1px;+export function navigate(to: string): void {+ window.location.hash = to.startsWith("/") ? to : "/" + to}-.show-nudge-copy {- flex: 0 0 auto;- white-space: nowrap;+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>+ )}-@keyframes show-ping {- 0% {- transform: scale(0.4);- opacity: 0.55;- }- 100% {- transform: scale(1.05);- opacity: 0;+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">{t("Page not found", "页面不存在")}</h1>+ <p className="mt-2 text-sm text-muted-foreground">+ {t("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="#/">+ {t("Back to Home", "返回首页")}+ </a>+ </p>+ </div>+ )}+ const Page = route.Component+ return <Page params={params} />}+"""-@media (prefers-reduced-motion: reduce) {- .show-pulse-ring {- animation: none;- opacity: 0;- }++def _default_page_home_tsx() -> str:+ # Demo landing page. Generic on purpose: it teaches the "add a file = add a+ # page" pattern without implying a page must map to a topic, feature, or+ # history. The agent is free to replace or remove it. Copy is locale-aware.+ return """import { Badge } from "@/components/ui/badge"+import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"+import { Link, t } from "../router"++export const meta = { title: t("Home", "首页"), order: 0 }++const codeClass = "rounded bg-muted px-1.5 py-0.5 font-mono text-xs"++export default function Home() {+ return (+ <div className="space-y-6">+ <div className="space-y-2">+ <Badge>{t("Starter", "起始模板")}</Badge>+ <h1 className="text-2xl font-semibold tracking-tight">{t("A multi-page Show Page", "多页 Show Page")}</h1>+ <p className="text-muted-foreground">+ {t(+ "This workspace starts as a small multi-page app so routing is ready to use. It is only a starting point — restyle it, extend it, or replace it with whatever structure fits your app: flat pages, sections, or nested routes.",+ "这个工作区默认就是一个小型多页应用,路由开箱即用。它只是一个起点——随意改样式、扩展,或换成任何适合你的结构:扁平页面、分区,或嵌套路由。",+ )}+ </p>+ </div>++ <Card>+ <CardHeader>+ <CardTitle>{t("Add a page", "添加页面")}</CardTitle>+ <CardDescription>{t("Routing is file-based — no config and no app-shell edits.", "文件即路由——无需配置,也不用改应用外壳。")}</CardDescription>+ </CardHeader>+ <CardContent className="space-y-3 text-sm text-muted-foreground">+ <p>+ {t("Create a file under ", "在 ")}+ <code className={codeClass}>src/pages/</code>+ {t(" and its location becomes the route:", " 下新建文件,它的位置就是路由:")}+ </p>+ <ul className="space-y-1">+ <li>+ <code className={codeClass}>src/pages/about.tsx</code> → <code className={codeClass}>#/about</code>+ </li>+ <li>+ <code className={codeClass}>src/pages/items/index.tsx</code> → <code className={codeClass}>#/items</code>+ </li>+ <li>+ <code className={codeClass}>src/pages/items/[id].tsx</code> → <code className={codeClass}>#/items/:id</code>+ {" "}({t("nested + dynamic", "嵌套 + 动态")})+ </li>+ </ul>+ <p>+ {t("Export a default component. Add an optional ", "默认导出一个组件。可选导出 ")}+ <code className={codeClass}>meta</code>+ {t(" to set its nav label and order.", " 来设置导航标题和排序。")}+ </p>+ </CardContent>+ </Card>++ <Card>+ <CardHeader>+ <CardTitle>{t("Nested routing", "嵌套路由")}</CardTitle>+ <CardDescription>{t("Folders become nested paths; [param] files capture values.", "文件夹变成嵌套路径;[param] 文件捕获动态值。")}</CardDescription>+ </CardHeader>+ <CardContent>+ <Link to="/items" className="font-medium text-foreground underline underline-offset-4">+ {t("Open the Items demo →", "打开 Items 示例 →")}+ </Link>+ </CardContent>+ </Card>+ </div>+ )+}+"""+++def _default_page_items_index_tsx() -> str:+ # Demo list page under a folder, so the route is nested (#/items) and links+ # into a dynamic child route (#/items/:id).+ return """import { Card, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"+import { Link, t } from "../../router"++export const meta = { title: t("Items", "条目"), order: 1 }++const items = [+ { id: "1", name: t("First item", "第一个条目"), hint: t("A demo record", "示例数据") },+ { id: "2", name: t("Second item", "第二个条目"), hint: t("Another demo record", "另一条示例数据") },+ { id: "3", name: t("Third item", "第三个条目"), hint: t("One more demo record", "再来一条示例数据") },+]++export default function Items() {+ return (+ <div className="space-y-6">+ <div className="space-y-2">+ <h1 className="text-2xl font-semibold tracking-tight">{t("Items", "条目")}</h1>+ <p className="text-muted-foreground">+ {t("Each item links to a nested route such as ", "每个条目都链接到一个嵌套路由,比如 ")}+ <code className="rounded bg-muted px-1.5 py-0.5 font-mono text-xs">#/items/1</code>+ {t(". Open one, then reload — the deep link loads directly.", "。打开其中一个再刷新——深链接会直接加载。")}+ </p>+ </div>++ <div className="grid gap-3 sm:grid-cols-2">+ {items.map((item) => (+ <Link key={item.id} to={"/items/" + item.id} className="block">+ <Card className="h-full transition-colors hover:border-primary/50">+ <CardHeader>+ <CardTitle className="text-base">{item.name}</CardTitle>+ <CardDescription>{item.hint}</CardDescription>+ </CardHeader>+ </Card>+ </Link>+ ))}+ </div>+ </div>+ )+}+"""+++def _default_page_item_detail_tsx() -> str:+ # Demo dynamic route: src/pages/items/[id].tsx -> /items/:id. Reads the id+ # param and is directly deep-linkable / refreshable.+ return """import { Badge } from "@/components/ui/badge"+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"+import { Link, t, type PageProps } from "../../router"++const codeClass = "rounded bg-muted px-1.5 py-0.5 font-mono text-xs"++export default function ItemDetail({ params }: PageProps) {+ return (+ <div className="space-y-6">+ <Link to="/items" className="text-sm text-muted-foreground underline underline-offset-4">+ {t("← Back to Items", "← 返回 Items")}+ </Link>++ <Card>+ <CardHeader>+ <Badge>{t("Nested route", "嵌套路由")}</Badge>+ <CardTitle>{t("Item", "条目")} {params.id}</CardTitle>+ </CardHeader>+ <CardContent className="space-y-2 text-sm text-muted-foreground">+ <p>+ {t("This page is ", "这个页面是 ")}+ <code className={codeClass}>src/pages/items/[id].tsx</code>+ {t(", matched from the URL. The ", ",根据 URL 匹配。参数 ")}+ <code className={codeClass}>id</code>+ {t(" parameter is ", " 的值是 ")}+ <code className={codeClass}>{params.id}</code>.+ </p>+ <p>{t("Reload the page — this deep link resolves on the client, in private and public modes.", "刷新页面——这个深链接会在客户端解析,私有和公开模式都一样。")}</p>+ </CardContent>+ </Card>+ </div>+ )+}+"""+++def _default_styles_css() -> str:+ return """@import "tailwindcss";+@import "@avibe/show-ui/theme.css";++:root {+ color-scheme: light;+}++/*+ * The default multi-page demo styles itself with Tailwind utility classes and the+ * @avibe/show-ui shadcn components, so this entry only needs the two imports above+ * (keep them first) plus a small base. Add global CSS here as the app grows.+ */+body {+ margin: 0;+ font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;}"""diff --git a/core/system_prompt_injection.py b/core/system_prompt_injection.pyindex 74ce62bd2..cf8c37117 100644--- a/core/system_prompt_injection.py+++ b/core/system_prompt_injection.py@@ -93,8 +93,9 @@ History contract:$show_git_agent_contractGuidance:-- New Show Page workspaces are managed React/Vite apps. Edit `src/App.tsx`, `src/styles.css`, and optional `api/*.ts` handler files. Do not replace `index.html` or `src/main.tsx` unless you are repairing the app shell.-- The standard structure is `index.html`, `src/main.tsx`, `src/App.tsx`, `src/styles.css`, and optional `api/*.ts`; treat `index.html` and `src/main.tsx` as the runtime-owned app shell.+- New Show Page workspaces are managed React/Vite apps that start as a small, working multi-page demo with a file-based router (`src/router.tsx`). When that router is present, add a route by creating a file under `src/pages/` — a folder becomes a nested path segment and a `[param]` file a dynamic segment — and customize the nav/layout in `src/App.tsx`, styles in `src/styles.css`, and optional `api/*.ts` handlers. The demo is only a starting point, not a required structure: extend it, replace it, or remove it, and organize pages however fits the app.+- An older Show Page with no `src/router.tsx` is a single-page app that renders `src/App.tsx` directly. There, edit `src/App.tsx` (or adopt the router scaffold: add `src/router.tsx` + `src/pages/` and render it from `App.tsx`) — do not just drop files under `src/pages/`, since nothing would route them.+- Treat `index.html` and `src/main.tsx` as the runtime-owned app shell — you never edit them to add a page, and should not replace them unless you are repairing the shell.- Hot reload is available while `/show/<session-id>/` is open. Users will see page changes live. Prefer component-level changes that preserve React state.- Built-in UI imports include shadcn-style aliases such as `@/components/ui/button`, `@/components/ui/card`, `@/components/ui/badge`, `@/components/ui/dialog`, `@/components/ui/input`, `@/components/ui/progress`, plus `@avibe/show-ui/theme` for theme presets and CSS variables.- Tailwind CSS v4 utility classes are built in and work in any `className`, including to restyle the built-in `@/components/ui/*` components (a utility overrides the component default). `src/styles.css` is the CSS entry and must keep `@import "tailwindcss";` and `@import "@avibe/show-ui/theme.css";` at the top; theme through the `@avibe/show-ui/theme` CSS variables.diff --git a/docs/plans/show-page-multipage-scaffold.md b/docs/plans/show-page-multipage-scaffold.mdnew file mode 100644index 000000000..fab948cd5--- /dev/null+++ b/docs/plans/show-page-multipage-scaffold.md@@ -0,0 +1,94 @@+# Show Page default multi-page scaffold with nested routing (#865)++## Background++A new Show Page workspace starts from a single-page React app (`core/show_pages.py`+`_write_default_runtime_files`). The scaffold proves the page renders but does not show+that a workspace can grow into a multi-page application, so agents tend to keep editing+one `App.tsx`. This issue makes multi-page routing an obvious, executable default without+prescribing what a "page" means.++This is a **capability/affordance** change, not a content policy. It does not define one+page per topic/feature/conversation/history, is not append-only, and does not touch the+durability/recovery scope owned by #669 (platform-owned Git checkpoints).++## Serving model (verified against current code)++- avibe proxies **both** private `/show/<id>/` and public `/p/<share>/` to the **same**+ managed Vite dev server (`vibe-show-runtime`). There is no separate public build; the+ public surface only neutralizes the HMR client via inert shims.+- avibe performs **no** SPA/index.html fallback itself; it passes the upstream status+ through. The runtime's Vite dev server (`appType` defaults to `spa`) does serve a+ base-prefixed `index.html` for nested HTML requests, on both surfaces.+- `index.html` and `src/main.tsx` are the **runtime-owned app shell**. `main.tsx` builds+ `globalThis.__AVIBE_SHOW__` (sessionId, basePath, events paths, writeToken). avibe's+ inline `basePath` regex is anchored to the path end, so it is *not* nested-safe.+- No router is bundled (shared vendor = react, react-dom, jsx runtime, `@avibe/show-ui`,+ `motion`, `lucide-react`). The workspace has no `package.json`.++## Decision: dependency-free hash router, file-based discovery++Router type — **HashRouter (client-only, hash fragment)**:+- Deep-link + refresh on nested routes work in **both** serving modes with zero reliance+ on server SPA-fallback behavior — the browser only ever requests the app root, so the+ existing root-document serving already covers it.+- **No shell edit**: `index.html`/`main.tsx` are untouched. The document URL never leaves+ the app root, so `__AVIBE_SHOW__.basePath`, event endpoints, `./api/*` handler calls,+ and relative assets all keep resolving — avoiding a whole class of relative-URL bugs an+ agent would otherwise hit when adding a page.+- No new dependency; no cross-repo runtime change; no release-gating chain.+- Tradeoff (known-by-design): URLs carry a `#` fragment. This is the standard, fully+ bookmark/PWA-compatible cost of client-only routing over a proxied/static mount.+ Browser-history routing remains a clean future option (the runtime already SPA-falls+ back) but would require a nested-safe `basePath` in the shell and absolute app-level+ fetch URLs; out of scope here.++Discovery — **file-based via Vite `import.meta.glob('./pages/**/*.tsx', { eager: true })`**:+- Adding a page = adding a file under `src/pages/`. No edit to the shell, the router+ engine, or a central route table. Directories create nested path segments; `[param]`+ files create dynamic segments.+- Per-page metadata: optional `export const meta = { title?, order?, nav? }`. Nav is+ derived from static (non-dynamic) pages that opt in; the demo is a starting point the+ agent may restyle, extend, or replace.++Route derivation: `./pages/index.tsx` -> `/`; `./pages/items/index.tsx` -> `/items`;+`./pages/items/[id].tsx` -> `/items/:id`.++## Files++Runtime-owned shell (unchanged, skip-if-exists): `index.html`, `src/main.tsx`,+`api/health.ts`.++Fresh-workspace multi-page demo (written only when `src/App.tsx` does not yet exist, so+existing single-page workspaces stay byte-identical):+- `src/App.tsx` — router host: `ThemeProvider` + `Layout` (nav) + `<RouterView/>`.+- `src/router.tsx` — dependency-free hash-router engine + file-based discovery.+- `src/pages/index.tsx` — Home (overview + how to add a page).+- `src/pages/items/index.tsx` — a list page linking into the nested route.+- `src/pages/items/[id].tsx` — nested dynamic route; deep-linkable/refreshable.+- `src/styles.css` — minimal: keeps `@import "tailwindcss";` + `@import+ "@avibe/show-ui/theme.css";`, plus a small base; demo styling uses Tailwind + show-ui.++## Compatibility++- Existing single-page workspaces: `src/App.tsx` present -> the whole demo set is skipped;+ shell/styles preserved. Renders unchanged.+- The runtime's fallback `ensureSessionTemplate` (single-page) is shadowed by avibe's+ scaffold in the real flow (avibe writes first); no functional dependency on it, so it is+ intentionally out of scope for this PR.++## Verification++- Unit (pytest): scaffold content/structure, fresh-vs-existing gating, shell untouched,+ single-page compatibility, styles imports preserved.+- Build + routing: real Vite build of a scaffolded workspace; route-derivation and matcher+ correctness (static > dynamic precedence, nested, params, 404).+- Real browser (desktop + mobile): nav between routes, nested direct-load via+ `#/items/<id>`, refresh, layout, clean console/network. Local Incus regression for the+ user-facing agent-authored flow if needed.++## System prompt++Update the Show Pages guidance so the shell boundary is explicit and adding a page is the+obvious file-drop pattern — without implying pages must map to topics/history. Keep the+prompt small; the scaffold's executable code is the primary mechanism.diff --git a/tests/test_show_pages.py b/tests/test_show_pages.pyindex f353dd6bc..f8366eca0 100644--- a/tests/test_show_pages.py+++ b/tests/test_show_pages.py@@ -720,9 +720,90 @@ def test_show_page_dir_creates_default_index(monkeypatch, tmp_path):assert 'eventsPath: injected.eventsPath ?? "__show/events"' in main_tsxassert 'streamPath: injected.streamPath ?? "__show/events?stream=1"' in main_tsxassert 'writeToken: injected.writeToken ?? readCookie("vibe_show_event_token")' in main_tsx+ # The runtime-owned shell just renders <App/>; routing is NOT moved into+ # main.tsx/index.html, so adding a page never requires touching the shell.+ assert 'import App from "./App"' in main_tsx+ assert "router" not in main_tsx.lower()app_tsx = (page_dir / "src" / "App.tsx").read_text(encoding="utf-8")- assert "Building your Show Page" in app_tsx- assert "Please visualize this session as a Show Page." in app_tsx+ # The default App is now a multi-page router host, not the old single-page+ # placeholder.+ assert "Building your Show Page" not in app_tsx+ assert 'from "./router"' in app_tsx+ assert "<RouterView" in app_tsx+ assert (page_dir / "api" / "health.ts").exists()+++def test_fresh_workspace_scaffolds_multipage_demo(monkeypatch, tmp_path):+ # A brand-new Show Page workspace starts as a working multi-page app: a router,+ # a nav derived from the pages, and at least two routes including a nested+ # dynamic one. Adding a page is just dropping a file under src/pages/ (found via+ # import.meta.glob), so the shell (index.html/main.tsx) is never edited.+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ page_dir = ensure_show_page_dir("sesmulti")++ router = (page_dir / "src" / "router.tsx").read_text(encoding="utf-8")+ # File-based discovery of pages.+ 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+ assert "useSyncExternalStore" in router+ # A concrete path wins over a matching [param] route of the same length.+ assert "routeSpecificity" in router+ assert "navItems" in router+ assert "export function RouterView" in router+ # A malformed hash param must degrade gracefully, not throw and blank the app.+ assert "safeDecode" in router+ # Pages exported as React exotic components (memo/forwardRef) are accepted.+ assert "isRenderablePage" in router+ assert "$$typeof" in router++ # Demo pages: a home, a nested list, and a nested dynamic detail route.+ home = (page_dir / "src" / "pages" / "index.tsx").read_text(encoding="utf-8")+ assert "export const meta" in home+ assert "export default function" in home+ assert (page_dir / "src" / "pages" / "items" / "index.tsx").exists()+ detail = page_dir / "src" / "pages" / "items" / "[id].tsx"+ assert detail.exists()+ # The dynamic route reads its captured param.+ assert "params.id" in detail.read_text(encoding="utf-8")++ # App composes the router and its nav; it does not hardcode a route table.+ app_tsx = (page_dir / "src" / "App.tsx").read_text(encoding="utf-8")+ assert "navItems" in app_tsx+ assert "<RouterView" in app_tsx++ # styles.css keeps the two imports the runtime's Tailwind pipeline requires,+ # with the tailwindcss import first.+ styles = (page_dir / "src" / "styles.css").read_text(encoding="utf-8")+ assert styles.splitlines()[0].strip() == '@import "tailwindcss";'+ assert '@import "@avibe/show-ui/theme.css";' in styles+++def test_existing_single_page_workspace_is_preserved(monkeypatch, tmp_path):+ # An existing single-page workspace (its own src/App.tsx) must not be migrated:+ # ensure() leaves App.tsx byte-for-byte and does NOT drop router/pages files+ # next to it. Only genuinely-missing shell files are (re)materialized so the+ # workspace stays runnable.+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ page_dir = paths.get_show_page_dir("seslegacy")+ (page_dir / "src").mkdir(parents=True, exist_ok=True)+ legacy_app = "export default function App() {\n return <h1>Legacy single page</h1>\n}\n"+ (page_dir / "src" / "App.tsx").write_text(legacy_app, encoding="utf-8")++ ensure_show_page_dir("seslegacy")++ # The agent's page is untouched.+ assert (page_dir / "src" / "App.tsx").read_text(encoding="utf-8") == legacy_app+ # No multi-page demo is sprinkled next to a customized single-page app.+ assert not (page_dir / "src" / "router.tsx").exists()+ assert not (page_dir / "src" / "pages").exists()+ # Missing shell/workspace files are still materialized.+ assert (page_dir / "index.html").exists()+ assert (page_dir / "src" / "main.tsx").exists()+ assert (page_dir / "src" / "styles.css").exists()assert (page_dir / "api" / "health.ts").exists()