Skip to content

armgit / avibe

Public Imported from GitHub
0

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

feat(show): prewarm runtime sessions (#446)

Call Whitef9eeead6c29b
diff --git a/core/show_runtime.py b/core/show_runtime.py
index 999bd95f0..e1b8e6518 100644
--- a/core/show_runtime.py
+++ b/core/show_runtime.py
@@ -183,6 +183,18 @@ class ShowRuntimeManager:
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 prewarm_session(self, session_id: str, *, base_path: str | None = None) -> ShowRuntimeResult:
+ session_part = urllib.parse.quote(session_id, safe="")
+ runtime_path = f"/sessions/{session_part}/app/"
+ headers = {"x-vibe-show-base": base_path} if base_path else None
+ try:
+ response = await self.request("GET", runtime_path, headers=headers)
+ if response.status_code >= 500:
+ return ShowRuntimeResult(False, reason=f"session_prewarm_failed:{response.status_code}")
+ return ShowRuntimeResult(True, self._base_url)
+ except Exception as exc:
+ return ShowRuntimeResult(False, reason=f"session_prewarm_failed:{exc}")
+
async def websocket_url(self, path: str) -> str:
ready = await self.ensure()
if not ready.available or not ready.base_url:
@@ -347,29 +359,39 @@ class ShowRuntimeManager:
removed.append(str(path))
versions_dir = self.runtime_dir / "versions"
if versions_dir.is_dir():
- current_version_dir: Path | None = None
+ current_install_dir: Path | None = None
try:
pointer = json.loads((self.runtime_dir / "current.json").read_text(encoding="utf-8"))
- current_install_dir = Path(str(pointer.get("install_dir") or "")).resolve()
- if versions_dir.resolve() in current_install_dir.parents:
- current_version_dir = current_install_dir.relative_to(versions_dir.resolve()).parts[0]
- current_version_dir = versions_dir / current_version_dir
+ pointer_install_dir = Path(str(pointer.get("install_dir") or "")).resolve()
+ if versions_dir.resolve() in pointer_install_dir.parents:
+ current_install_dir = pointer_install_dir
except Exception:
- current_version_dir = None
- version_dirs = sorted(
- (path for path in versions_dir.iterdir() if path.is_dir()),
- key=lambda path: path.stat().st_mtime,
- reverse=True,
- )
+ current_install_dir = None
+ install_dirs = {
+ path.parent
+ for pattern in ("*/*/.vibe-show-runtime.json", "*/*/*/.vibe-show-runtime.json")
+ for path in versions_dir.glob(pattern)
+ if path.parent.is_dir()
+ }
+ sorted_install_dirs = sorted(install_dirs, key=lambda path: path.stat().st_mtime, reverse=True)
kept_previous = 0
- for path in version_dirs:
- if current_version_dir is not None and path.resolve() == current_version_dir.resolve():
+ for path in sorted_install_dirs:
+ path_resolved = path.resolve()
+ if current_install_dir is not None and (
+ path_resolved == current_install_dir or path_resolved in current_install_dir.parents
+ ):
continue
if kept_previous < keep_previous:
kept_previous += 1
continue
shutil.rmtree(path, ignore_errors=True)
removed.append(str(path))
+ for path in sorted(versions_dir.glob("*/*"), reverse=True):
+ if path.is_dir() and not any(path.iterdir()):
+ path.rmdir()
+ for path in sorted(versions_dir.iterdir(), reverse=True):
+ if path.is_dir() and not any(path.iterdir()):
+ path.rmdir()
return {"ok": True, "removed": removed}
def prepare(self, *, force: bool | None = None, offline: bool | None = None) -> dict[str, Any]:
@@ -410,10 +432,10 @@ class ShowRuntimeManager:
if not archive:
return None
install_dir = self._manifest_install_dir(manifest, archive)
- command = self._manifest_runtime_command(install_dir, node)
- if command and self._manifest_install_matches(install_dir, manifest, archive):
+ command = self._verified_manifest_runtime_command(install_dir, manifest, archive, node)
+ if command:
return command
- return None
+ return self._verified_manifest_runtime_command(self._legacy_manifest_install_dir(manifest, archive), manifest, archive, node)
def _install_manifest_runtime(self) -> list[str] | None:
node = _resolve_node_command()
@@ -429,9 +451,10 @@ class ShowRuntimeManager:
if not archive:
return None
install_dir = self._manifest_install_dir(manifest, archive)
- existing_command = self._manifest_runtime_command(install_dir, node)
- existing_matches = self._manifest_install_matches(install_dir, manifest, archive)
- verified_existing_command = existing_command if existing_matches else None
+ verified_existing_command = self._verified_manifest_runtime_command(install_dir, manifest, archive, node)
+ if not verified_existing_command:
+ legacy_install_dir = self._legacy_manifest_install_dir(manifest, archive)
+ verified_existing_command = self._verified_manifest_runtime_command(legacy_install_dir, manifest, archive, node)
if verified_existing_command and not self.force_install:
self._install_reason = None
return verified_existing_command
@@ -578,11 +601,33 @@ class ShowRuntimeManager:
return True
def _manifest_install_dir(self, manifest: ShowRuntimeManifest, archive: ShowRuntimeArchive) -> Path:
+ fingerprint = hashlib.sha256(f"{manifest.digest}:{archive.sha256}".encode("utf-8")).hexdigest()[:16]
+ return (
+ self.runtime_dir
+ / "versions"
+ / _safe_path_part(manifest.runtime_version)
+ / _safe_path_part(archive.platform)
+ / fingerprint
+ )
+
+ def _legacy_manifest_install_dir(self, manifest: ShowRuntimeManifest, archive: ShowRuntimeArchive) -> Path:
return self.runtime_dir / "versions" / _safe_path_part(manifest.runtime_version) / _safe_path_part(archive.platform)
def _manifest_metadata_path(self, install_dir: Path) -> Path:
return install_dir / ".vibe-show-runtime.json"
+ def _verified_manifest_runtime_command(
+ self,
+ install_dir: Path,
+ manifest: ShowRuntimeManifest,
+ archive: ShowRuntimeArchive,
+ node: list[str],
+ ) -> list[str] | None:
+ command = self._manifest_runtime_command(install_dir, node)
+ if command and self._manifest_install_matches(install_dir, manifest, archive):
+ return command
+ return None
+
def _manifest_install_matches(self, install_dir: Path, manifest: ShowRuntimeManifest, archive: ShowRuntimeArchive) -> bool:
try:
payload = json.loads(self._manifest_metadata_path(install_dir).read_text(encoding="utf-8"))
@@ -901,6 +946,14 @@ def stop_show_runtime_manager() -> None:
_manager.stop()
+async def prewarm_show_runtime() -> ShowRuntimeResult:
+ return await get_show_runtime_manager().ensure()
+
+
+async def prewarm_show_page_session(session_id: str, *, base_path: str | None = None) -> ShowRuntimeResult:
+ return await get_show_runtime_manager().prewarm_session(session_id, base_path=base_path)
+
+
def set_show_runtime_manager_for_tests(manager: ShowRuntimeManager | None) -> None:
global _manager
_manager = manager
diff --git a/tests/test_show_pages.py b/tests/test_show_pages.py
index 92b0c79bf..bb29b8bbf 100644
--- a/tests/test_show_pages.py
+++ b/tests/test_show_pages.py
@@ -1,4 +1,5 @@
import json
+from dataclasses import dataclass
from config import paths
from config.v2_config import AgentsConfig, PlatformsConfig, RemoteAccessConfig, RuntimeConfig, SlackConfig, UiConfig, V2Config
@@ -7,6 +8,12 @@ from storage.pagination import PageRequest
from vibe import cli
+@dataclass(frozen=True)
+class _FakeShowRuntimeResult:
+ available: bool
+ reason: str | None = None
+
+
def test_show_without_subcommand_prints_help(capsys):
parser = cli.build_parser()
args = parser.parse_args(["show"])
@@ -245,6 +252,26 @@ def test_show_path_cli_json_creates_page(monkeypatch, tmp_path, capsys):
monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
paths.ensure_data_dirs()
_save_config()
+ captured = {}
+
+ class _Response:
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_args):
+ return None
+
+ def read(self):
+ return json.dumps({"ok": True}).encode("utf-8")
+
+ def _urlopen(request, timeout):
+ captured["url"] = request.full_url
+ captured["payload"] = json.loads(request.data.decode("utf-8"))
+ captured["timeout"] = timeout
+ return _Response()
+
+ monkeypatch.setattr(cli.runtime, "read_status", lambda: {"ui_pid": 123})
+ monkeypatch.setattr(cli.urllib.request, "urlopen", _urlopen)
args = cli.build_parser().parse_args(["show", "path", "--session-id", "ses123", "--json"])
assert cli.cmd_show_path(args) == 0
@@ -264,6 +291,28 @@ def test_show_path_cli_json_creates_page(monkeypatch, tmp_path, capsys):
in payload["next_actions"]
)
assert (tmp_path / "show" / "ses123" / "index.html").exists()
+ assert captured["url"] == "http://127.0.0.1:5123/api/show/sessions/ses123/prewarm"
+ assert captured["payload"] == {}
+ assert captured["timeout"] == 3
+
+
+def test_show_path_cli_keeps_page_when_prewarm_fails(monkeypatch, tmp_path, capsys):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+ _save_config()
+
+ def _urlopen(_request, timeout):
+ raise OSError("runtime unavailable")
+
+ monkeypatch.setattr(cli.runtime, "read_status", lambda: {"ui_pid": 123})
+ monkeypatch.setattr(cli.urllib.request, "urlopen", _urlopen)
+
+ args = cli.build_parser().parse_args(["show", "path", "--session-id", "ses123", "--json"])
+ assert cli.cmd_show_path(args) == 0
+
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["ok"] is True
+ assert (tmp_path / "show" / "ses123" / "index.html").exists()
def test_show_list_cli_json_reports_existing_pages(monkeypatch, tmp_path, capsys):
@@ -385,6 +434,24 @@ def test_show_update_cli_reports_transition_urls(monkeypatch, tmp_path, capsys):
monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
paths.ensure_data_dirs()
_save_config()
+ prewarmed = []
+
+ class _Response:
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_args):
+ return None
+
+ def read(self):
+ return json.dumps({"ok": True}).encode("utf-8")
+
+ def _urlopen(request, timeout):
+ prewarmed.append((request.full_url, json.loads(request.data.decode("utf-8"))))
+ return _Response()
+
+ monkeypatch.setattr(cli.runtime, "read_status", lambda: {"ui_pid": 123})
+ monkeypatch.setattr(cli.urllib.request, "urlopen", _urlopen)
parser = cli.build_parser()
assert cli.cmd_show_path(parser.parse_args(["show", "path", "--session-id", "ses123", "--json"])) == 0
@@ -397,6 +464,11 @@ def test_show_update_cli_reports_transition_urls(monkeypatch, tmp_path, capsys):
assert public_payload["active_url"] == public_payload["public_url"]
assert public_payload["public_url"].startswith("https://alex.avibe.bot/p/")
assert public_payload["previous_private_url"] == "https://alex.avibe.bot/show/ses123/"
+ share_path = "/" + public_payload["public_url"].split("https://alex.avibe.bot/", 1)[1]
+ assert prewarmed[-1] == (
+ "http://127.0.0.1:5123/api/show/sessions/ses123/prewarm",
+ {"base_path": share_path},
+ )
args = parser.parse_args(["show", "update", "--session-id", "ses123", "--visibility", "private", "--json"])
assert cli.cmd_show_update(args) == 0
@@ -404,6 +476,7 @@ def test_show_update_cli_reports_transition_urls(monkeypatch, tmp_path, capsys):
assert private_payload["visibility"] == "private"
assert private_payload["active_url"] == "https://alex.avibe.bot/show/ses123/"
assert private_payload["previous_public_url"] == public_payload["public_url"]
+ assert prewarmed[-1] == ("http://127.0.0.1:5123/api/show/sessions/ses123/prewarm", {})
def test_show_update_rotate_share_fails_while_private(monkeypatch, tmp_path, capsys):
diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.py
index 638a53382..9a071444a 100644
--- a/tests/test_ui_show_pages.py
+++ b/tests/test_ui_show_pages.py
@@ -4,6 +4,7 @@ import io
import json
import tarfile
from pathlib import Path
+from types import SimpleNamespace
from unittest.mock import patch
import pytest
@@ -926,6 +927,50 @@ def test_cli_show_event_ingress_requires_cli_token(monkeypatch, tmp_path):
assert response.status_code == 403
+def test_cli_show_prewarm_ingress_uses_ui_runtime_manager(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ calls = []
+
+ async def fake_prewarm(session_id, *, base_path=None):
+ calls.append((session_id, base_path))
+ return SimpleNamespace(available=True, reason=None, base_url="http://127.0.0.1:49200")
+
+ monkeypatch.setattr("core.show_runtime.prewarm_show_page_session", fake_prewarm)
+
+ response = app.test_client().post(
+ "/api/show/sessions/ses123/prewarm",
+ base_url="http://127.0.0.1:5123",
+ headers={
+ "Content-Type": "application/json",
+ "X-Vibe-Show-Client": "cli",
+ "X-Vibe-Show-Cli-Token": show_cli_event_token(),
+ },
+ json={"base_path": "/p/share123/"},
+ )
+
+ assert response.status_code == 200
+ assert response.get_json()["ok"] is True
+ assert calls == [("ses123", "/p/share123/")]
+
+
+def test_cli_show_prewarm_ingress_requires_cli_token(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+
+ response = app.test_client().post(
+ "/api/show/sessions/ses123/prewarm",
+ base_url="http://127.0.0.1:5123",
+ headers={
+ "Content-Type": "application/json",
+ "X-Vibe-Show-Client": "cli",
+ },
+ json={},
+ )
+
+ assert response.status_code == 403
+
+
def test_cli_show_event_ingress_allows_configured_host_with_cli_token(monkeypatch, tmp_path):
monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
config = _save_config(tmp_path)
@@ -1289,17 +1334,11 @@ def test_show_runtime_manager_installs_from_manifest_cache(monkeypatch, tmp_path
monkeypatch.setattr("core.show_runtime._resolve_command", lambda command: ["/bin/node"] if command == "node" else None)
result = manager.prepare()
- installed_cli = (
- runtime_dir
- / "versions"
- / "runtime-test-ref"
- / _runtime_platform_tag()
- / "node_modules"
- / "@avibe"
- / "show-runtime"
- / "dist"
- / "cli.js"
- )
+ manifest = manager._load_runtime_manifest()
+ assert manifest is not None
+ archive = manager._manifest_archive_for_platform(manifest)
+ assert archive is not None
+ installed_cli = Path(manager._manifest_runtime_command(manager._manifest_install_dir(manifest, archive), ["/bin/node"])[1])
assert result["ok"] is True
assert result["command"] == ["/bin/node", str(installed_cli)]
@@ -1313,6 +1352,123 @@ def test_show_runtime_manager_installs_from_manifest_cache(monkeypatch, tmp_path
assert status["installed_matches_manifest"] is True
+def test_show_runtime_manager_manifest_install_dir_includes_manifest_and_archive_identity(monkeypatch, tmp_path):
+ old_archive_path = _write_runtime_archive(tmp_path / "old", text="old runtime\n")
+ old_manifest_path = _write_runtime_manifest(tmp_path / "old", old_archive_path)
+ runtime_dir = tmp_path / "runtime"
+ monkeypatch.setattr("core.show_runtime._resolve_command", lambda command: ["/bin/node"] if command == "node" else None)
+
+ old_manager = ShowRuntimeManager(
+ workspace_root=tmp_path / "show",
+ runtime_dir=runtime_dir,
+ manifest_path=old_manifest_path,
+ )
+ old_result = old_manager.prepare()
+ old_cli = Path(old_result["command"][1])
+ assert old_cli.read_text(encoding="utf-8") == "old runtime\n"
+
+ new_archive_path = _write_runtime_archive(tmp_path / "new", text="new runtime\n")
+ new_manifest_path = _write_runtime_manifest(tmp_path / "new", new_archive_path)
+ new_manager = ShowRuntimeManager(
+ workspace_root=tmp_path / "show",
+ runtime_dir=runtime_dir,
+ manifest_path=new_manifest_path,
+ )
+
+ new_result = new_manager.prepare()
+ new_cli = Path(new_result["command"][1])
+
+ assert new_cli != old_cli
+ assert new_cli.read_text(encoding="utf-8") == "new runtime\n"
+ assert old_cli.read_text(encoding="utf-8") == "old runtime\n"
+ assert new_manager.status()["installed_matches_manifest"] is True
+
+
+def test_show_runtime_clean_prunes_stale_manifest_fingerprints(monkeypatch, tmp_path):
+ old_archive_path = _write_runtime_archive(tmp_path / "old", text="old runtime\n")
+ old_manifest_path = _write_runtime_manifest(tmp_path / "old", old_archive_path)
+ runtime_dir = tmp_path / "runtime"
+ monkeypatch.setattr("core.show_runtime._resolve_command", lambda command: ["/bin/node"] if command == "node" else None)
+
+ old_manager = ShowRuntimeManager(
+ workspace_root=tmp_path / "show",
+ runtime_dir=runtime_dir,
+ manifest_path=old_manifest_path,
+ )
+ old_result = old_manager.prepare()
+ old_install_dir = Path(old_result["command"][1]).parents[4]
+
+ new_archive_path = _write_runtime_archive(tmp_path / "new", text="new runtime\n")
+ new_manifest_path = _write_runtime_manifest(tmp_path / "new", new_archive_path)
+ new_manager = ShowRuntimeManager(
+ workspace_root=tmp_path / "show",
+ runtime_dir=runtime_dir,
+ manifest_path=new_manifest_path,
+ )
+ new_result = new_manager.prepare()
+ new_install_dir = Path(new_result["command"][1]).parents[4]
+
+ result = new_manager.clean(keep_previous=0)
+
+ assert result["ok"] is True
+ assert str(old_install_dir) in result["removed"]
+ assert old_install_dir.exists() is False
+ assert new_install_dir.exists() is True
+
+
+def test_show_runtime_manager_reuses_legacy_manifest_install_offline(monkeypatch, tmp_path):
+ archive_path = _write_runtime_archive(tmp_path, text="legacy runtime\n")
+ manifest_path = _write_runtime_manifest(tmp_path, archive_path)
+ runtime_dir = tmp_path / "runtime"
+ manager = ShowRuntimeManager(
+ workspace_root=tmp_path / "show",
+ runtime_dir=runtime_dir,
+ manifest_path=manifest_path,
+ offline=True,
+ )
+ monkeypatch.setattr("core.show_runtime._resolve_command", lambda command: ["/bin/node"] if command == "node" else None)
+ manifest = manager._load_runtime_manifest()
+ assert manifest is not None
+ archive = manager._manifest_archive_for_platform(manifest)
+ assert archive is not None
+ legacy_install_dir = manager._legacy_manifest_install_dir(manifest, archive)
+ legacy_cli = legacy_install_dir / "node_modules" / "@avibe" / "show-runtime" / "dist" / "cli.js"
+ legacy_cli.parent.mkdir(parents=True)
+ legacy_cli.write_text("legacy runtime\n", encoding="utf-8")
+ manager._write_manifest_install_metadata(legacy_install_dir, manifest, archive)
+
+ result = manager.prepare()
+
+ assert result["ok"] is True
+ assert result["command"] == ["/bin/node", str(legacy_cli)]
+
+
+def test_show_runtime_clean_skips_legacy_parent_of_current_fingerprint(monkeypatch, tmp_path):
+ archive_path = _write_runtime_archive(tmp_path, text="current runtime\n")
+ manifest_path = _write_runtime_manifest(tmp_path, archive_path)
+ runtime_dir = tmp_path / "runtime"
+ manager = ShowRuntimeManager(
+ workspace_root=tmp_path / "show",
+ runtime_dir=runtime_dir,
+ manifest_path=manifest_path,
+ )
+ monkeypatch.setattr("core.show_runtime._resolve_command", lambda command: ["/bin/node"] if command == "node" else None)
+ result = manager.prepare()
+ current_install_dir = Path(result["command"][1]).parents[4]
+ legacy_parent = current_install_dir.parent
+ manifest = manager._load_runtime_manifest()
+ assert manifest is not None
+ archive = manager._manifest_archive_for_platform(manifest)
+ assert archive is not None
+ manager._write_manifest_install_metadata(legacy_parent, manifest, archive)
+
+ clean_result = manager.clean(keep_previous=0)
+
+ assert str(legacy_parent) not in clean_result["removed"]
+ assert current_install_dir.exists() is True
+ assert Path(result["command"][1]).exists() is True
+
+
def test_show_runtime_manager_rejects_node_below_manifest_minimum(monkeypatch, tmp_path):
archive_path = _write_runtime_archive(tmp_path)
manifest_path = _write_runtime_manifest(tmp_path, archive_path)
@@ -1647,6 +1803,30 @@ def test_show_runtime_shutdown_stops_manager():
assert manager.stopped is True
+def test_show_runtime_shutdown_cancels_prewarm_before_stopping_manager():
+ from vibe.ui_server import _stop_show_runtime_prewarm, stop_show_runtime_on_shutdown
+
+ shutdown_handlers = app.router.on_shutdown
+
+ assert shutdown_handlers.index(_stop_show_runtime_prewarm) < shutdown_handlers.index(stop_show_runtime_on_shutdown)
+
+
+def test_show_runtime_startup_prewarms_manager(monkeypatch):
+ from vibe.ui_server import _prewarm_show_runtime_task
+
+ called = []
+
+ async def fake_prewarm():
+ called.append(True)
+ return SimpleNamespace(available=True, reason=None)
+
+ monkeypatch.setattr("core.show_runtime.prewarm_show_runtime", fake_prewarm)
+
+ asyncio.run(_prewarm_show_runtime_task())
+
+ assert called == [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)
diff --git a/vibe/cli.py b/vibe/cli.py
index cca98b71a..3706a3157 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -1,4 +1,5 @@
import argparse
+import asyncio
import getpass
import json
import logging
@@ -4144,6 +4145,7 @@ def cmd_show_path(args):
try:
page = store.ensure(args.session_id)
page_dir = ensure_show_page_dir(args.session_id)
+ _prewarm_show_page_session_best_effort(args.session_id)
payload = _show_page_result(page, message=f"Show Page workspace is ready at {page_dir}.")
if getattr(args, "json", False):
_print_json(payload)
@@ -4157,6 +4159,11 @@ def cmd_show_path(args):
store.close()
+def _prewarm_show_page_session_best_effort(session_id: str, *, base_path: str | None = None) -> None:
+ if _request_show_page_prewarm_best_effort(session_id, base_path=base_path) is None:
+ logger.debug("Show Page session prewarm skipped for %s", session_id)
+
+
def cmd_show_status(args):
store = _load_show_page_store()
try:
@@ -4219,6 +4226,9 @@ def cmd_show_update(args):
extra["previous_active_url"] = previous_active_url
message = "Show Page has been taken offline. Local files were not deleted."
+ if updated.visibility != "offline":
+ base_path = f"/p/{updated.share_id}/" if updated.visibility == "public" and updated.share_id else None
+ _prewarm_show_page_session_best_effort(updated.session_id, base_path=base_path)
payload = _show_page_result(updated, message=message, extra=extra)
if getattr(args, "json", False):
_print_json(payload)
@@ -4272,6 +4282,40 @@ def _local_show_events_url(session_id: str) -> str | None:
return f"http://{_ui_show_events_host(config)}:{int(port)}/api/show/sessions/{quote(session_id, safe='')}/events"
+def _local_show_prewarm_url(session_id: str) -> str | None:
+ events_url = _local_show_events_url(session_id)
+ if not events_url:
+ return None
+ return f"{events_url.rsplit('/', 1)[0]}/prewarm"
+
+
+def _request_show_page_prewarm_best_effort(session_id: str, *, base_path: str | None = None) -> dict | None:
+ from core.show_pages import SHOW_CLI_EVENT_TOKEN_HEADER, show_cli_event_token
+
+ url = _local_show_prewarm_url(session_id)
+ if not url:
+ return None
+ payload = {"base_path": base_path} if base_path else {}
+ body = json.dumps(payload).encode("utf-8")
+ request = urllib.request.Request(
+ url,
+ data=body,
+ method="POST",
+ headers={
+ "Content-Type": "application/json",
+ "X-Vibe-Show-Client": "cli",
+ SHOW_CLI_EVENT_TOKEN_HEADER: show_cli_event_token(),
+ },
+ )
+ try:
+ with urllib.request.urlopen(request, timeout=3) as response:
+ data = json.loads(response.read().decode("utf-8") or "{}")
+ return data if isinstance(data, dict) else None
+ except Exception:
+ logger.debug("Failed to request Show Page prewarm from live UI", exc_info=True)
+ return None
+
+
def _post_show_event_to_live_ui(session_id: str, payload: dict) -> dict | None:
from core.show_pages import SHOW_CLI_EVENT_TOKEN_HEADER, show_cli_event_token
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index cdb3d0943..11142f72c 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -223,7 +223,7 @@ def _is_cli_show_event_request() -> bool:
token = request.headers.get(SHOW_CLI_EVENT_TOKEN_HEADER)
return (
request.method == "POST"
- and re.fullmatch(r"/api/show/sessions/[^/]+/events", request.path or "") is not None
+ and re.fullmatch(r"/api/show/sessions/[^/]+/(events|prewarm)", request.path or "") is not None
and request.headers.get("X-Vibe-Show-Client") == "cli"
and bool(token)
and hmac.compare_digest(token, show_cli_event_token())
@@ -5032,6 +5032,21 @@ def show_session_events_create(session_id: str):
return _show_event_response_from_payload(session_id, _show_events_payload_from_request())
[email protected]("/api/show/sessions/<session_id>/prewarm", methods=["POST"])
+async def show_session_prewarm(session_id: str):
+ if not _is_cli_show_event_request():
+ return jsonify({"ok": False, "code": "forbidden"}), 403
+ payload = _show_events_payload_from_request()
+ base_path = payload.get("base_path")
+ if base_path is not None and not isinstance(base_path, str):
+ return jsonify({"ok": False, "code": "invalid_base_path"}), 400
+ from core.show_runtime import prewarm_show_page_session
+
+ result = await prewarm_show_page_session(session_id, base_path=base_path)
+ status_code = 200 if result.available else 202
+ return jsonify({"ok": result.available, "reason": result.reason, "base_url": result.base_url}), status_code
+
+
async def _show_page_runtime_response(
session_id: str,
asset_path: str,
@@ -5204,9 +5219,6 @@ def stop_show_runtime_on_shutdown() -> None:
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
@@ -5399,6 +5411,7 @@ def _reconcile_remote_access_for_ui_start(config: V2Config | None) -> None:
# shutdown/reload instead of leaking a pending task.
_inbox_bridge_task: "asyncio.Task | None" = None
+_show_runtime_prewarm_task: "asyncio.Task | None" = None
async def _start_inbox_bridge() -> None:
@@ -5426,6 +5439,46 @@ app.add_event_handler("startup", _start_inbox_bridge)
app.add_event_handler("shutdown", _stop_inbox_bridge)
+async def _prewarm_show_runtime_task() -> None:
+ from core.show_runtime import prewarm_show_runtime
+
+ start = time.monotonic()
+ try:
+ result = await prewarm_show_runtime()
+ duration_ms = int((time.monotonic() - start) * 1000)
+ if result.available:
+ logger.info("Show Runtime prewarmed in %sms", duration_ms)
+ else:
+ logger.warning("Show Runtime prewarm failed in %sms: %s", duration_ms, result.reason)
+ except Exception:
+ duration_ms = int((time.monotonic() - start) * 1000)
+ logger.warning("Show Runtime prewarm raised after %sms", duration_ms, exc_info=True)
+
+
+async def _start_show_runtime_prewarm() -> None:
+ global _show_runtime_prewarm_task
+ if _show_runtime_prewarm_task is None or _show_runtime_prewarm_task.done():
+ _show_runtime_prewarm_task = asyncio.create_task(_prewarm_show_runtime_task(), name="show-runtime-prewarm")
+
+
+async def _stop_show_runtime_prewarm() -> None:
+ global _show_runtime_prewarm_task
+ task, _show_runtime_prewarm_task = _show_runtime_prewarm_task, None
+ if task is not None and not task.done():
+ task.cancel()
+ try:
+ await task
+ except asyncio.CancelledError:
+ pass
+ except Exception:
+ logger.debug("show runtime prewarm shutdown raised", exc_info=True)
+
+
+app.add_event_handler("startup", _start_show_runtime_prewarm)
+app.add_event_handler("shutdown", _stop_show_runtime_prewarm)
+app.add_event_handler("shutdown", stop_show_runtime_on_shutdown)
+
+
def _bind_ui_socket(host: str, port: int) -> socket.socket:
family = socket.AF_INET6 if host and ":" in host else socket.AF_INET
sock = socket.socket(family)