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
Add Show Runtime proxy integration (#341)
Call White9b365da23518
diff --git a/config/v2_sessions.py b/config/v2_sessions.pyindex 87f6b250b..449399680 100644--- a/config/v2_sessions.py+++ b/config/v2_sessions.py@@ -378,6 +378,27 @@ class SessionsStore:self.get_agent_map(user_id, agent_name)[thread_id] = session_idreturn agent_session_id+ def bind_agent_session_by_id(+ self,+ agent_session_id: str,+ native_session_id: Any,+ *,+ workdir: str | None = None,+ vibe_agent_id: str | None = None,+ vibe_agent_name: str | None = None,+ ) -> Optional[str]:+ self._ensure_service()+ bound_id = self._service.bind_agent_session_by_id(+ session_id=agent_session_id,+ native_session_id=native_session_id,+ workdir=workdir,+ vibe_agent_id=vibe_agent_id,+ vibe_agent_name=vibe_agent_name,+ )+ if bound_id:+ self.load()+ return bound_id+def remove_agent_session(self, user_id: str, agent_name: str, thread_id: str) -> bool:self._ensure_service()removed = self._service.delete_agent_session(diff --git a/core/show_pages.py b/core/show_pages.pyindex 0bfc62a35..5791c25ea 100644--- a/core/show_pages.py+++ b/core/show_pages.py@@ -70,9 +70,7 @@ def show_page_dir(session_id: str) -> Path:def ensure_show_page_dir(session_id: str) -> Path:page_dir = show_page_dir(session_id)page_dir.mkdir(parents=True, exist_ok=True)- index_path = page_dir / "index.html"- if not index_path.exists():- index_path.write_text(_default_index_html(validate_session_id(session_id)), encoding="utf-8")+ _write_default_runtime_files(page_dir, validate_session_id(session_id))return page_dir@@ -317,85 +315,241 @@ def show_page_payload(page: ShowPage, *, config: V2Config | None = None) -> dict}+def _write_default_runtime_files(page_dir: Path, session_id: str) -> None:+ files = {+ "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(),+ }+ for relative_path, contents in files.items():+ target = page_dir / relative_path+ if target.exists():+ continue+ target.parent.mkdir(parents=True, exist_ok=True)+ target.write_text(contents, encoding="utf-8")++def _default_index_html(session_id: str) -> str:escaped = session_id.replace("&", "&").replace("<", "<").replace(">", ">")+ prompt = (+ "Please repair this Vibe Remote Show Page. Open the Show Page workspace for session "+ f"{session_id}, read the local Show Page/runtime instructions, then replace src/App.tsx "+ "with a polished React page. Use the shadcn-style components from @/components/ui and "+ "@avibe/show-ui. Do not edit index.html unless it is required. If the browser shows "+ "Ready to visualize, check src/App.tsx, src/main.tsx, src/styles.css, and the Vite/browser "+ "console for compile or runtime errors. Make the page responsive and verify it renders."+ )+ escaped_prompt = prompt.replace("&", "&").replace("<", "<").replace(">", ">")return f"""<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">- <title>Show Page</title>+ <title>Show Page {escaped}</title><style>:root {{- color-scheme: light dark;+ color-scheme: light;font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;- background: #f7f8fb;+ background: #f6f7f9;color: #172033;}}body {{margin: 0;+ min-height: 100vh;+ box-sizing: border-box;+ }}+ #root:not(:empty) + .fallback-shell {{+ display: none;+ }}+ .fallback-shell {{min-height: 100vh;display: grid;place-items: center;padding: 32px 18px;box-sizing: border-box;}}- main {{- width: min(720px, 100%);+ .fallback {{+ width: min(860px, 100%);border: 1px solid rgba(23, 32, 51, 0.12);- border-radius: 14px;- background: rgba(255, 255, 255, 0.86);- padding: clamp(24px, 5vw, 48px);+ border-radius: 18px;+ background: rgba(255, 255, 255, 0.92);+ padding: clamp(24px, 5vw, 44px);box-shadow: 0 24px 80px rgba(23, 32, 51, 0.10);+ box-sizing: border-box;}}- p {{+ .fallback p {{+ max-width: 720px;line-height: 1.65;- margin: 10px 0 0;+ margin: 12px 0 0;+ color: #526078;}}- .eyebrow {{+ .fallback .eyebrow {{color: #526078;font-size: 13px;- font-weight: 700;+ font-weight: 760;letter-spacing: 0.08em;text-transform: uppercase;}}- h1 {{+ .fallback h1 {{margin: 12px 0 0;- font-size: clamp(32px, 8vw, 56px);+ font-size: clamp(32px, 7vw, 56px);line-height: 1;letter-spacing: 0;}}- code {{+ .fallback-grid {{+ display: grid;+ grid-template-columns: minmax(0, 1fr) minmax(280px, 0.8fr);+ gap: 18px;+ margin-top: 24px;+ }}+ .fallback-panel {{+ border: 1px solid rgba(23, 32, 51, 0.10);+ border-radius: 14px;+ background: #fff;+ padding: 16px;+ }}+ .fallback-panel h2 {{+ margin: 0 0 10px;+ font-size: 15px;+ }}+ .fallback-panel ul {{+ margin: 0;+ padding-left: 18px;+ color: #526078;+ line-height: 1.7;+ }}+ .fallback textarea {{+ width: 100%;+ min-height: 178px;+ resize: vertical;+ border: 1px solid rgba(23, 32, 51, 0.14);+ border-radius: 12px;+ padding: 12px;+ box-sizing: border-box;+ font: 13px/1.55 ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace;+ color: #172033;+ background: #f8fafc;+ }}+ .copy-button {{+ margin-top: 10px;+ height: 36px;+ border: 0;+ border-radius: 10px;+ padding: 0 14px;+ background: #0f172a;+ color: #fff;+ font: 700 14px/1 Inter, ui-sans-serif, system-ui;+ cursor: pointer;+ }}+ .fallback code {{background: rgba(82, 96, 120, 0.12);border-radius: 6px;padding: 2px 6px;}}- @media (prefers-color-scheme: dark) {{- :root {{- background: #111827;- color: #edf2ff;- }}- main {{- background: rgba(17, 24, 39, 0.86);- border-color: rgba(237, 242, 255, 0.14);- box-shadow: 0 24px 80px rgba(0, 0, 0, 0.32);- }}- .eyebrow {{- color: #a8b3cf;- }}- code {{- background: rgba(237, 242, 255, 0.12);+ @media (max-width: 760px) {{+ .fallback-grid {{+ grid-template-columns: 1fr;}}}}</style></head><body>- <main>- <div class="eyebrow">Vibe Remote Show Page</div>- <h1>Ready to visualize</h1>- <p>This session's Show Page workspace is ready. Replace this file with a focused visual explanation, report, diagram, dashboard, or prototype.</p>- <p>Session: <code>{escaped}</code></p>- </main>+ <div id="root"></div>+ <section class="fallback-shell">+ <main class="fallback">+ <div class="eyebrow">Vibe Show recovery</div>+ <h1>Ready to visualize</h1>+ <p>The React app has not mounted yet. This can happen during first-load dependency optimization, before the agent writes the page, or when <code>src/App.tsx</code> has a compile/runtime error.</p>+ <div class="fallback-grid">+ <div class="fallback-panel">+ <h2>Ask your agent to fix the Show Page</h2>+ <textarea id="agent-prompt" readonly>{escaped_prompt}</textarea>+ <button class="copy-button" type="button" onclick="navigator.clipboard.writeText(document.getElementById('agent-prompt').value).then(() => this.textContent = 'Copied')">Copy prompt</button>+ </div>+ <div class="fallback-panel">+ <h2>What to check</h2>+ <ul>+ <li>Wait a moment and refresh if this is the first visit.</li>+ <li>Ask the agent to inspect Vite and browser console errors.</li>+ <li>The main file to edit is <code>src/App.tsx</code>.</li>+ <li>Use shared UI imports like <code>@/components/ui/card</code>.</li>+ </ul>+ </div>+ </div>+ <p>Session: <code>{escaped}</code></p>+ </main>+ </section>+ <script type="module" src="./src/main.tsx"></script></body></html>"""+++def _default_main_tsx() -> str:+ return """import React from "react"+import { createRoot } from "react-dom/client"+import "@avibe/show-ui/styles.css"+import "./styles.css"+import App from "./App"++createRoot(document.getElementById("root")!).render(+ <React.StrictMode>+ <App />+ </React.StrictMode>+)+"""+++def _default_app_tsx() -> str:+ return """import { Button } from "@/components/ui/button"+import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"+import { ThemeProvider } from "@avibe/show-ui/theme"++export default function App() {+ return (+ <ThemeProvider preset="zinc">+ <main className="page">+ <Card className="panel">+ <CardHeader>+ <CardTitle>Ready to visualize</CardTitle>+ <CardDescription>This Show Page is served by the managed React runtime.</CardDescription>+ </CardHeader>+ <CardContent>+ <Button onClick={() => void fetch("./api/health")}>Call handler</Button>+ </CardContent>+ </Card>+ </main>+ </ThemeProvider>+ )+}+"""+++def _default_styles_css() -> str:+ return """body {+ margin: 0;+ font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;+ background: #f6f7f9;+ color: hsl(var(--avs-foreground));+}++.page {+ min-height: 100vh;+ display: grid;+ place-items: center;+ padding: 24px;+}++.panel {+ width: min(560px, 100%);+}+"""+++def _default_api_health_ts() -> str:+ return """export async function GET() {+ return Response.json({ ok: true, message: "Show Runtime handler is ready." })+}+"""diff --git a/core/show_runtime.py b/core/show_runtime.pynew file mode 100644index 000000000..039316d2d--- /dev/null+++ b/core/show_runtime.py@@ -0,0 +1,379 @@+from __future__ import annotations++import atexit+import asyncio+import logging+import os+import shlex+import shutil+import signal+import subprocess+from dataclasses import dataclass+from pathlib import Path+from typing import Any++import httpx++from config import paths+from core.process_isolation import KILL_SIGNAL, isolated_subprocess_kwargs, signal_process_tree+++logger = logging.getLogger(__name__)+_RUNTIME_BIN = "avibe-show-runtime"+_RUNTIME_PACKAGE = "@avibe/show-runtime"+_RUNTIME_GITHUB_REPO = "https://github.com/avibe-bot/vibe-show-runtime.git"+_RUNTIME_GITHUB_REF = "main"+_RUNTIME_SOURCE_GITHUB = "github"+_RUNTIME_SOURCE_NPM = "npm"+_FALSE_VALUES = {"0", "false", "no", "off"}+++@dataclass(frozen=True)+class ShowRuntimeResult:+ available: bool+ base_url: str | None = None+ reason: str | None = None+++class ShowRuntimeManager:+ def __init__(+ self,+ *,+ command: str | None = None,+ workspace_root: Path | None = None,+ runtime_dir: Path | None = None,+ auto_install: bool | None = None,+ package_spec: str | None = None,+ runtime_source: str | None = None,+ github_repo: str | None = None,+ github_ref: str | None = None,+ ) -> None:+ self.command = command or os.environ.get("VIBE_SHOW_RUNTIME_BIN") or _RUNTIME_BIN+ self.workspace_root = workspace_root or paths.get_show_pages_dir()+ self.runtime_dir = runtime_dir or paths.get_runtime_dir() / "show-runtime"+ self.auto_install = _auto_install_enabled() if auto_install is None else auto_install+ self.package_spec = package_spec or os.environ.get("VIBE_SHOW_RUNTIME_PACKAGE_SPEC") or _RUNTIME_PACKAGE+ self.runtime_source = _normalize_runtime_source(runtime_source or os.environ.get("VIBE_SHOW_RUNTIME_SOURCE"))+ self.github_repo = github_repo or os.environ.get("VIBE_SHOW_RUNTIME_GITHUB_REPO") or _RUNTIME_GITHUB_REPO+ self.github_ref = github_ref or os.environ.get("VIBE_SHOW_RUNTIME_GITHUB_REF") or _RUNTIME_GITHUB_REF+ self.stdout_path = self.runtime_dir / "stdout.log"+ self.stderr_path = self.runtime_dir / "stderr.log"+ self.install_log_path = self.runtime_dir / "install.log"+ self._install_attempted = False+ self._install_reason: str | None = None+ self._managed_command: list[str] | None = None+ self._process: subprocess.Popen[str] | None = None+ self._base_url: str | None = None+ self._lock = asyncio.Lock()++ async def ensure(self) -> ShowRuntimeResult:+ if self._base_url and await self._healthy(self._base_url):+ return ShowRuntimeResult(True, self._base_url)+ async with self._lock:+ if self._base_url and await self._healthy(self._base_url):+ return ShowRuntimeResult(True, self._base_url)+ self.stop()+ command = _resolve_command(self.command)+ if not command:+ command = await self._resolve_managed_command()+ if not command:+ return ShowRuntimeResult(False, reason=self._install_reason or "runtime_command_missing")+ self.runtime_dir.mkdir(parents=True, exist_ok=True)+ self.workspace_root.mkdir(parents=True, exist_ok=True)+ with self.stdout_path.open("w", encoding="utf-8") as stdout, self.stderr_path.open(+ "w", encoding="utf-8"+ ) as stderr:+ self._process = subprocess.Popen(+ [+ *command,+ "--workspace-root",+ str(self.workspace_root),+ "--host",+ "127.0.0.1",+ "--port",+ "0",+ ],+ stdout=stdout,+ stderr=stderr,+ text=True,+ **isolated_subprocess_kwargs(),+ )+ base_url = await self._read_startup_url()+ if not base_url:+ self.stop()+ return ShowRuntimeResult(False, reason="runtime_start_failed")+ self._base_url = base_url+ return ShowRuntimeResult(True, base_url)++ async def request(+ self,+ method: str,+ path: str,+ *,+ headers: dict[str, str] | None = None,+ body: bytes | None = None,+ ) -> httpx.Response:+ ready = await self.ensure()+ if not ready.available or not ready.base_url:+ raise RuntimeError(ready.reason or "show runtime unavailable")+ async with httpx.AsyncClient(timeout=httpx.Timeout(30.0, connect=5.0)) as client:+ return await client.request(method, f"{ready.base_url}{path}", headers=headers, content=body)++ async def websocket_url(self, path: str) -> str:+ ready = await self.ensure()+ if not ready.available or not ready.base_url:+ raise RuntimeError(ready.reason or "show runtime unavailable")+ return f"{ready.base_url.replace('http://', 'ws://', 1).replace('https://', 'wss://', 1)}{path}"++ async def _healthy(self, base_url: str) -> bool:+ try:+ async with httpx.AsyncClient(timeout=httpx.Timeout(2.0, connect=0.5)) as client:+ response = await client.get(f"{base_url}/health")+ return response.status_code == 200+ except Exception:+ return False++ async def _read_startup_url(self) -> str | None:+ deadline = asyncio.get_running_loop().time() + 10+ while asyncio.get_running_loop().time() < deadline:+ if self._process and self._process.poll() is not None:+ return None+ try:+ text = self.stdout_path.read_text(encoding="utf-8")+ except FileNotFoundError:+ text = ""+ for line in reversed(text.splitlines()):+ marker = "Vibe Show Runtime listening at "+ if marker in line:+ return line.split(marker, 1)[1].strip()+ await asyncio.sleep(0.05)+ return None++ def stop(self) -> None:+ process = self._process+ self._process = None+ self._base_url = None+ if not process or process.poll() is not None:+ return+ signal_process_tree(process, signal.SIGTERM, logger, "show runtime")+ try:+ process.wait(timeout=5)+ except subprocess.TimeoutExpired:+ signal_process_tree(process, KILL_SIGNAL, logger, "show runtime")++ async def _resolve_managed_command(self) -> list[str] | None:+ if self.command != _RUNTIME_BIN:+ self._install_reason = "runtime_command_missing"+ return None+ managed = self._managed_bin_path()+ resolved = _resolve_executable_path(managed)+ if resolved:+ return [resolved]+ if self._managed_command:+ return self._managed_command+ if self.runtime_source == _RUNTIME_SOURCE_GITHUB:+ command = self._installed_github_runtime_command()+ if command:+ self._managed_command = command+ return command+ if not self.auto_install:+ self._install_reason = "runtime_command_missing"+ return None+ if self._install_attempted:+ return None+ self._install_attempted = True+ command = await asyncio.to_thread(self._install_managed_runtime)+ if command:+ self._managed_command = command+ return command++ def _install_managed_runtime(self) -> list[str] | None:+ if self.runtime_source == _RUNTIME_SOURCE_GITHUB:+ return self._install_github_runtime()+ if self.runtime_source == _RUNTIME_SOURCE_NPM:+ return self._install_npm_runtime()+ self._install_reason = "runtime_source_unsupported"+ return None++ def _installed_github_runtime_command(self) -> list[str] | None:+ node = _resolve_command("node")+ if not node:+ return None+ return self._github_runtime_command(self._github_source_dir(), node)++ def _install_github_runtime(self) -> list[str] | None:+ node = _resolve_command("node")+ if not node:+ self._install_reason = "runtime_node_missing"+ return None+ self.runtime_dir.mkdir(parents=True, exist_ok=True)+ source_dir = self._github_source_dir()+ existing_command = self._github_runtime_command(source_dir, node)+ git = _resolve_command("git")+ npm = _resolve_command("npm")+ if not git:+ if existing_command:+ self._install_reason = None+ return existing_command+ self._install_reason = "runtime_git_missing"+ return None+ if not npm:+ if existing_command:+ self._install_reason = None+ return existing_command+ self._install_reason = "runtime_npm_missing"+ return None+ if not source_dir.exists():+ source_dir.parent.mkdir(parents=True, exist_ok=True)+ if not self._run_install_command([*git, "clone", "--depth", "1", "--branch", self.github_ref, self.github_repo, str(source_dir)]):+ return None+ else:+ if not self._run_install_command([*git, "-C", str(source_dir), "fetch", "--depth", "1", "origin", self.github_ref]):+ return self._reuse_existing_github_runtime(existing_command)+ if not self._run_install_command([*git, "-C", str(source_dir), "checkout", "FETCH_HEAD"]):+ return self._reuse_existing_github_runtime(existing_command)+ if not self._run_install_command([*npm, "ci"], cwd=source_dir):+ return self._reuse_existing_github_runtime(existing_command)+ if not self._run_install_command([*npm, "run", "build"], cwd=source_dir):+ return self._reuse_existing_github_runtime(existing_command)+ command = self._github_runtime_command(source_dir, node)+ if not command:+ self._install_reason = "runtime_install_missing_bin"+ return None+ return command++ def _github_runtime_command(self, source_dir: Path, node: list[str]) -> list[str] | None:+ cli_path = source_dir / "packages" / "runtime" / "dist" / "cli.js"+ if not cli_path.exists():+ return None+ return [*node, str(cli_path)]++ def _reuse_existing_github_runtime(self, command: list[str] | None) -> list[str] | None:+ if command:+ self._install_reason = None+ return command+ return None++ def _install_npm_runtime(self) -> list[str] | None:+ npm = _resolve_command("npm")+ if not npm:+ self._install_reason = "runtime_npm_missing"+ return None+ self.runtime_dir.mkdir(parents=True, exist_ok=True)+ install_root = self.runtime_dir / "package"+ install_root.mkdir(parents=True, exist_ok=True)+ package_json = install_root / "package.json"+ if not package_json.exists():+ package_json.write_text('{"private":true,"type":"module"}\n', encoding="utf-8")+ with self.install_log_path.open("w", encoding="utf-8") as log:+ result = subprocess.run(+ [+ *npm,+ "install",+ "--prefix",+ str(install_root),+ "--no-audit",+ "--no-fund",+ self.package_spec,+ ],+ stdout=log,+ stderr=subprocess.STDOUT,+ text=True,+ timeout=180,+ check=False,+ **isolated_subprocess_kwargs(),+ )+ if result.returncode != 0:+ self._install_reason = "runtime_install_failed"+ return None+ resolved = _resolve_executable_path(self._managed_bin_path())+ if not resolved:+ self._install_reason = "runtime_install_missing_bin"+ return None+ return [resolved]++ def _managed_bin_path(self) -> Path:+ suffix = ".cmd" if os.name == "nt" else ""+ return self.runtime_dir / "package" / "node_modules" / ".bin" / f"{_RUNTIME_BIN}{suffix}"++ def _github_source_dir(self) -> Path:+ repo_slug = self.github_repo.removesuffix(".git").rstrip("/").rsplit("/", 2)[-2:]+ repo_part = "_".join(repo_slug) if len(repo_slug) == 2 else "vibe-show-runtime"+ ref_part = _safe_path_part(self.github_ref)+ return self.runtime_dir / "source" / "github" / repo_part / ref_part++ def _run_install_command(self, command: list[str], *, cwd: Path | None = None) -> bool:+ with self.install_log_path.open("a", encoding="utf-8") as log:+ log.write(f"$ {' '.join(command)}\n")+ result = subprocess.run(+ command,+ cwd=str(cwd) if cwd else None,+ stdout=log,+ stderr=subprocess.STDOUT,+ text=True,+ timeout=300,+ check=False,+ **isolated_subprocess_kwargs(),+ )+ if result.returncode != 0:+ self._install_reason = "runtime_install_failed"+ return False+ return True+++_manager: ShowRuntimeManager | None = None+++def get_show_runtime_manager() -> ShowRuntimeManager:+ global _manager+ if _manager is None:+ _manager = ShowRuntimeManager()+ return _manager+++def stop_show_runtime_manager() -> None:+ if _manager is not None:+ _manager.stop()+++def set_show_runtime_manager_for_tests(manager: ShowRuntimeManager | None) -> None:+ global _manager+ _manager = manager+++def _auto_install_enabled() -> bool:+ value = os.environ.get("VIBE_SHOW_RUNTIME_AUTO_INSTALL")+ return value is None or value.strip().lower() not in _FALSE_VALUES+++def _normalize_runtime_source(value: str | None) -> str:+ normalized = (value or _RUNTIME_SOURCE_GITHUB).strip().lower()+ return normalized or _RUNTIME_SOURCE_GITHUB+++def _safe_path_part(value: str) -> str:+ cleaned = "".join(ch if ch.isalnum() or ch in "._-" else "_" for ch in value.strip())+ return cleaned or "main"+++def _resolve_command(command: str) -> list[str] | None:+ parts = shlex.split(command)+ if not parts:+ return None+ executable = parts[0]+ if os.path.sep in executable or (os.altsep is not None and os.altsep in executable):+ path = Path(executable).expanduser()+ resolved = str(path) if path.exists() and os.access(path, os.X_OK) else None+ else:+ resolved = shutil.which(executable)+ if not resolved:+ return None+ return [resolved, *parts[1:]]+++def _resolve_executable_path(path: Path) -> str | None:+ expanded = path.expanduser()+ return str(expanded) if expanded.exists() and os.access(expanded, os.X_OK) else None+++atexit.register(stop_show_runtime_manager)diff --git a/core/system_prompt_injection.py b/core/system_prompt_injection.pyindex c2a384564..ad50beb26 100644--- a/core/system_prompt_injection.py+++ b/core/system_prompt_injection.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport osfrom pathlib import Path+from string import Templatefrom typing import Optionalfrom config import paths@@ -43,31 +44,37 @@ Example: _SHOW_PAGES_PROMPT = """\## Show Pages-When a visual page would help the user understand a problem, plan, process, result, or complex information more clearly, use Show Pages. They are useful for diagrams, flowcharts, mind maps, timelines, architecture maps, comparison views, dashboards, visual reports, interactive explanations, and small static prototypes.+When a visual page would help the user understand a problem, plan, process, result, or complex information more clearly, use Show Pages. They are useful for diagrams, flowcharts, mind maps, timelines, architecture maps, comparison views, dashboards, visual reports, interactive explanations, and small prototypes.Each Agent Session has one Show Page. Get this session's page directory:-`vibe show path --session-id {default_session_id}`+`vibe show path --session-id $default_session_id`Check status:-`vibe show status --session-id {default_session_id}`+`vibe show status --session-id $default_session_id`Change visibility:-`vibe show update --session-id {default_session_id} --visibility public`-`vibe show update --session-id {default_session_id} --visibility private`-`vibe show update --session-id {default_session_id} --visibility offline`+`vibe show update --session-id $default_session_id --visibility public`+`vibe show update --session-id $default_session_id --visibility private`+`vibe show update --session-id $default_session_id --visibility offline`For more usage details, run `vibe show --help` or a subcommand help such as `vibe show update --help`.-{avibe_cloud_guidance_section}+$avibe_cloud_guidance_sectionGuidance:-- Write `index.html` and related static assets in the Show Page directory.+- 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.+- Hot reload is available while the private `/show/<session-id>/` page is open. 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.+- Prefer the built-in UI primitives over hand-rolled controls. They include Show Page motion for changed text, numbers, badges, cards, and progress without extra animation calls.+- Optional server handlers live under `api/` and run only when requested. Export functions named like HTTP methods, for example `export async function GET(request) { return Response.json({ ok: true }) }`.+- If the browser shows "Ready to visualize", the React app did not mount. Check `src/App.tsx`, `src/main.tsx`, `src/styles.css`, and the Vite/browser console, then repair the React page.- Design for user understanding, not just for moving text onto a webpage. Choose the visual form that best helps the user inspect, compare, confirm, and continue the discussion.- Use diagrams or mind maps for relationships, flowcharts or state machines for processes, timelines for sequences, charts or dashboards for metrics, and side-by-side views for tradeoffs.- Make the page visually polished: use clear hierarchy, spacing, typography, contrast, and consistent components. Avoid rough default-looking pages.- Make the page work reasonably on mobile because users may open links from an IM app on their phone.-- You may choose any suitable implementation. Reference options include native HTML/CSS/JavaScript, Excalidraw-style static SVG/PNG diagrams, React Flow, Mermaid, Markmap, Chart.js, and Cytoscape.js.+- Prefer React component implementations. Useful visualization libraries include React Flow, Mermaid, Markmap, Chart.js, and Cytoscape.js.- Keep pages private by default. Publish publicly only when the user asks for a shareable or public link.- Do not publish secrets, credentials, private logs, or sensitive user data publicly.- If a Show Page would clearly help but the user's preference is unclear, briefly ask whether they want one.@@ -158,7 +165,7 @@ def _build_show_pages_prompt(context: MessageContext, *, avibe_cloud_guidance: sdefault_session_id = platform_specific.get("agent_session_id")if not default_session_id:raise ValueError("agent_session_id is required before building Vibe Remote capability prompt")- return _SHOW_PAGES_PROMPT.format(+ return Template(_SHOW_PAGES_PROMPT).substitute(default_session_id=str(default_session_id),avibe_cloud_guidance_section=f"\n{avibe_cloud_guidance}\n" if avibe_cloud_guidance else "\n",)diff --git a/docs/plans/show-service-runtime.md b/docs/plans/show-service-runtime.mdnew file mode 100644index 000000000..bdd94dd2b--- /dev/null+++ b/docs/plans/show-service-runtime.md@@ -0,0 +1,248 @@+# Show Service Runtime Integration Plan++## Summary++Show Pages are moving from static visual files to session-scoped visual+services.++Every Agent Session still has one Show Page URL. Vibe Remote owns that URL,+session visibility, authentication, public sharing policy, and remote-access+host checks. A managed Node sidecar owns the React/Vite runtime, hot reload,+shared UI dependencies, and optional server handlers.++The companion runtime project plan lives in `../../../vibe-show-runtime/docs/plan.md`.++## Product Goals++- Make Show Page the default visual collaboration surface for agent sessions.+- Let agents write React components with Vite hot reload.+- Let agents optionally add backend handlers without starting arbitrary web+ frameworks or allocating per-session ports.+- Keep one internal runtime sidecar, not one public dev server per session.+- Avoid per-session dependency installs and session-local `node_modules`+ growth.+- Keep the runtime independently releasable from Vibe Remote when the Python+ integration contract does not change.++## Runtime Modes++The target runtime model has two modes:++- `service`: the default managed runtime. It supports React UI and optional+ server handlers in one stack.+- `external`: a future advanced escape hatch for user-owned processes.++Static files are now compatibility fallback, not a first-class new-session+mode. Existing static pages still serve when the runtime is unavailable or when+the workspace contains only static assets.++## Architecture++```text+User browser+ -> /show/<session-id>/...+ -> Vibe Remote Web UI server+ - validates host and remote-access login+ - enforces Show Page visibility+ - strips UI credentials before proxying+ - starts or wakes Show Runtime on demand+ - proxies HTTP, service handlers, and Vite HMR WebSocket+ -> Vibe Show Runtime sidecar on 127.0.0.1:<internal-port>+ - manages active session Vite contexts+ - serves React app and assets+ - runs optional api/*.ts handlers+ - reuses shared dependencies+```++The sidecar binds only to loopback. Vibe Remote remains the only public entry+point through the local UI server and Avibe Cloud tunnel.++## Current Integration Contract++Vibe Remote proxies private Show Pages to the sidecar:++```text+GET/HEAD /show/<session-id>/...+ANY /show/<session-id>/api/...+WS /show/<session-id>/__vite_hmr+```++Sidecar routes:++```text+GET /health+POST /sessions/:sessionId/ensure+GET /sessions/:sessionId/status+POST /sessions/:sessionId/suspend+ANY /sessions/:sessionId/app/*+```++Important policies:++- private `/show/...` can use live service runtime+- public `/p/...` keeps static/public-file behavior for now+- live service handlers are not exposed through public share links yet+- offline pages keep the existing offline response+- Vibe Remote never forwards UI cookies, authorization headers, CSRF headers,+ or `Set-Cookie` between browser and sidecar+- HMR WebSocket separately checks local loopback or remote-access session+ cookie, because FastAPI WebSocket routes do not pass through HTTP+ `before_request` hooks++## Session Workspace++New `vibe show path` workspaces are React/Vite workspaces:++```text+~/.vibe_remote/show/<session-id>/+ index.html+ src/+ main.tsx+ App.tsx+ styles.css+ api/+ health.ts+```++Pure frontend page:++```tsx+export default function App() {+ return <main>Hello from this session</main>+}+```++Page with backend behavior:++```ts+export async function GET() {+ return Response.json({ ok: true })+}++export async function POST(request: Request) {+ const body = await request.json()+ return Response.json({ received: body })+}+```++Front-end code calls handlers through relative paths:++```ts+await fetch("./api/data")+```++## UI SDK And shadcn Alias Strategy++The default visual direction is shadcn-style. Agents should not run the shadcn+CLI inside each session, and Vibe Remote should not copy component source into+each workspace.++The runtime owns a shared UI package:++```text+@avibe/show-ui+@avibe/show-ui/button+@avibe/show-ui/card+@avibe/show-ui/dialog+@avibe/show-ui/input+@avibe/show-ui/progress+@avibe/show-ui/switch+@avibe/show-ui/theme+@avibe/show-ui/utils+```++To preserve agent prior knowledge, the runtime also supports familiar shadcn+import paths:++```tsx+import { Button } from "@/components/ui/button"+import { Card, CardContent } from "@/components/ui/card"+import { cn } from "@/lib/utils"+```++Those paths resolve to `@avibe/show-ui/*` inside the shared dependency store.++Theme customization is token-based through `@avibe/show-ui/theme`, so agents+can use presets or override CSS variables without editing component source.++## Shared Dependencies++Dependencies are owned by the runtime, not by each session.++Vibe Remote resolution order:++1. `VIBE_SHOW_RUNTIME_BIN`, for local development or pinned custom runtime.+2. `avibe-show-runtime` on PATH.+3. Managed GitHub source install under Vibe Remote runtime state.++Managed GitHub source install:++```text+~/.vibe_remote/runtime/show-runtime/source/github/avibe-bot_vibe-show-runtime/main/+ package.json+ node_modules/+ packages/runtime/dist/cli.js+```++The default managed source is GitHub, so early runtime iteration does not+require publishing npm packages for every change:++```bash+VIBE_SHOW_RUNTIME_SOURCE=github+VIBE_SHOW_RUNTIME_GITHUB_REPO=https://github.com/avibe-bot/vibe-show-runtime.git+VIBE_SHOW_RUNTIME_GITHUB_REF=main+```++For stable releases, the same manager can use npm explicitly:++```bash+VIBE_SHOW_RUNTIME_SOURCE=npm+VIBE_SHOW_RUNTIME_PACKAGE_SPEC=@avibe/show-runtime+```++`VIBE_SHOW_RUNTIME_AUTO_INSTALL=0` disables managed install entirely.++## Lifecycle++Runtime state is automatic and demand-driven:++```text+created -> warming -> active -> idle -> suspended+```++Rules:++- opening `/show/<session-id>/` wakes a suspended session+- cold wake requires no CLI command or agent action+- active Vite contexts should be bounded by idle TTL and LRU pressure+- historical sessions should consume disk only, not watchers or module graphs++The first implementation starts the sidecar lazily from Vibe Remote. Runtime+context TTL/LRU enforcement belongs in `@avibe/show-runtime`.++## Dynamic Runtime Updates++Vibe Remote can update the Show Runtime independently if the sidecar API stays+compatible:++- runtime releases can be GitHub refs during fast iteration and npm package+ versions for stable channels+- Vibe Remote installs them under managed runtime state+- active sessions keep their current process until idle or restart+- new sessions use the currently installed package+- template migrations must be explicit and idempotent++Vibe Remote still needs a Python release when routing, auth, CLI, storage, or+prompt behavior changes.++## Remaining Work++- Publish `@avibe/show-runtime`, `@avibe/show-ui`, and `@avibe/show-sdk` under+ the `@avibe` npm organization when the runtime API stabilizes.+- Add runtime status to `vibe show status`.+- Add sidecar logs/error surfacing to the UI.+- Implement active-context TTL/LRU limits in the runtime package.+- Define public snapshot publishing for `/p/<share-id>/`; do not proxy live+ handlers publicly until that policy exists.+- Expand `@avibe/show-ui` component coverage and default visualization+ dependencies.diff --git a/modules/agents/opencode/session.py b/modules/agents/opencode/session.pyindex 34df7a0e4..88ffd68e1 100644--- a/modules/agents/opencode/session.py+++ b/modules/agents/opencode/session.py@@ -66,7 +66,20 @@ class OpenCodeSessionManager:payload["agent_session_id"] = agent_session_idrequest.context.platform_specific = payload+ def _reserved_agent_session_id(self, request: AgentRequest) -> Optional[str]:+ payload = request.context.platform_specific or {}+ session_target = payload.get("agent_session_target")+ if isinstance(session_target, dict):+ target_id = str(session_target.get("id") or "").strip()+ if target_id:+ return target_id+ return None+def ensure_agent_session_id(self, request: AgentRequest, composite_session_key: str) -> Optional[str]:+ reserved_id = self._reserved_agent_session_id(request)+ if reserved_id:+ self._set_request_agent_session_id(request, reserved_id)+ return reserved_idsessions = getattr(self._settings_manager, "sessions", self._settings_manager)ensure = getattr(sessions, "ensure_agent_session_id", None)if callable(ensure):@@ -88,6 +101,22 @@ class OpenCodeSessionManager:opencode_session_id: str,) -> Optional[str]:sessions = getattr(self._settings_manager, "sessions", self._settings_manager)+ reserved_id = self._reserved_agent_session_id(request)+ if reserved_id:+ bind_by_id = getattr(sessions, "bind_agent_session_by_id", None)+ if callable(bind_by_id):+ agent_session_id = bind_by_id(+ reserved_id,+ opencode_session_id,+ workdir=request.working_path,+ vibe_agent_id=request.vibe_agent_id,+ vibe_agent_name=request.vibe_agent_name,+ )+ if agent_session_id:+ self._set_request_agent_session_id(request, agent_session_id)+ return agent_session_id+ self._set_request_agent_session_id(request, reserved_id)+ return reserved_idbinder = getattr(sessions, "bind_agent_session", None)if callable(binder):agent_session_id = binder(diff --git a/modules/sessions_facade.py b/modules/sessions_facade.pyindex a7aa5448a..41224b7cb 100644--- a/modules/sessions_facade.py+++ b/modules/sessions_facade.py@@ -111,6 +111,26 @@ class SessionsFacade:vibe_agent_name=vibe_agent_name,)+ def bind_agent_session_by_id(+ self,+ agent_session_id: str,+ native_session_id: Any,+ *,+ workdir: str | None = None,+ vibe_agent_id: str | None = None,+ vibe_agent_name: str | None = None,+ ) -> Optional[str]:+ binder = getattr(self.sessions_store, "bind_agent_session_by_id", None)+ if not callable(binder):+ return None+ return binder(+ agent_session_id,+ native_session_id,+ workdir=workdir,+ vibe_agent_id=vibe_agent_id,+ vibe_agent_name=vibe_agent_name,+ )+def clear_agent_session_mapping(self,user_id: Union[int, str],diff --git a/storage/sessions_service.py b/storage/sessions_service.pyindex 9d99bf11e..0637b1792 100644--- a/storage/sessions_service.py+++ b/storage/sessions_service.py@@ -225,6 +225,38 @@ class SQLiteSessionsService:conn.execute(agent_sessions.update().where(agent_sessions.c.id == row_id).values(**values))return row_id+ def bind_agent_session_by_id(+ self,+ *,+ session_id: str,+ native_session_id: Any,+ workdir: str | None = None,+ vibe_agent_id: str | None = None,+ vibe_agent_name: str | None = None,+ ) -> str | None:+ """Bind a backend-native session id to an already-reserved Vibe session row."""+ now = _utc_now_iso()+ encoded_session_id = encode_session_value(native_session_id)+ values = {+ "native_session_id": encoded_session_id,+ "status": "active",+ "updated_at": now,+ "last_active_at": now,+ }+ if workdir is not None:+ values["workdir"] = str(workdir) or None+ if vibe_agent_id is not None:+ values["agent_id"] = vibe_agent_id+ if vibe_agent_name is not None:+ values["agent_name"] = vibe_agent_name+ with self.engine.begin() as conn:+ result = conn.execute(+ agent_sessions.update()+ .where(agent_sessions.c.id == str(session_id))+ .values(**values)+ )+ return str(session_id) if result.rowcount else None+def delete_agent_session(self,*,diff --git a/tests/test_opencode_session_manager.py b/tests/test_opencode_session_manager.pyindex a3aa4eeff..845ab9ac9 100644--- a/tests/test_opencode_session_manager.py+++ b/tests/test_opencode_session_manager.py@@ -48,6 +48,36 @@ def test_opencode_reused_session_attaches_agent_session_id() -> None:)+def test_opencode_reserved_agent_session_id_is_not_replaced() -> None:+ sessions = SimpleNamespace(+ get_agent_session_id=Mock(return_value="oc-session-1"),+ ensure_agent_session_id=Mock(return_value="ses-different"),+ bind_agent_session=Mock(return_value="ses-different"),+ bind_agent_session_by_id=Mock(return_value="ses-reserved"),+ )+ manager = OpenCodeSessionManager(SimpleNamespace(sessions=sessions), "opencode")+ server = SimpleNamespace(get_session=AsyncMock(return_value={"id": "oc-session-1"}))+ request = _request()+ request.context.platform_specific = {+ "agent_session_id": "ses-reserved",+ "agent_session_target": {"id": "ses-reserved"},+ }++ session_id = asyncio.run(manager.get_or_create_session_id(request, server))++ assert session_id == "oc-session-1"+ assert request.context.platform_specific["agent_session_id"] == "ses-reserved"+ sessions.ensure_agent_session_id.assert_not_called()+ sessions.bind_agent_session.assert_not_called()+ sessions.bind_agent_session_by_id.assert_called_once_with(+ "ses-reserved",+ "oc-session-1",+ workdir="/repo",+ vibe_agent_id=None,+ vibe_agent_name=None,+ )++def test_session_facade_ensure_fallback_does_not_clear_existing_native_session() -> None:class _LegacyStore:def __init__(self):diff --git a/tests/test_reply_enhancer_platform.py b/tests/test_reply_enhancer_platform.pyindex 7208b3fb5..54a20aedc 100644--- a/tests/test_reply_enhancer_platform.py+++ b/tests/test_reply_enhancer_platform.py@@ -221,7 +221,10 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):self.assertIn("## Show Pages", prompt)self.assertIn("`vibe show path --session-id sesk8m4q2p7x`", prompt)self.assertIn("Make the page work reasonably on mobile", prompt)- self.assertIn("Excalidraw-style static SVG/PNG diagrams", prompt)+ self.assertIn("managed React/Vite apps", prompt)+ self.assertIn("Ready to visualize", prompt)+ self.assertIn("@/components/ui/progress", prompt)+ self.assertNotIn("Excalidraw-style static SVG/PNG diagrams", prompt)self.assertNotIn("Avibe Cloud is not connected", prompt)self.assertIn("## Scheduled tasks, watches, and hooks", prompt)self.assertIn("`vibe task add`", prompt)@@ -288,6 +291,23 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):self.assertIn("register an avibe.bot account", prompt)self.assertIn("`vibe remote pair`", prompt)+ def test_show_pages_prompt_allows_literal_typescript_braces(self):+ context = MessageContext(+ user_id="U1",+ channel_id="C1",+ platform="slack",+ platform_specific={"agent_session_id": "sesk8m4q2p7x"},+ )++ with patch.object(paths, "get_user_preferences_path", return_value=Path("/tmp/user_preferences.md")):+ prompt = build_system_prompt_injection(+ include_quick_replies=False,+ context=context,+ )++ self.assertIn("`vibe show path --session-id sesk8m4q2p7x`", prompt)+ self.assertIn("export async function GET(request) { return Response.json({ ok: true }) }", prompt)+def test_prompt_uses_fallback_platform_for_unannotated_context(self):context = MessageContext(user_id="U1",diff --git a/tests/test_show_pages.py b/tests/test_show_pages.pyindex 59219252f..cef34c5e2 100644--- a/tests/test_show_pages.py+++ b/tests/test_show_pages.py@@ -162,7 +162,11 @@ def test_show_page_dir_creates_default_index(monkeypatch, tmp_path):index_path = page_dir / "index.html"assert page_dir == tmp_path / "show" / "ses123"assert index_path.exists()- assert "Ready to visualize" in index_path.read_text(encoding="utf-8")+ index_html = index_path.read_text(encoding="utf-8")+ assert 'src="./src/main.tsx"' in index_html+ assert "Ready to visualize" in index_html+ assert "Ready to visualize" in (page_dir / "src" / "App.tsx").read_text(encoding="utf-8")+ assert (page_dir / "api" / "health.ts").exists()def test_show_path_cli_json_creates_page(monkeypatch, tmp_path, capsys):diff --git a/tests/test_sqlite_sessions_store.py b/tests/test_sqlite_sessions_store.pyindex dfb01ce8d..35ee021e3 100644--- a/tests/test_sqlite_sessions_store.py+++ b/tests/test_sqlite_sessions_store.py@@ -229,6 +229,33 @@ def test_sqlite_sessions_service_reserves_then_binds_agent_session_id(tmp_path:service.close()+def test_sqlite_sessions_service_binds_reserved_agent_session_by_id(tmp_path: Path) -> None:+ db_path = tmp_path / "vibe.sqlite"+ service = SQLiteSessionsService(db_path)+ try:+ reserved_id = service.reserve_agent_session(+ scope_key="slack::channel::C123",+ agent_backend="opencode",+ session_anchor="slack_private-agent",+ agent_name="opencode",+ )+ assert reserved_id is not None++ bound_id = service.bind_agent_session_by_id(+ session_id=reserved_id,+ native_session_id="oc-session-1",+ workdir="/repo",+ )++ assert bound_id == reserved_id+ row = service.get_agent_session_by_id(reserved_id)+ assert row is not None+ assert row["native_session_id"] == "oc-session-1"+ assert row["workdir"] == "/repo"+ finally:+ service.close()++def test_sqlite_sessions_service_delete_agent_sessions_escapes_anchor_prefix(tmp_path: Path) -> None:db_path = tmp_path / "vibe.sqlite"service = SQLiteSessionsService(db_path)diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.pyindex a9beb962d..3de5701d5 100644--- a/tests/test_ui_server_fastapi.py+++ b/tests/test_ui_server_fastapi.py@@ -90,7 +90,7 @@ def test_run_maybe_async_offloads_sync_handlers_without_losing_context():assert tick == "tick"-def test_wechat_qr_poll_marks_bind_hint_without_scheduling_send(monkeypatch):+def test_wechat_qr_poll_marks_bind_hint_and_schedules_managed_restart(monkeypatch):from vibe import runtimeclass _Auth:@@ -104,9 +104,15 @@ def test_wechat_qr_poll_marks_bind_hint_without_scheduling_send(monkeypatch):}bound_users = []+ restart_calls = []runtime.ensure_config()monkeypatch.setattr(ui_server, "_get_wechat_auth", lambda: _Auth())+ monkeypatch.setattr(+ ui_server,+ "_schedule_wechat_qr_login_restart",+ lambda: restart_calls.append(True) or {"job_id": "restart-1"},+ )monkeypatch.setattr("vibe.api.auto_bind_wechat_user",lambda user_id: bound_users.append(user_id)@@ -123,3 +129,4 @@ def test_wechat_qr_poll_marks_bind_hint_without_scheduling_send(monkeypatch):assert response.status_code == 200assert response.get_json()["status"] == "confirmed"assert bound_users == ["wx-user"]+ assert restart_calls == [True]diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.pyindex 59ffc1e0b..f62b868e6 100644--- a/tests/test_ui_show_pages.py+++ b/tests/test_ui_show_pages.py@@ -1,9 +1,51 @@+import asyncio+from config import pathsfrom core.show_pages import ShowPageStore, ensure_show_page_dir-from tests.test_ui_remote_access_auth import _remote_peer, _save_config+from core.show_runtime import ShowRuntimeManager, set_show_runtime_manager_for_tests+from tests.test_ui_remote_access_auth import _mock_interface, _remote_peer, _save_config+from vibe import remote_accessfrom vibe.ui_server import app+class _FakeShowRuntimeManager:+ def __init__(+ self,+ *,+ body: bytes = b"Runtime Show Page",+ fail: bool = False,+ status_code: int = 200,+ extra_headers: dict[str, str] | None = None,+ ):+ self.body = body+ self.fail = fail+ self.status_code = status_code+ self.extra_headers = extra_headers or {}+ self.calls = []+ self.websocket_paths = []+ self.stopped = False++ async def request(self, method, path, *, headers=None, body=None):+ import httpx++ self.calls.append((method, path, headers, body))+ if self.fail:+ raise RuntimeError("runtime unavailable")+ headers = {+ "content-type": "text/html; charset=utf-8",+ "set-cookie": "__Host-vibe_remote_session=attacker",+ "x-runtime-private-header": "secret",+ } | self.extra_headers+ return httpx.Response(self.status_code, content=self.body, headers=headers)++ async def websocket_url(self, path):+ self.websocket_paths.append(path)+ return f"ws://127.0.0.1:1{path}"++ def stop(self):+ self.stopped = True++def _create_show_page(session_id: str, visibility: str) -> str | None:page_dir = ensure_show_page_dir(session_id)(page_dir / "index.html").write_text("<!doctype html><title>Show</title><h1>Show Page</h1>", encoding="utf-8")@@ -43,6 +85,552 @@ def test_private_show_page_serves_locally(monkeypatch, tmp_path):assert b"Show Page" in response.content+def test_private_show_page_uses_runtime_when_available(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ _save_config(tmp_path)+ _create_show_page("ses123", "private")+ manager = _FakeShowRuntimeManager(body=b"<h1>Runtime Page</h1>")+ set_show_runtime_manager_for_tests(manager)+ try:+ response = app.test_client().get(+ "/show/ses123/",+ base_url="http://127.0.0.1:5123",+ headers={+ "Accept": "text/html",+ "Accept-Encoding": "br, zstd",+ "Authorization": "Bearer secret",+ "Cookie": "__Host-vibe_remote_session=secret",+ "X-Vibe-CSRF-Token": "secret",+ },+ )+ finally:+ set_show_runtime_manager_for_tests(None)++ assert response.status_code == 200+ assert b"Runtime Page" in response.content+ assert "__Host-vibe_remote_session=attacker" not in "\n".join(response.headers.getlist("set-cookie"))+ assert "x-runtime-private-header" not in response.headers+ assert response.headers["content-type"] == "text/html; charset=utf-8"+ assert manager.calls[0][0] == "GET"+ assert manager.calls[0][1] == "/sessions/ses123/app/"+ assert manager.calls[0][2]["accept"] == "text/html"+ assert "accept-encoding" not in manager.calls[0][2]+ assert "authorization" not in manager.calls[0][2]+ assert "cookie" not in manager.calls[0][2]+ assert "x-vibe-csrf-token" not in manager.calls[0][2]+++def test_private_show_page_falls_back_to_static_when_runtime_unavailable(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ _save_config(tmp_path)+ _create_show_page("ses123", "private")+ set_show_runtime_manager_for_tests(_FakeShowRuntimeManager(fail=True))+ try:+ response = app.test_client().get("/show/ses123/", base_url="http://127.0.0.1:5123")+ finally:+ set_show_runtime_manager_for_tests(None)++ assert response.status_code == 200+ assert b"Show Page" in response.content+++def test_private_show_page_api_does_not_fall_back_to_static(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ _save_config(tmp_path)+ _create_show_page("ses123", "private")+ (paths.get_show_pages_dir() / "ses123" / "api" / "health.ts").write_text("export const secret = true\n", encoding="utf-8")+ set_show_runtime_manager_for_tests(_FakeShowRuntimeManager(fail=True))+ try:+ response = app.test_client().get("/show/ses123/api/health.ts", base_url="http://127.0.0.1:5123")+ finally:+ set_show_runtime_manager_for_tests(None)++ assert response.status_code == 503+ assert response.get_json()["error"] == "show_runtime_unavailable"+ assert b"secret" not in response.content+++def test_private_show_page_proxies_runtime_api_methods(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ _save_config(tmp_path)+ _create_show_page("ses123", "private")+ manager = _FakeShowRuntimeManager(body=b'{"ok":true}', extra_headers={"content-type": "application/json"})+ set_show_runtime_manager_for_tests(manager)+ try:+ response = app.test_client().post(+ "/show/ses123/api/health",+ base_url="http://127.0.0.1:5123",+ headers={+ "Origin": "http://127.0.0.1:5123",+ "Content-Type": "application/json",+ "Cookie": "__Host-vibe_remote_session=secret",+ },+ content=b'{"ping":true}',+ )+ finally:+ set_show_runtime_manager_for_tests(None)++ assert response.status_code == 200+ assert response.content == b'{"ok":true}'+ assert manager.calls[0][0] == "POST"+ assert manager.calls[0][1] == "/sessions/ses123/app/api/health"+ assert manager.calls[0][2]["content-type"] == "application/json"+ assert "cookie" not in manager.calls[0][2]+ assert manager.calls[0][3] == b'{"ping":true}'+++def test_private_show_page_api_mutation_rejects_missing_origin(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ _save_config(tmp_path)+ _create_show_page("ses123", "private")+ manager = _FakeShowRuntimeManager(body=b'{"ok":true}', extra_headers={"content-type": "application/json"})+ set_show_runtime_manager_for_tests(manager)+ try:+ response = app.test_client().post(+ "/show/ses123/api/health",+ base_url="http://127.0.0.1:5123",+ headers={"Content-Type": "application/json"},+ content=b'{"ping":true}',+ )+ finally:+ set_show_runtime_manager_for_tests(None)++ assert response.status_code == 403+ assert response.get_json()["message"] == "Forbidden: missing origin header"+ assert manager.calls == []+++def test_private_show_page_api_mutation_rejects_cross_origin(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ _save_config(tmp_path)+ _create_show_page("ses123", "private")+ manager = _FakeShowRuntimeManager(body=b'{"ok":true}', extra_headers={"content-type": "application/json"})+ set_show_runtime_manager_for_tests(manager)+ try:+ response = app.test_client().post(+ "/show/ses123/api/health",+ base_url="http://127.0.0.1:5123",+ headers={+ "Origin": "http://evil.example",+ "Content-Type": "application/json",+ },+ content=b'{"ping":true}',+ )+ finally:+ set_show_runtime_manager_for_tests(None)++ assert response.status_code == 403+ assert response.get_json()["message"] == "Forbidden: invalid origin"+ assert manager.calls == []+++def test_private_show_page_preserves_runtime_redirect_location(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ _save_config(tmp_path)+ _create_show_page("ses123", "private")+ manager = _FakeShowRuntimeManager(+ body=b"",+ status_code=302,+ extra_headers={"location": "/sessions/ses123/app/foo/"},+ )+ set_show_runtime_manager_for_tests(manager)+ try:+ response = app.test_client().get(+ "/show/ses123/foo",+ base_url="http://127.0.0.1:5123",+ follow_redirects=False,+ )+ finally:+ set_show_runtime_manager_for_tests(None)++ assert response.status_code == 302+ assert response.headers["location"] == "/show/ses123/foo/"+ assert "__Host-vibe_remote_session=attacker" not in "\n".join(response.headers.getlist("set-cookie"))+++def test_private_show_page_rewrites_absolute_runtime_redirect_location(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ _save_config(tmp_path)+ _create_show_page("ses123", "private")+ manager = _FakeShowRuntimeManager(+ body=b"",+ status_code=302,+ extra_headers={"location": "http://127.0.0.1:49321/sessions/ses123/app/foo/?x=1#top"},+ )+ set_show_runtime_manager_for_tests(manager)+ try:+ response = app.test_client().get(+ "/show/ses123/foo",+ base_url="http://127.0.0.1:5123",+ follow_redirects=False,+ )+ finally:+ set_show_runtime_manager_for_tests(None)++ assert response.status_code == 302+ assert response.headers["location"] == "/show/ses123/foo/?x=1#top"+++def test_show_runtime_manager_reports_missing_command(tmp_path):+ manager = ShowRuntimeManager(+ command="definitely-missing-avibe-show-runtime",+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ )++ result = asyncio.run(manager.ensure())++ assert result.available is False+ assert result.reason == "runtime_command_missing"+++def test_show_runtime_manager_uses_managed_runtime_bin(tmp_path):+ runtime_dir = tmp_path / "runtime with spaces"+ bin_path = runtime_dir / "package" / "node_modules" / ".bin" / "avibe-show-runtime"+ bin_path.parent.mkdir(parents=True)+ bin_path.write_text("#!/bin/sh\n", encoding="utf-8")+ bin_path.chmod(0o755)++ manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=runtime_dir,+ auto_install=False,+ )++ assert asyncio.run(manager._resolve_managed_command()) == [str(bin_path)]+++def test_show_runtime_manager_can_disable_auto_install(tmp_path):+ manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ auto_install=False,+ )++ assert asyncio.run(manager._resolve_managed_command()) is None+ assert manager._install_reason == "runtime_command_missing"+++def test_show_runtime_manager_installs_without_blocking_event_loop(monkeypatch, tmp_path):+ manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ )++ def fake_install():+ bin_path = manager._managed_bin_path()+ bin_path.parent.mkdir(parents=True)+ bin_path.write_text("#!/bin/sh\n", encoding="utf-8")+ bin_path.chmod(0o755)+ return [str(bin_path)]++ monkeypatch.setattr(manager, "_install_managed_runtime", fake_install)+ calls = []++ async def fake_to_thread(func):+ calls.append(func)+ return func()++ monkeypatch.setattr("core.show_runtime.asyncio.to_thread", fake_to_thread)++ assert asyncio.run(manager._resolve_managed_command()) == [str(manager._managed_bin_path())]+ assert calls == [fake_install]+++def test_show_runtime_manager_installs_from_github_source(monkeypatch, tmp_path):+ runtime_dir = tmp_path / "runtime"+ source_dir = runtime_dir / "source" / "github" / "avibe-bot_vibe-show-runtime" / "main"+ commands = []++ manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=runtime_dir,+ runtime_source="github",+ github_repo="https://github.com/avibe-bot/vibe-show-runtime.git",+ github_ref="main",+ )++ monkeypatch.setattr(+ "core.show_runtime._resolve_command",+ lambda command: [f"/bin/{command}"] if command in {"git", "npm", "node"} else None,+ )++ def fake_run(command, *, cwd=None):+ commands.append((command, cwd))+ if command[:2] == ["/bin/npm", "run"]:+ cli_path = source_dir / "packages" / "runtime" / "dist" / "cli.js"+ cli_path.parent.mkdir(parents=True, exist_ok=True)+ cli_path.write_text("#!/usr/bin/env node\n", encoding="utf-8")+ return True++ monkeypatch.setattr(manager, "_run_install_command", fake_run)++ assert manager._install_managed_runtime() == ["/bin/node", str(source_dir / "packages" / "runtime" / "dist" / "cli.js")]+ assert commands == [+ (+ [+ "/bin/git",+ "clone",+ "--depth",+ "1",+ "--branch",+ "main",+ "https://github.com/avibe-bot/vibe-show-runtime.git",+ str(source_dir),+ ],+ None,+ ),+ (["/bin/npm", "ci"], source_dir),+ (["/bin/npm", "run", "build"], source_dir),+ ]+++def test_show_runtime_manager_reuses_installed_github_runtime_when_update_fails(monkeypatch, tmp_path):+ runtime_dir = tmp_path / "runtime"+ source_dir = runtime_dir / "source" / "github" / "avibe-bot_vibe-show-runtime" / "main"+ cli_path = source_dir / "packages" / "runtime" / "dist" / "cli.js"+ cli_path.parent.mkdir(parents=True)+ cli_path.write_text("#!/usr/bin/env node\n", encoding="utf-8")+ commands = []++ manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=runtime_dir,+ runtime_source="github",+ github_repo="https://github.com/avibe-bot/vibe-show-runtime.git",+ github_ref="main",+ )++ monkeypatch.setattr(+ "core.show_runtime._resolve_command",+ lambda command: [f"/bin/{command}"] if command in {"git", "npm", "node"} else None,+ )++ def fake_run(command, *, cwd=None):+ commands.append((command, cwd))+ return False++ monkeypatch.setattr(manager, "_run_install_command", fake_run)++ assert manager._install_managed_runtime() == ["/bin/node", str(cli_path)]+ assert manager._install_reason is None+ assert commands == [+ (+ ["/bin/git", "-C", str(source_dir), "fetch", "--depth", "1", "origin", "main"],+ None,+ )+ ]+++def test_show_runtime_manager_reuses_installed_github_runtime_without_git(monkeypatch, tmp_path):+ runtime_dir = tmp_path / "runtime"+ source_dir = runtime_dir / "source" / "github" / "avibe-bot_vibe-show-runtime" / "main"+ cli_path = source_dir / "packages" / "runtime" / "dist" / "cli.js"+ cli_path.parent.mkdir(parents=True)+ cli_path.write_text("#!/usr/bin/env node\n", encoding="utf-8")++ manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=runtime_dir,+ runtime_source="github",+ github_repo="https://github.com/avibe-bot/vibe-show-runtime.git",+ github_ref="main",+ )++ monkeypatch.setattr(+ "core.show_runtime._resolve_command",+ lambda command: ["/bin/node"] if command == "node" else None,+ )++ assert manager._install_managed_runtime() == ["/bin/node", str(cli_path)]+ assert manager._install_reason is None+++def test_show_runtime_manager_reuses_github_runtime_after_install_attempt(monkeypatch, tmp_path):+ runtime_dir = tmp_path / "runtime"+ source_dir = runtime_dir / "source" / "github" / "avibe-bot_vibe-show-runtime" / "main"+ cli_path = source_dir / "packages" / "runtime" / "dist" / "cli.js"+ cli_path.parent.mkdir(parents=True)+ cli_path.write_text("#!/usr/bin/env node\n", encoding="utf-8")++ manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=runtime_dir,+ runtime_source="github",+ github_repo="https://github.com/avibe-bot/vibe-show-runtime.git",+ github_ref="main",+ )+ manager._install_attempted = True++ monkeypatch.setattr(+ "core.show_runtime._resolve_command",+ lambda command: ["/bin/node"] if command == "node" else None,+ )++ assert asyncio.run(manager._resolve_managed_command()) == ["/bin/node", str(cli_path)]+ assert manager._managed_command == ["/bin/node", str(cli_path)]+++def test_show_runtime_manager_reuses_cached_managed_command_after_install_attempt(monkeypatch, tmp_path):+ manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ runtime_source="github",+ )+ manager._install_attempted = True+ manager._managed_command = ["/bin/node", "/tmp/runtime/cli.js"]+ monkeypatch.setattr("core.show_runtime._resolve_command", lambda command: None)++ assert asyncio.run(manager._resolve_managed_command()) == ["/bin/node", "/tmp/runtime/cli.js"]+++def test_show_runtime_manager_can_use_npm_source(monkeypatch, tmp_path):+ manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ runtime_source="npm",+ )+ called = []+ monkeypatch.setattr(manager, "_install_npm_runtime", lambda: called.append("npm") or ["/tmp/avibe-show-runtime"])++ assert manager._install_managed_runtime() == ["/tmp/avibe-show-runtime"]+ assert called == ["npm"]+++def test_show_runtime_shutdown_stops_manager():+ from vibe.ui_server import stop_show_runtime_on_shutdown++ manager = _FakeShowRuntimeManager()+ set_show_runtime_manager_for_tests(manager)+ try:+ stop_show_runtime_on_shutdown()+ finally:+ set_show_runtime_manager_for_tests(None)++ assert manager.stopped is True+++def test_private_show_page_hmr_websocket_requires_private_page(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ _save_config(tmp_path)+ _create_show_page("ses123", "offline")++ try:+ with app.test_client().websocket_connect(+ "/show/ses123/__vite_hmr",+ headers={"host": "127.0.0.1:5123"},+ subprotocols=["vite-hmr"],+ ):+ raise AssertionError("websocket should not connect")+ except Exception as exc:+ assert getattr(exc, "code", None) == 1008+++def test_private_show_page_hmr_websocket_requires_remote_session(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ _save_config(tmp_path)+ _create_show_page("ses123", "private")++ try:+ with app.test_client().websocket_connect(+ "wss://alex.avibe.bot/show/ses123/__vite_hmr",+ headers={"host": "alex.avibe.bot"},+ subprotocols=["vite-hmr"],+ ):+ raise AssertionError("websocket should not connect")+ except Exception as exc:+ assert getattr(exc, "code", None) == 1008+++def test_private_show_page_hmr_websocket_accepts_remote_session(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ config = _save_config(tmp_path)+ _create_show_page("ses123", "private")+ manager = _FakeShowRuntimeManager()+ set_show_runtime_manager_for_tests(manager)+ client = app.test_client()+ client.set_cookie(+ remote_access.SESSION_COOKIE_NAME,+ remote_access.make_session_cookie(config, "[email protected]", "user-1"),+ domain="alex.avibe.bot",+ )+ try:+ with client.websocket_connect(+ "wss://alex.avibe.bot/show/ses123/__vite_hmr",+ headers={"host": "alex.avibe.bot"},+ subprotocols=["vite-hmr"],+ ) as websocket:+ websocket.receive_text()+ except Exception as exc:+ assert getattr(exc, "code", None) == 1011+ finally:+ set_show_runtime_manager_for_tests(None)+++def test_private_show_page_hmr_websocket_accepts_setup_host_local_peer(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ config = _save_config(tmp_path)+ config.ui.setup_host = "192.168.2.3"+ config.save()+ _mock_interface(monkeypatch, "192.168.2.3", 24)+ _create_show_page("ses123", "private")+ manager = _FakeShowRuntimeManager()+ set_show_runtime_manager_for_tests(manager)+ try:+ with app.test_client().websocket_connect(+ "/show/ses123/__vite_hmr",+ headers={+ "host": "192.168.2.3:5123",+ "x-vibe-test-remote-addr": "192.168.2.44",+ },+ subprotocols=["vite-hmr"],+ ) as websocket:+ websocket.receive_text()+ except Exception as exc:+ assert getattr(exc, "code", None) == 1011+ finally:+ set_show_runtime_manager_for_tests(None)++ assert manager.websocket_paths == ["/show/ses123/__vite_hmr"]+++def test_public_show_page_hmr_websocket_uses_share_path(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ _save_config(tmp_path)+ share_id = _create_show_page("ses123", "public")+ manager = _FakeShowRuntimeManager()+ set_show_runtime_manager_for_tests(manager)+ try:+ with app.test_client().websocket_connect(+ f"wss://alex.avibe.bot/p/{share_id}/__vite_hmr?token=test-token",+ headers={"host": "alex.avibe.bot"},+ subprotocols=["vite-hmr"],+ ) as websocket:+ websocket.receive_text()+ except Exception as exc:+ assert getattr(exc, "code", None) == 1011+ finally:+ set_show_runtime_manager_for_tests(None)++ assert manager.websocket_paths == [f"/p/{share_id}/__vite_hmr?token=test-token"]+++def test_public_show_page_hmr_websocket_requires_public_page(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ _save_config(tmp_path)+ share_id = _create_show_page("ses123", "private")++ try:+ with app.test_client().websocket_connect(+ f"wss://alex.avibe.bot/p/{share_id}/__vite_hmr",+ headers={"host": "alex.avibe.bot"},+ subprotocols=["vite-hmr"],+ ):+ raise AssertionError("websocket should not connect")+ except Exception as exc:+ assert getattr(exc, "code", None) == 1008++def test_private_show_page_redirects_without_trailing_slash(monkeypatch, tmp_path):monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))_save_config(tmp_path)@@ -62,26 +650,151 @@ def test_public_show_page_skips_remote_login_but_requires_public_host(monkeypatcmonkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))_save_config(tmp_path)share_id = _create_show_page("ses123", "public")+ set_show_runtime_manager_for_tests(_FakeShowRuntimeManager(fail=True))- response = app.test_client().get(- f"/p/{share_id}/",- base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),- follow_redirects=False,- )+ try:+ response = app.test_client().get(+ f"/p/{share_id}/",+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ follow_redirects=False,+ )++ assert response.status_code == 200+ assert b"Show Page" in response.content++ mismatch = app.test_client().get(+ f"/p/{share_id}/",+ base_url="https://evil.example",+ environ_base=_remote_peer(),+ follow_redirects=False,+ )+ finally:+ set_show_runtime_manager_for_tests(None)++ assert mismatch.status_code == 503+ assert mismatch.get_json()["error"] == "remote_access_host_mismatch"+++def test_public_show_page_uses_runtime_when_available(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ _save_config(tmp_path)+ share_id = _create_show_page("ses123", "public")+ manager = _FakeShowRuntimeManager(body=b"<h1>Public Runtime Page</h1>")+ set_show_runtime_manager_for_tests(manager)+ try:+ response = app.test_client().get(+ f"/p/{share_id}/",+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ )+ finally:+ set_show_runtime_manager_for_tests(None)assert response.status_code == 200- assert b"Show Page" in response.content+ assert b"Public Runtime Page" in response.content+ assert manager.calls[0][0] == "GET"+ assert manager.calls[0][1] == "/sessions/ses123/app/"+ assert manager.calls[0][2]["x-vibe-show-base"] == f"/p/{share_id}/"- mismatch = app.test_client().get(- f"/p/{share_id}/",- base_url="https://evil.example",- environ_base=_remote_peer(),- follow_redirects=False,++def test_public_show_page_rewrites_runtime_redirect_location(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ _save_config(tmp_path)+ share_id = _create_show_page("ses123", "public")+ manager = _FakeShowRuntimeManager(+ body=b"",+ status_code=302,+ extra_headers={"location": "/sessions/ses123/app/foo/"},)+ set_show_runtime_manager_for_tests(manager)+ try:+ response = app.test_client().get(+ f"/p/{share_id}/foo",+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ follow_redirects=False,+ )+ finally:+ set_show_runtime_manager_for_tests(None)- assert mismatch.status_code == 503- assert mismatch.get_json()["error"] == "remote_access_host_mismatch"+ assert response.status_code == 302+ assert response.headers["location"] == f"/p/{share_id}/foo/"+++def test_public_show_page_proxies_runtime_api_methods(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ _save_config(tmp_path)+ share_id = _create_show_page("ses123", "public")+ manager = _FakeShowRuntimeManager(body=b'{"ok":true}', extra_headers={"content-type": "application/json"})+ set_show_runtime_manager_for_tests(manager)+ try:+ response = app.test_client().post(+ f"/p/{share_id}/api/health",+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ headers={+ "Origin": "https://alex.avibe.bot",+ "Content-Type": "application/json",+ },+ content=b'{"ping":true}',+ )+ finally:+ set_show_runtime_manager_for_tests(None)++ assert response.status_code == 200+ assert response.content == b'{"ok":true}'+ assert manager.calls[0][0] == "POST"+ assert manager.calls[0][1] == "/sessions/ses123/app/api/health"+ assert manager.calls[0][2]["content-type"] == "application/json"+ assert manager.calls[0][2]["x-vibe-show-base"] == f"/p/{share_id}/"+ assert "cookie" not in manager.calls[0][2]+ assert manager.calls[0][3] == b'{"ping":true}'+++def test_public_show_page_api_mutation_rejects_cross_origin(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ _save_config(tmp_path)+ share_id = _create_show_page("ses123", "public")+ manager = _FakeShowRuntimeManager(body=b'{"ok":true}', extra_headers={"content-type": "application/json"})+ set_show_runtime_manager_for_tests(manager)+ try:+ response = app.test_client().post(+ f"/p/{share_id}/api/health",+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ headers={+ "Origin": "https://evil.example",+ "Content-Type": "application/json",+ },+ content=b'{"ping":true}',+ )+ finally:+ set_show_runtime_manager_for_tests(None)++ assert response.status_code == 403+ assert response.get_json()["message"] == "Forbidden: invalid origin"+ assert manager.calls == []+++def test_public_show_page_api_does_not_fall_back_to_static(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ _save_config(tmp_path)+ share_id = _create_show_page("ses123", "public")+ (paths.get_show_pages_dir() / "ses123" / "api" / "health.ts").write_text("export const secret = true\n", encoding="utf-8")+ set_show_runtime_manager_for_tests(_FakeShowRuntimeManager(fail=True))+ try:+ response = app.test_client().get(+ f"/p/{share_id}/api/health.ts",+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ )+ finally:+ set_show_runtime_manager_for_tests(None)++ assert response.status_code == 503+ assert response.get_json()["error"] == "show_runtime_unavailable"+ assert b"secret" not in response.contentdef test_public_show_page_redirects_without_trailing_slash(monkeypatch, tmp_path):diff --git a/vibe/cli.py b/vibe/cli.pyindex a942c372a..dabdbd3a0 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -503,12 +503,13 @@ def _show_examples_text() -> str:def _show_path_examples_text() -> str:return dedent("""\- Returns the directory where the agent should write index.html and related static assets.- The directory is created if needed. On first creation, Vibe Remote writes a default index.html.+ Returns the directory where the agent should write a React/Vite Show Page.+ The directory is created if needed. On first creation, Vibe Remote writes src/App.tsx,+ src/styles.css, index.html, and a sample api/health.ts handler.First-run workflow:1. Run: vibe show path --session-id sesk8m4q2p7x- 2. Write or update index.html in the returned path.+ 2. Write or update src/App.tsx in the returned path.3. Share the active URL if the command output includes one.4. Run `vibe show update --visibility public` only when the user asks for a shareable public link."""@@ -3919,7 +3920,7 @@ def _show_page_next_actions(payload: dict) -> list[str]:actions.append("No active URL is available right now.")actions.append("Treat the Show Page as the primary collaboration surface; put meaningful updates there first.")actions.append("Use visual thinking: diagrams, timelines, maps, comparisons, dashboards, or small prototypes when they help.")- actions.append("To update the page later, edit the same directory and refresh.")+ actions.append("To update the page later, edit src/App.tsx or api/*.ts; the private page hot-reloads when open.")actions.append("For more options, run: vibe show --help")return actions@@ -3955,7 +3956,7 @@ def _print_show_page_status_missing(session_id: str) -> None:print("")print("Use it:")print(f" - Create the workspace with: vibe show path --session-id {session_id}")- print(" - Then edit index.html in the returned directory.")+ print(" - Then edit src/App.tsx in the returned directory.")print(" - For more options, run: vibe show --help")diff --git a/vibe/ui_compat.py b/vibe/ui_compat.pyindex ebadbf963..a9b4f3387 100644--- a/vibe/ui_compat.py+++ b/vibe/ui_compat.py@@ -328,6 +328,13 @@ class CompatApp(FastAPI):self._after_request_handlers: list[Callable[..., Any]] = []self._error_handlers: list[tuple[type[BaseException], Callable[..., Any]]] = []+ def add_event_handler(self, event_type: str, func: Callable[..., Any]) -> None:+ handler = getattr(super(), "add_event_handler", None)+ if callable(handler):+ handler(event_type, func)+ return+ self.router.add_event_handler(event_type, func)+def route(self,path: str,diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 98e149397..133a51c38 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -1,4 +1,5 @@import base64+import asyncioimport hashlibimport hmacimport ipaddress@@ -20,9 +21,11 @@ from typing import Any, Callablefrom urllib.parse import parse_qsl, quote, unquote, urlencode, urlparse, urlsplit, urlunsplitimport psutil-from fastapi import WebSocket, WebSocketDisconnect+from aiohttp import ClientSession, WSMsgType+from fastapi import Request as FastAPIRequest, WebSocket, WebSocketDisconnect+from fastapi.responses import Response as FastAPIResponse-from vibe.ui_compat import CompatApp, Response, g, jsonify, redirect, request, send_file+from vibe.ui_compat import CompatApp, Response, TEST_REMOTE_ADDR_HEADER, g, jsonify, redirect, request, send_filefrom config import pathsfrom config.v2_config import CONFIG_LOCK, V2Config@@ -36,6 +39,32 @@ app = CompatApp(title="Vibe Remote UI", docs_url=None, redoc_url=None, openapi_u# Global server instance for graceful shutdown on reload_server = None+_SHOW_RUNTIME_REQUEST_HEADER_ALLOWLIST = {+ "accept",+ "accept-language",+ "cache-control",+ "content-type",+ "if-modified-since",+ "if-none-match",+ "pragma",+ "range",+ "user-agent",+}+_SHOW_RUNTIME_RESPONSE_HEADER_ALLOWLIST = {+ "accept-ranges",+ "cache-control",+ "content-disposition",+ "content-language",+ "content-range",+ "content-type",+ "etag",+ "expires",+ "last-modified",+ "location",+ "sourcemap",+ "vary",+ "x-sourcemap",+}STRUCTURED_LOG_PATTERN = re.compile(r"^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3})\s+-\s+([\w.]+)\s+-\s+(\w+)\s+-\s+(.*)$")LEVEL_HINT_PATTERN = re.compile(r"\b(DEBUG|INFO|WARNING|ERROR|CRITICAL)\b")@@ -170,6 +199,10 @@ def _is_mutation_guard_exempt() -> bool:)+def _is_show_api_mutation() -> bool:+ return (request.path.startswith("/show/") or request.path.startswith("/p/")) and "/api/" in request.path++def _ensure_csrf_cookie(response: Response) -> Response:if response.headers.getlist("Set-Cookie"):for cookie_header in response.headers.getlist("Set-Cookie"):@@ -1068,6 +1101,9 @@ def protect_mutating_ui_requests():if source != _current_origin():return jsonify({"ok": False, "message": "Forbidden: invalid origin"}), 403+ if _is_show_api_mutation():+ return None+csrf_cookie = request.cookies.get(CSRF_COOKIE_NAME, "")csrf_header = request.headers.get(CSRF_HEADER_NAME, "")if not csrf_cookie or not csrf_header or not hmac.compare_digest(csrf_cookie, csrf_header):@@ -1260,6 +1296,248 @@ async def websocket_echo(websocket: WebSocket):return[email protected]("/show/{session_id}/__vite_hmr")+async def show_runtime_hmr_websocket(websocket: WebSocket, session_id: str):+ from core.show_pages import ShowPageStore++ if not _show_runtime_websocket_authorized(websocket):+ await websocket.close(code=1008)+ return++ store = ShowPageStore()+ try:+ page = store.get(session_id)+ if page is None or page.visibility != "private":+ await websocket.close(code=1008)+ return+ finally:+ store.close()++ await websocket.accept(subprotocol="vite-hmr")+ try:+ await _proxy_show_runtime_websocket(websocket, session_id)+ except Exception:+ logger.debug("Show runtime HMR websocket unavailable", exc_info=True)+ await websocket.close(code=1011)++[email protected]("/p/{share_id}/__vite_hmr")+async def public_show_runtime_hmr_websocket(websocket: WebSocket, share_id: str):+ from core.show_pages import ShowPageStore++ store = ShowPageStore()+ try:+ page = store.get_by_share_id(share_id)+ if page is None or page.visibility != "public":+ await websocket.close(code=1008)+ return+ session_id = page.session_id+ finally:+ store.close()++ await websocket.accept(subprotocol="vite-hmr")+ try:+ await _proxy_show_runtime_websocket(+ websocket,+ session_id,+ external_prefix=f"/p/{quote(share_id, safe='')}",+ )+ except Exception:+ logger.debug("Public show runtime HMR websocket unavailable", exc_info=True)+ await websocket.close(code=1011)+++def _show_runtime_websocket_authorized(websocket: WebSocket) -> bool:+ config = _load_remote_access_config()+ if config is None:+ return _websocket_is_local_request(websocket)+ if _websocket_is_local_request(websocket, config):+ return True+ if _websocket_normalized_host(websocket) != _remote_access_public_host(config):+ return False+ from vibe import remote_access++ if not config.remote_access.vibe_cloud.enabled or not config.remote_access.vibe_cloud.session_secret:+ return False+ return remote_access.parse_session_cookie(+ config,+ websocket.cookies.get(remote_access.SESSION_COOKIE_NAME),+ ) is not None+++def _websocket_is_local_request(websocket: WebSocket, config: V2Config | None = None) -> bool:+ if _websocket_has_forwarded_metadata(websocket):+ return False+ client_host = _websocket_client_host(websocket)+ if client_host == "testclient":+ return _is_loopback_host(websocket.headers.get("host"))+ try:+ client_address = ipaddress.ip_address(client_host)+ except ValueError:+ client_address = None+ if client_address is not None and client_address.is_loopback and _is_loopback_host(websocket.headers.get("host")):+ return True+ return _websocket_is_setup_host_request(websocket, config)+++def _websocket_has_forwarded_metadata(websocket: WebSocket) -> bool:+ forwarded_headers = (+ "Forwarded",+ "X-Forwarded-For",+ "X-Forwarded-Host",+ "X-Forwarded-Proto",+ "X-Forwarded-Port",+ "X-Real-IP",+ "X-Original-Forwarded-For",+ "True-Client-IP",+ "CF-Connecting-IP",+ "CF-Ray",+ "CF-Visitor",+ "CF-IPCountry",+ )+ return any(websocket.headers.get(header) for header in forwarded_headers)+++def _websocket_client_host(websocket: WebSocket) -> str:+ client_host = websocket.client.host if websocket.client else ""+ if client_host == "testclient":+ return websocket.headers.get(TEST_REMOTE_ADDR_HEADER) or client_host+ return client_host+++def _websocket_peer_address(websocket: WebSocket) -> ipaddress._BaseAddress | None:+ client_host = _websocket_client_host(websocket).strip()+ if not client_host or client_host in {"localhost", "testclient"}:+ return None+ try:+ address = ipaddress.ip_address(client_host)+ except ValueError:+ return None+ mapped = getattr(address, "ipv4_mapped", None)+ return mapped or address+++def _websocket_is_private_peer(websocket: WebSocket) -> bool:+ address = _websocket_peer_address(websocket)+ return address is not None and _is_private_address(address)+++def _websocket_peer_shares_setup_host_network(websocket: WebSocket, setup_address: ipaddress._BaseAddress) -> bool:+ peer = _websocket_peer_address(websocket)+ if peer is None:+ return False+ if peer.version != setup_address.version:+ mapped = getattr(peer, "ipv4_mapped", None)+ if mapped is None or mapped.version != setup_address.version:+ return False+ peer = mapped+ network = _setup_host_trust_network(setup_address)+ if network is None:+ return False+ return peer in network+++def _websocket_is_wildcard_setup_host_request(websocket: WebSocket, config: V2Config | None) -> bool:+ if config is None:+ return False+ setup_host = _normalized_host(getattr(config.ui, "setup_host", ""))+ if not _is_wildcard_setup_host(setup_host):+ return False+ if _websocket_has_forwarded_metadata(websocket):+ return False++ try:+ host_address = ipaddress.ip_address(_websocket_normalized_host(websocket))+ except ValueError:+ return False+ if host_address.is_unspecified:+ return False+ if not _is_private_address(host_address):+ return False+ if _local_interface_network(host_address, interface_filter=_allows_wildcard_setup_host_trust) is None:+ return False+ if not _websocket_is_private_peer(websocket):+ return False+ if _is_tailscale_overlay_address(host_address):+ peer_address = _websocket_peer_address(websocket)+ return peer_address is not None and _is_trusted_tailscale_peer(peer_address)+ return _websocket_peer_shares_setup_host_network(websocket, host_address)+++def _websocket_is_setup_host_request(websocket: WebSocket, config: V2Config | None) -> bool:+ if config is None:+ return False+ setup_host = _normalized_host(getattr(config.ui, "setup_host", ""))+ if not setup_host:+ return False+ if _is_wildcard_setup_host(setup_host):+ return _websocket_is_wildcard_setup_host_request(websocket, config)+ if _is_loopback_host(setup_host):+ return False+ try:+ setup_address = ipaddress.ip_address(setup_host)+ except ValueError:+ return False+ if not _is_private_address(setup_address):+ return False+ if _websocket_normalized_host(websocket) != setup_host:+ return False+ if _websocket_has_forwarded_metadata(websocket):+ return False+ if not _websocket_is_private_peer(websocket):+ return False+ if _is_tunnel_wildcard_bind(config):+ return _websocket_peer_shares_setup_host_network(websocket, setup_address)+ return True+++def _websocket_normalized_host(websocket: WebSocket) -> str:+ return _normalized_host(websocket.headers.get("x-forwarded-host") or websocket.headers.get("host"))+++async def _proxy_show_runtime_websocket(+ websocket: WebSocket,+ session_id: str,+ *,+ external_prefix: str | None = None,+) -> None:+ from core.show_runtime import get_show_runtime_manager++ if external_prefix is None:+ external_prefix = f"/show/{quote(session_id, safe='')}"+ runtime_path = f"{external_prefix.rstrip('/')}/__vite_hmr"+ if websocket.url.query:+ runtime_path = f"{runtime_path}?{websocket.url.query}"+ upstream_url = await get_show_runtime_manager().websocket_url(runtime_path)+ async with ClientSession() as session:+ async with session.ws_connect(upstream_url, protocols=["vite-hmr"], autoping=True) as upstream:+ async def client_to_upstream():+ try:+ while True:+ message = await websocket.receive()+ if message["type"] == "websocket.disconnect":+ await upstream.close()+ return+ if "text" in message:+ await upstream.send_str(message["text"])+ elif "bytes" in message:+ await upstream.send_bytes(message["bytes"])+ except WebSocketDisconnect:+ await upstream.close()++ async def upstream_to_client():+ async for message in upstream:+ if message.type == WSMsgType.TEXT:+ await websocket.send_text(message.data)+ elif message.type == WSMsgType.BINARY:+ await websocket.send_bytes(message.data)+ elif message.type in {WSMsgType.CLOSE, WSMsgType.CLOSED, WSMsgType.ERROR}:+ await websocket.close()+ return++ await asyncio.gather(client_to_upstream(), upstream_to_client())++@app.route("/doctor", methods=["GET"])def doctor_get():payload = {}@@ -1843,6 +2121,13 @@ def _get_wechat_auth():return _wechat_auth_manager+def _schedule_wechat_qr_login_restart() -> dict:+ """Schedule a managed restart after QR-login credentials are persisted."""+ from vibe.restart_supervisor import schedule_restart++ return schedule_restart(delay_seconds=2.0, trigger="wechat-qr-login")++@app.route("/wechat/qr_login/start", methods=["POST"])async def wechat_qr_login_start():"""Start WeChat QR code login flow."""@@ -1881,25 +2166,11 @@ async def wechat_qr_login_poll():except Exception as e:logger.warning("Failed to auto-bind WeChat user: %s", e)- # Schedule service restart so the new token takes effect- def _restart_after_login():- import time-- time.sleep(2) # let the response go out first- try:- from vibe import runtime-- runtime.stop_service()- time.sleep(1)- runtime.ensure_config()- service_pid = runtime.start_service()- st = runtime.read_status()- runtime.write_status("running", "restarted", service_pid, st.get("ui_pid"))- logger.info("Service restarted after WeChat QR login")- except Exception as exc:- logger.warning("Failed to restart service after QR login: %s", exc)-- threading.Thread(target=_restart_after_login, daemon=True).start()+ try:+ restart = _schedule_wechat_qr_login_restart()+ logger.info("Scheduled service restart after WeChat QR login: %s", restart.get("job_id"))+ except Exception as exc:+ logger.warning("Failed to schedule service restart after WeChat QR login: %s", exc)return jsonify(result)@@ -3199,6 +3470,15 @@ def _show_page_not_found_response():return jsonify({"error": "not_found"}), 404+def _show_page_runtime_unavailable_response():+ return jsonify({"error": "show_runtime_unavailable"}), 503+++def _is_show_api_asset(asset_path: str) -> bool:+ relative = (asset_path or "").strip("/")+ return relative == "api" or relative.startswith("api/")++def _show_page_file_response(root: Path, asset_path: str):relative = (asset_path or "").strip("/")if not relative:@@ -3216,6 +3496,75 @@ def _show_page_file_response(root: Path, asset_path: str):return response+async def _show_page_runtime_response(+ session_id: str,+ asset_path: str,+ starlette_request: FastAPIRequest,+ *,+ external_prefix: str | None = None,+):+ from core.show_runtime import get_show_runtime_manager++ session_part = quote(session_id, safe="")+ asset_part = quote(asset_path.lstrip("/"), safe="/@:-._~")+ runtime_path = f"/sessions/{session_part}/app/"+ if asset_part:+ runtime_path = f"{runtime_path}{asset_part}"+ if starlette_request.url.query:+ runtime_path = f"{runtime_path}?{starlette_request.url.query}"+ forwarded_headers = {+ key: value+ for key, value in starlette_request.headers.items()+ if key.lower() in _SHOW_RUNTIME_REQUEST_HEADER_ALLOWLIST+ }+ if external_prefix:+ forwarded_headers["x-vibe-show-base"] = f"{external_prefix.rstrip('/')}/"+ body = await starlette_request.body()+ proxied = await get_show_runtime_manager().request(+ starlette_request.method,+ runtime_path,+ headers=forwarded_headers,+ body=body or None,+ )+ response_headers = {+ key: value+ for key, value in proxied.headers.items()+ if key.lower() in _SHOW_RUNTIME_RESPONSE_HEADER_ALLOWLIST+ }+ if location := response_headers.get("location"):+ response_headers["location"] = _rewrite_show_runtime_location(+ session_id,+ location,+ external_prefix=external_prefix,+ )+ response_headers["X-Content-Type-Options"] = "nosniff"+ response_headers["Referrer-Policy"] = "no-referrer"+ return FastAPIResponse(content=proxied.content, status_code=proxied.status_code, headers=response_headers)+++def _rewrite_show_runtime_location(session_id: str, location: str, *, external_prefix: str | None = None) -> str:+ parsed = urlsplit(location)+ internal_prefix = f"/sessions/{quote(session_id, safe='')}/app"+ external_prefix = (external_prefix or f"/show/{quote(session_id, safe='')}").rstrip("/")+ if parsed.path == internal_prefix:+ public_path = f"{external_prefix}/"+ elif parsed.path.startswith(f"{internal_prefix}/"):+ suffix = parsed.path[len(internal_prefix) :].lstrip("/")+ public_path = f"{external_prefix}/{suffix}"+ else:+ return location+ return urlunsplit(("", "", public_path, parsed.query, parsed.fragment))+++def stop_show_runtime_on_shutdown() -> None:+ from core.show_runtime import stop_show_runtime_manager++ stop_show_runtime_manager()+++app.add_event_handler("shutdown", stop_show_runtime_on_shutdown)++@app.route("/show/<session_id>")def redirect_private_show_page_to_canonical_path(session_id):from core.show_pages import ShowPageStore@@ -3233,8 +3582,16 @@ def redirect_private_show_page_to_canonical_path(session_id):@app.route("/show/<session_id>/", defaults={"asset_path": ""})[email protected]("/show/<session_id>/<path:asset_path>")-def serve_private_show_page(session_id, asset_path):+ "/show/<session_id>/",+ defaults={"asset_path": ""},+ methods=["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],+)+ "/show/<session_id>/<path:asset_path>",+ methods=["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],+)+async def serve_private_show_page(session_id, asset_path):from core.show_pages import ShowPageStore, show_page_dirstore = ShowPageStore()@@ -3246,6 +3603,14 @@ def serve_private_show_page(session_id, asset_path):return _show_page_offline_response()if page.visibility != "private":return _show_page_not_found_response()+ if request.method in {"GET", "HEAD"} or _is_show_api_asset(asset_path):+ try:+ starlette_request = request._request+ return await _show_page_runtime_response(page.session_id, asset_path, starlette_request)+ except Exception:+ if _is_show_api_asset(asset_path):+ return _show_page_runtime_unavailable_response()+ logger.debug("Show runtime unavailable; serving static Show Page", exc_info=True)return _show_page_file_response(show_page_dir(page.session_id), asset_path)finally:store.close()@@ -3267,9 +3632,16 @@ def redirect_public_show_page_to_canonical_path(share_id):store.close()[email protected]("/p/<share_id>/", defaults={"asset_path": ""})[email protected]("/p/<share_id>/<path:asset_path>")-def serve_public_show_page(share_id, asset_path):+ "/p/<share_id>/",+ defaults={"asset_path": ""},+ methods=["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],+)+ "/p/<share_id>/<path:asset_path>",+ methods=["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],+)+async def serve_public_show_page(share_id, asset_path):from core.show_pages import ShowPageStore, show_page_dirstore = ShowPageStore()@@ -3281,6 +3653,19 @@ def serve_public_show_page(share_id, asset_path):return _show_page_offline_response()if page.visibility != "public":return _show_page_not_found_response()+ if request.method in {"GET", "HEAD"} or _is_show_api_asset(asset_path):+ try:+ starlette_request = request._request+ return await _show_page_runtime_response(+ page.session_id,+ asset_path,+ starlette_request,+ external_prefix=f"/p/{quote(share_id, safe='')}",+ )+ except Exception:+ if _is_show_api_asset(asset_path):+ return _show_page_runtime_unavailable_response()+ logger.debug("Show runtime unavailable; serving static public Show Page", exc_info=True)return _show_page_file_response(show_page_dir(page.session_id), asset_path)finally:store.close()