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
fix(show-runtime): bound retries and refresh recovery state (#1640)
Call White903414cc4ac9
diff --git a/core/show_pages.py b/core/show_pages.pyindex 28674946c..f3a11c471 100644--- a/core/show_pages.py+++ b/core/show_pages.py@@ -1,9 +1,9 @@from __future__ import annotations-import reimport hashlibimport hmacimport os+import reimport secretsimport stat as stat_modulefrom collections.abc import Iterable, Mapping@@ -21,11 +21,15 @@ from sqlalchemy.exc import IntegrityErrorfrom config import pathsfrom config.v2_config import V2Config, config_file_lockfrom core.avibe_cloud import avibe_cloud_connect_guidance, base_public_url-from core.show_git import format_agent_contract+from core.show_runtime_failures import (+ ShowRuntimeFailureClass,+ ShowRuntimeRecoveryAction,+)from storage.db import create_sqlite_enginefrom storage.importer import ensure_sqlite_state, resolve_primary_platform_from_configfrom storage.models import agent_sessions, show_page_access_entries, show_pagesfrom storage.pagination import PageRequest, PageResult, page_sequence+from vibe.i18n import tVISIBILITY_PRIVATE = "private"VISIBILITY_LIMITED = "limited"@@ -80,7 +84,9 @@ SHARE_ID_BYTES = 8SHOW_EVENT_WRITE_TOKEN_COOKIE = "vibe_show_event_token"SHOW_EVENT_WRITE_TOKEN_HEADER = "X-Vibe-Show-Token"SHOW_CLI_EVENT_TOKEN_HEADER = "X-Vibe-Show-Cli-Token"-SHOW_RUNTIME_RECOVERY_LOADING_DELAY_SECONDS = 30+SHOW_PAGE_RUNTIME_RECOVERY_LOADING_DELAY_SECONDS = 30++# Only the head of index.html is scanned for the icon <link> (it lives in <head>,# at the top). Bounds the per-page read so a huge inline page can't stall# /api/show-pages or allocate a large string (§7.1f review).@@ -2267,29 +2273,61 @@ def _default_index_html(session_id: str) -> str:"""-def show_page_runtime_recovery_html(session_id: str) -> str:+def show_page_runtime_recovery_html(+ session_id: str,+ *,+ reason: str,+ failure_class: ShowRuntimeFailureClass,+ recovery_action: ShowRuntimeRecoveryAction,+ retry_authorized: bool,+ language: str = "en",+) -> str:session_id = validate_session_id(session_id)escaped = _escape_html(session_id)- loading_delay = f"{SHOW_RUNTIME_RECOVERY_LOADING_DELAY_SECONDS}s"- prompt = (- "Please repair this avibe 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 "- "Tailwind CSS v4. Keep the existing CSS imports and customize standard shadcn variables "- "such as --background, --foreground, --primary, --border, and --radius. 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.\n\n"- "Show Page history contract:\n"- f"{format_agent_contract(numbered=True, session_id=session_id)}"+ current_reason = reason+ escaped_reason = _escape_html(current_reason)+ loading_delay = "0s"+ translate = lambda key: _escape_html(t(f"show.runtimeRecovery.{key}", language))+ message_key = _show_runtime_recovery_message_key(reason, failure_class=failure_class)+ surface_action = recovery_action if retry_authorized else ShowRuntimeRecoveryAction.NO_LOCAL_ACTION+ if surface_action is ShowRuntimeRecoveryAction.REPAIR:+ action_card = f"""<div class="show-recovery-card">+ <h2>{translate("repairHeading")}</h2>+ <p>{translate("repairMessage")}</p>+ <p><code>vibe doctor repair show-runtime</code></p>+ <div class="show-recovery-actions">+ <button class="show-recovery-button" id="show-runtime-retry-now" type="button">{translate("retryNow")}</button>+ </div>+ </div>"""+ elif surface_action is ShowRuntimeRecoveryAction.CHANGE_SETTING:+ action_card = f"""<div class="show-recovery-card">+ <h2>{translate("settingsHeading")}</h2>+ <p>{translate("settingsMessage")}</p>+ <p><code>{escaped_reason}</code></p>+ <div class="show-recovery-actions">+ <button class="show-recovery-button" id="show-runtime-retry-now" type="button">{translate("retryNow")}</button>+ </div>+ </div>"""+ else:+ if recovery_action is ShowRuntimeRecoveryAction.NO_LOCAL_ACTION:+ no_action_heading = "unsupportedHeading"+ no_action_message = "unsupportedMessage"+ else:+ no_action_heading = "ownerActionHeading"+ no_action_message = "ownerActionMessage"+ action_card = f"""<div class="show-recovery-card">+ <h2>{translate(no_action_heading)}</h2>+ <p>{translate(no_action_message)}</p>+ </div>"""+ recovery_script = _show_runtime_recovery_script(+ retry_authorized=retry_authorized and surface_action is not ShowRuntimeRecoveryAction.NO_LOCAL_ACTION,)- escaped_prompt = _escape_html(prompt)return f"""<!doctype html>-<html lang="en">+<html lang="{_escape_html(language)}" data-show-runtime-reason="{escaped_reason}" data-show-runtime-class="{failure_class.value}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">- <title>Show Page recovery {escaped}</title>+ <title>{translate("title")}</title><style>:root {{color-scheme: light;@@ -2446,45 +2484,95 @@ def show_page_runtime_recovery_html(session_id: str) -> str:</head><body><main class="show-recovery-shell">- <div class="show-recovery-loading">Loading Show Page</div>+ <div class="show-recovery-loading">{translate("loading")}</div><section class="show-recovery-panel">- <div class="show-recovery-eyebrow">Vibe Show recovery</div>- <h1>Ready to visualize</h1>- <p>The managed Show runtime did not respond, so avibe is showing this recovery page instead of serving a raw app shell.</p>+ <div class="show-recovery-eyebrow">{translate("eyebrow")}</div>+ <h1>{translate("heading")}</h1>+ <p>{translate(message_key)}</p><div class="show-recovery-grid">+ {action_card}<div class="show-recovery-card">- <h2>Ask your agent to fix the Show Page</h2>- <textarea id="show-recovery-agent-prompt" readonly>{escaped_prompt}</textarea>- <div class="show-recovery-actions">- <button class="show-recovery-button" type="button" data-copy-prompt>Copy prompt</button>- <button class="show-recovery-button secondary" type="button" onclick="window.location.reload()">Retry</button>- </div>- </div>- <div class="show-recovery-card">- <h2>What to check</h2>- <ul>- <li>Wait a moment and refresh if the runtime is still starting.</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>+ <h2>{translate("reasonLabel")}</h2>+ <p><code>{escaped_reason}</code></p></div></div>- <p>Session: <code>{escaped}</code></p>+ <p>{translate("sessionLabel")}: <code>{escaped}</code></p></section></main>- <script>- document.querySelector("[data-copy-prompt]")?.addEventListener("click", async (event) => {{- const prompt = document.getElementById("show-recovery-agent-prompt")?.value || "";- await navigator.clipboard.writeText(prompt);- event.currentTarget.textContent = "Copied";- }});- </script>+ {recovery_script}</body></html>"""+def _show_runtime_recovery_script(+ *,+ retry_authorized: bool,+) -> str:+ if not retry_authorized:+ return ""+ return """<script>+ (() => {+ const retryNow = async () => {+ const button = document.getElementById("show-runtime-retry-now");+ if (button) button.disabled = true;+ try {+ const response = await fetch(window.location.href, {+ cache: "no-store",+ credentials: "same-origin",+ headers: {+ "Accept": "text/html",+ "X-Avibe-Show-Recovery-Retry": "1",+ },+ });+ const contentType = (response.headers.get("content-type") || "").toLowerCase();+ if (response.redirected || !response.ok || !contentType.includes("text/html")) {+ window.location.assign(response.url || window.location.href);+ return;+ }+ const html = await response.text();+ document.open();+ document.write(html);+ document.close();+ } catch (_error) {+ if (button) button.disabled = false;+ }+ };+ document.getElementById("show-runtime-retry-now")?.addEventListener("click", retryNow);+ })();+ </script>"""+++def _show_runtime_recovery_message_key(+ reason: str | None,+ *,+ failure_class: ShowRuntimeFailureClass,+) -> str:+ if failure_class is ShowRuntimeFailureClass.CONFIGURED and reason and reason.endswith("_unavailable_offline"):+ return "offlineMessage"+ if reason in {"runtime_archive_download_failed", "runtime_manifest_download_failed"}:+ return "downloadMessage"+ if reason in {"runtime_node_missing", "runtime_node_unsupported"}:+ return "nodeMessage"+ if reason == "runtime_platform_unsupported":+ return "platformMessage"+ if reason in {+ "runtime_archive_checksum_mismatch",+ "runtime_archive_size_mismatch",+ "runtime_manifest_invalid",+ }:+ return "verificationMessage"+ if reason in {"runtime_source_unsupported", "runtime_archive_url_unsupported"}:+ return "configurationMessage"+ if reason in {"VIBE_INSTALL_SKIP_SHOW_RUNTIME", "VIBE_SHOW_RUNTIME_AUTO_INSTALL"}:+ return "policyMessage"+ if reason and reason.startswith("runtime_start_"):+ return "startMessage"+ if reason and (reason.startswith("runtime_install_") or reason in {"runtime_git_missing", "runtime_npm_missing"}):+ return "installMessage"+ return "unavailableMessage"++def _escape_html(value: str) -> str:return value.replace("&", "&").replace("<", "<").replace(">", ">")diff --git a/core/show_runtime.py b/core/show_runtime.pyindex f55a1bfa3..cc437030a 100644--- a/core/show_runtime.py+++ b/core/show_runtime.py@@ -43,9 +43,15 @@ from storage.lock import (from config import pathsfrom core.dependency_network import dependency_error_details, fetch_bytes, fetch_to_path, probe_url, redact_url-from core.show_pages import SHOW_RUNTIME_RECOVERY_LOADING_DELAY_SECONDSfrom core.process_isolation import KILL_SIGNAL, isolated_subprocess_kwargs, signal_process_tree-from core.show_runtime_failures import ShowRuntimeFailureClass, classify_show_runtime_failure+from core.show_runtime_failures import (+ ShowRuntimeFailureClass,+ ShowRuntimeFailureDimension,+ ShowRuntimeFailureEvidence,+ ShowRuntimeRecoveryAction,+ classify_show_runtime_failure,+ show_runtime_recovery_action,+)logger = logging.getLogger(__name__)@@ -117,11 +123,15 @@ SHOW_RUNTIME_REQUEST_TIMEOUT_SECONDS = 30.0_CAPABILITY_RETRY_BASE_SECONDS = 0.25_CAPABILITY_RETRY_MAX_SECONDS = 5.0_CAPABILITY_RETRYABLE_STATUS_CODES = {408, 429}+SHOW_RUNTIME_CLI_FALLBACK_DELAY_SECONDS = 30_STARTUP_READY_TIMEOUT_SECONDS = 10.0_STARTUP_POLL_INTERVAL_SECONDS = 0.05_STARTUP_URL_TIMEOUT_REASON = "runtime_start_url_timeout"_STARTUP_PROCESS_UNAVAILABLE_REASON = "runtime_start_process_unavailable"_STARTUP_HEALTH_TIMEOUT_REASON = "runtime_start_health_timeout"+_STARTUP_COMMAND_UNAVAILABLE_REASON = "runtime_start_command_unavailable"+_STARTUP_COMMAND_INVALID_REASON = "runtime_start_command_invalid"+_STARTUP_ATTEMPT_FAILED_REASON = "runtime_start_attempt_failed"_MISSING = object()@@ -173,6 +183,19 @@ class ShowRuntimeRequestTimeoutError(TimeoutError):"""A proxied Runtime request exceeded its total request deadline."""+class ShowRuntimeUnavailableError(RuntimeError):+ def __init__(+ self,+ reason: str,+ failure_class: ShowRuntimeFailureClass,+ recovery_action: ShowRuntimeRecoveryAction,+ ):+ self.reason = reason+ self.failure_class = failure_class+ self.recovery_action = recovery_action+ super().__init__(reason)++class ShowRuntimePolicyState(str, Enum):ALLOWED = "allowed"SKIPPED = "skipped"@@ -258,12 +281,44 @@ class ShowRuntimeAvailability:command: list[str] | None = Nonebase_url: str | None = Nonepolicy_reason: str | None = None+ policy_failure_class: ShowRuntimeFailureClass | None = None+ policy_recovery_action: ShowRuntimeRecoveryAction | None = Noneinstall_reason: str | None = Noneinstall_failure_class: ShowRuntimeFailureClass | None = None+ install_recovery_action: ShowRuntimeRecoveryAction | None = Noneinstall_dir: str | None = Noneinstall_runtime_version: str | None = Noneinstall_matches_manifest: bool | None = Noneruntime_reason: str | None = None+ runtime_failure_class: ShowRuntimeFailureClass | None = None+ runtime_recovery_action: ShowRuntimeRecoveryAction | None = None++ def __post_init__(self) -> None:+ for dimension, reason, failure_class, recovery_action in (+ (+ "policy",+ self.policy_reason,+ self.policy_failure_class,+ self.policy_recovery_action,+ ),+ (+ "install",+ self.install_reason,+ self.install_failure_class,+ self.install_recovery_action,+ ),+ (+ "runtime",+ self.runtime_reason,+ self.runtime_failure_class,+ self.runtime_recovery_action,+ ),+ ):+ evidence = (failure_class, recovery_action)+ if reason is None and any(value is not None for value in evidence):+ raise ValueError(f"{dimension} recovery evidence requires a reason")+ if reason is not None and any(value is None for value in evidence):+ raise ValueError(f"{dimension} reason requires complete recovery evidence")@propertydef ok(self) -> bool:@@ -277,6 +332,14 @@ class ShowRuntimeAvailability:def reason(self) -> str | None:return self.runtime_reason or self.install_reason or self.policy_reason+ @property+ def failure_class(self) -> ShowRuntimeFailureClass | None:+ return self.runtime_failure_class or self.install_failure_class or self.policy_failure_class++ @property+ def recovery_action(self) -> ShowRuntimeRecoveryAction | None:+ return self.runtime_recovery_action or self.install_recovery_action or self.policy_recovery_action+@classmethoddef from_install(cls,@@ -285,6 +348,9 @@ class ShowRuntimeAvailability:install: ShowRuntimeInstallState | None = None,policy_reason: str | None = None,install_reason: str | None = None,+ install_evidence: ShowRuntimeFailureEvidence | None = None,+ install_failure_class: ShowRuntimeFailureClass | None = None,+ install_recovery_action: ShowRuntimeRecoveryAction | None = None,install_dir: Path | str | None = None,install_runtime_version: str | None = None,install_matches_manifest: bool | None = None,@@ -296,14 +362,34 @@ class ShowRuntimeAvailability:install = ShowRuntimeInstallState.FAILEDelse:install = ShowRuntimeInstallState.ABSENT+ policy_evidence = ShowRuntimeFailureEvidence(+ ShowRuntimeFailureDimension.POLICY,+ policy_reason,+ )+ if install_evidence is None:+ install_evidence = ShowRuntimeFailureEvidence(+ ShowRuntimeFailureDimension.INSTALL,+ install_reason,+ )+ elif (+ install_evidence.dimension is not ShowRuntimeFailureDimension.INSTALL+ or install_evidence.reason != install_reason+ ):+ raise ValueError("install evidence must describe the published install reason")+ resolved_install_failure_class = install_failure_class or (+ classify_show_runtime_failure(install_evidence) if install is ShowRuntimeInstallState.FAILED else None+ )return cls(policy=(ShowRuntimePolicyState.SKIPPED if policy_reason else ShowRuntimePolicyState.ALLOWED),install=install,command=command,policy_reason=policy_reason,+ policy_failure_class=(classify_show_runtime_failure(policy_evidence) if policy_reason else None),+ policy_recovery_action=(show_runtime_recovery_action(policy_evidence) if policy_reason else None),install_reason=install_reason,- install_failure_class=(- classify_show_runtime_failure(install_reason) if install is ShowRuntimeInstallState.FAILED else None+ install_failure_class=resolved_install_failure_class,+ install_recovery_action=(+ install_recovery_action or (show_runtime_recovery_action(install_evidence) if install_reason else None)),install_dir=str(install_dir) if install_dir is not None else None,install_runtime_version=install_runtime_version,@@ -313,11 +399,17 @@ class ShowRuntimeAvailability:def as_payload(self) -> dict[str, Any]:command = list(self.command) if self.command else Nonereturn {- "policy": {"state": self.policy.value, "reason": self.policy_reason},+ "policy": {+ "state": self.policy.value,+ "reason": self.policy_reason,+ "failure_class": self.policy_failure_class.value if self.policy_failure_class else None,+ "recovery_action": self.policy_recovery_action.value if self.policy_recovery_action else None,+ },"install": {"state": self.install.value,"reason": self.install_reason,"failure_class": self.install_failure_class.value if self.install_failure_class else None,+ "recovery_action": self.install_recovery_action.value if self.install_recovery_action else None,"command": command,"install_dir": self.install_dir,"runtime_version": self.install_runtime_version,@@ -326,6 +418,8 @@ class ShowRuntimeAvailability:"runtime": {"state": self.runtime.value,"reason": self.runtime_reason,+ "failure_class": self.runtime_failure_class.value if self.runtime_failure_class else None,+ "recovery_action": self.runtime_recovery_action.value if self.runtime_recovery_action else None,"base_url": self.base_url,},# Compatibility fields remain projections of the three dimensions.@@ -379,10 +473,9 @@ class ShowRuntimeManager:self.auto_install = _auto_install_enabled() if auto_install is None else auto_installself.package_spec = package_spec or os.environ.get("VIBE_SHOW_RUNTIME_PACKAGE_SPEC") or _RUNTIME_PACKAGEself.runtime_source = _normalize_runtime_source(source_value)- self.archive_url = archive_url if archive_url is not None else os.environ.get(- "VIBE_SHOW_RUNTIME_ARCHIVE_URL",- _default_runtime_archive_url(),- )+ configured_archive_url = archive_url if archive_url is not None else archive_url_env+ self.archive_url = configured_archive_url if configured_archive_url is not None else _default_runtime_archive_url()+ self._archive_url_provenance = "configured" if configured_archive_url is not None else "packaged"self.github_repo = github_repo or os.environ.get("VIBE_SHOW_RUNTIME_GITHUB_REPO") or _RUNTIME_GITHUB_REPOself.github_ref = github_ref or os.environ.get("VIBE_SHOW_RUNTIME_GITHUB_REF") or _RUNTIME_GITHUB_REFself.offline = _env_flag_enabled("VIBE_SHOW_RUNTIME_OFFLINE", default=False) if offline is None else offline@@ -391,8 +484,7 @@ class ShowRuntimeManager:self.stderr_path = self.runtime_dir / "stderr.log"self.install_log_path = self.runtime_dir / "install.log"self.cache_root = self.runtime_dir / "vite-cache"- self._install_attempted = False- self._install_reason: str | None = None+ self._install_evidence: ShowRuntimeFailureEvidence | None = Noneself._download_error: dict[str, Any] | None = Noneself._managed_command: list[str] | None = Noneself._availability = ShowRuntimeAvailability()@@ -415,78 +507,226 @@ class ShowRuntimeManager:self._capability_retry_attempt = 0self._capability_generation = 0- async def ensure(self) -> ShowRuntimeAvailability:- if self._base_url and await self._healthy(self._base_url):- return self._publish_runtime_availability(ShowRuntimeServingState.SERVING, self._base_url)+ @property+ def _install_reason(self) -> str | None:+ return self._install_evidence.reason if self._install_evidence else None++ @_install_reason.setter+ def _install_reason(self, reason: str | None) -> None:+ self._install_evidence = (+ ShowRuntimeFailureEvidence(ShowRuntimeFailureDimension.INSTALL, reason)+ if reason+ else None+ )++ def _record_install_failure(+ self,+ reason: str,+ *,+ provenance: str | None = None,+ retryable: bool | None = None,+ ) -> None:+ self._install_evidence = ShowRuntimeFailureEvidence(+ ShowRuntimeFailureDimension.INSTALL,+ reason,+ provenance,+ retryable,+ )++ def _record_download_failure(+ self,+ reason: str,+ exc: BaseException,+ url: str,+ *,+ provenance: str,+ ) -> None:+ self._download_error = _runtime_download_error(exc, url)+ retryable = self._download_error.get("retryable")+ self._record_install_failure(+ reason,+ provenance=provenance,+ retryable=retryable if isinstance(retryable, bool) else None,+ )++ def _resolve_explicit_command_availability(self) -> ShowRuntimeAvailability:+ """Resolve the configured command without discarding failure evidence."""+ if not self._command_explicit:+ raise AssertionError("explicit command resolution requires an explicit command")+ try:+ command = _resolve_command(self.command)+ except (OSError, ValueError):+ evidence = ShowRuntimeFailureEvidence(+ ShowRuntimeFailureDimension.RUNTIME,+ _STARTUP_COMMAND_INVALID_REASON,+ )+ return ShowRuntimeAvailability(+ runtime=ShowRuntimeServingState.START_FAILED,+ runtime_reason=evidence.reason,+ runtime_failure_class=classify_show_runtime_failure(evidence),+ runtime_recovery_action=show_runtime_recovery_action(evidence),+ )+ return ShowRuntimeAvailability.from_install(+ command=command,+ install_reason=None if command else "runtime_command_missing",+ )++ def _publish_explicit_command_availability(+ self,+ availability: ShowRuntimeAvailability,+ ) -> ShowRuntimeAvailability:+ self._availability = availability+ return availability++ async def ensure(self, *, automatic: bool = True) -> ShowRuntimeAvailability:async with self._lock:- if self._base_url and await self._healthy(self._base_url):- return self._publish_runtime_availability(ShowRuntimeServingState.SERVING, self._base_url)- self.stop()- if self._command_explicit:- command = _resolve_command(self.command)- availability = self._publish_install_availability(- command=command,- install_reason=None if command else "runtime_command_missing",+ return await self._admit_runtime_start(automatic=automatic)++ async def _admit_runtime_start(self, *, automatic: bool) -> ShowRuntimeAvailability:+ """Own one start admission through readiness publication."""+ availability: ShowRuntimeAvailability | None = None+ operation: _ShowRuntimeOperationOutcome | None = None+ base_url: str | None = None+ pending_exception: BaseException | None = None+ start_phase = "admission"+ try:+ availability = self._availability+ operation = _ShowRuntimeOperationOutcome(+ _ShowRuntimeOperationState.NOT_APPLICABLE,+ availability.reason or "runtime_unavailable",+ )+ if self._base_url:+ base_url = self._base_url+ operation = _ShowRuntimeOperationOutcome(+ _ShowRuntimeOperationState.COMPLETED,+ None,)else:- availability = await self._resolve_managed_availability()- command = availability.command- if not command:- return availability- self.runtime_dir.mkdir(parents=True, exist_ok=True)- self.workspace_root.mkdir(parents=True, exist_ok=True)- self.cache_root.mkdir(parents=True, exist_ok=True)- # Reap any orphaned runtime server still bound to this workspace root before- # spawning ours, so there is a single writer (avibe#813). self.stop() above- # already released our own tracked child; anything left is a stray from a- # prior avibe instance that died without reaping it (SIGKILL / crash). Run it- # off the event loop: the psutil scan + terminate/kill can block for seconds.- await asyncio.to_thread(self._sweep_orphan_runtime_servers)- with self.stdout_path.open("w", encoding="utf-8") as stdout, self.stderr_path.open(- "w", encoding="utf-8"- ) as stderr:- startup_deadline = asyncio.get_running_loop().time() + _STARTUP_READY_TIMEOUT_SECONDS- self._process = subprocess.Popen(- [- *command,- "--workspace-root",- str(self.workspace_root),- "--cache-root",- str(self.cache_root),- "--host",- "127.0.0.1",- "--port",- "0",- "--fallback-delay-seconds",- str(SHOW_RUNTIME_RECOVERY_LOADING_DELAY_SECONDS),- ],- stdout=stdout,- stderr=stderr,- text=True,- **isolated_subprocess_kwargs(),- )- base_url = await self._read_startup_url(deadline=startup_deadline)- process = self._process- if process is None or process.poll() is not None:- self.stop()- return self._publish_runtime_availability(- ShowRuntimeServingState.START_FAILED,- runtime_reason=_STARTUP_PROCESS_UNAVAILABLE_REASON,- )- if not base_url:self.stop()- return self._publish_runtime_availability(- ShowRuntimeServingState.START_FAILED,- runtime_reason=_STARTUP_URL_TIMEOUT_REASON,+ command: list[str] | None = None+ if self._command_explicit:+ start_phase = "resolve-command"+ availability = self._publish_explicit_command_availability(+ self._resolve_explicit_command_availability()+ )+ command = availability.command+ if availability.runtime_reason:+ operation = _ShowRuntimeOperationOutcome(+ _ShowRuntimeOperationState.FAILED,+ availability.runtime_reason,+ )+ else:+ start_phase = "install"+ availability = await self._resolve_managed_availability(automatic=automatic)+ command = availability.command+ if command:+ start_phase = "establish"+ self.runtime_dir.mkdir(parents=True, exist_ok=True)+ self.workspace_root.mkdir(parents=True, exist_ok=True)+ self.cache_root.mkdir(parents=True, exist_ok=True)+ # Reap any orphaned runtime server still bound to this workspace root before+ # spawning ours, so there is a single writer (avibe#813). self.stop() above+ # already released our own tracked child; anything left is a stray from a+ # prior avibe instance that died without reaping it (SIGKILL / crash). Run it+ # off the event loop: the psutil scan + terminate/kill can block for seconds.+ await asyncio.to_thread(self._sweep_orphan_runtime_servers)+ with (+ self.stdout_path.open(+ "w",+ encoding="utf-8",+ ) as stdout,+ self.stderr_path.open("w", encoding="utf-8") as stderr,+ ):+ startup_deadline = asyncio.get_running_loop().time() + _STARTUP_READY_TIMEOUT_SECONDS+ start_phase = "spawn"+ self._process = subprocess.Popen(+ [+ *command,+ "--workspace-root",+ str(self.workspace_root),+ "--cache-root",+ str(self.cache_root),+ "--host",+ "127.0.0.1",+ "--port",+ "0",+ "--fallback-delay-seconds",+ str(SHOW_RUNTIME_CLI_FALLBACK_DELAY_SECONDS),+ ],+ stdout=stdout,+ stderr=stderr,+ text=True,+ **isolated_subprocess_kwargs(),+ )+ start_phase = "readiness"+ base_url = await self._read_startup_url(deadline=startup_deadline)+ process = self._process+ if process is None or process.poll() is not None:+ operation = _ShowRuntimeOperationOutcome(+ _ShowRuntimeOperationState.FAILED,+ _STARTUP_PROCESS_UNAVAILABLE_REASON,+ )+ elif not base_url:+ operation = _ShowRuntimeOperationOutcome(+ _ShowRuntimeOperationState.FAILED,+ _STARTUP_URL_TIMEOUT_REASON,+ )+ elif reason := await self._wait_for_startup_health(+ base_url,+ process,+ deadline=startup_deadline,+ ):+ operation = _ShowRuntimeOperationOutcome(+ _ShowRuntimeOperationState.FAILED,+ reason,+ )+ else:+ operation = _ShowRuntimeOperationOutcome(+ _ShowRuntimeOperationState.COMPLETED,+ None,+ )+ elif operation.state is not _ShowRuntimeOperationState.FAILED:+ operation = _ShowRuntimeOperationOutcome(+ _ShowRuntimeOperationState.NOT_APPLICABLE,+ availability.reason or "runtime_unavailable",+ )+ except OSError as exc:+ reason = _STARTUP_ATTEMPT_FAILED_REASON+ if start_phase == "spawn" and exc.errno in {+ errno.EACCES,+ errno.ENOENT,+ errno.ENOEXEC,+ }:+ reason = (+ _STARTUP_COMMAND_INVALID_REASON if self._command_explicit else _STARTUP_COMMAND_UNAVAILABLE_REASON)- if reason := await self._wait_for_startup_health(base_url, process, deadline=startup_deadline):- self.stop()- return self._publish_runtime_availability(- ShowRuntimeServingState.START_FAILED,- runtime_reason=reason,+ operation = _ShowRuntimeOperationOutcome(+ _ShowRuntimeOperationState.FAILED,+ reason,+ )+ logger.exception("Show Runtime start admission raised during %s", start_phase)+ except BaseException as exc:+ pending_exception = exc+ finally:+ if pending_exception is not None and self._process is not None:+ try:+ self.stop()+ except OSError:+ logger.warning("Show Runtime cancellation cleanup failed", exc_info=True)+ if availability is None or operation is None:+ availability = self._availability+ operation = _ShowRuntimeOperationOutcome(+ _ShowRuntimeOperationState.NOT_APPLICABLE,+ availability.reason or "runtime_unavailable",)- self._base_url = base_url- return self._publish_runtime_availability(ShowRuntimeServingState.SERVING, base_url)+ published = self._complete_runtime_start_admission(+ availability,+ operation,+ base_url=base_url,+ )+ if pending_exception is not None:+ raise pending_exception+ return publishedasync def request(self,@@ -497,43 +737,33 @@ class ShowRuntimeManager:headers: dict[str, str] | None = None,body: bytes | None = None,timeout_seconds: float | None = None,+ automatic: bool = True,) -> httpx.Response:- ready = await self.ensure()- if not ready.available or not ready.base_url:- raise RuntimeError(ready.reason or "show runtime unavailable")- await self._negotiate_context_key_capability(ready.base_url)+ base_url = self._base_url+ process = self._process+ if base_url is None:+ ready = await self.ensure(automatic=automatic)+ if not ready.available or not ready.base_url:+ raise self._unavailable_error(ready)+ base_url = ready.base_url+ process = self._process+ await self._negotiate_context_key_capability(base_url)request_headers = {- key: value- for key, value in envelope.headers(headers).items()- if key.lower() != SHOW_RUNTIME_BASE_HEADER+ key: value for key, value in envelope.headers(headers).items() if key.lower() != SHOW_RUNTIME_BASE_HEADER}if session_part := _show_runtime_app_session_part(path):request_headers[SHOW_RUNTIME_BASE_HEADER] = f"/show/{session_part}/"- phase_timeout_seconds = (- SHOW_RUNTIME_REQUEST_TIMEOUT_SECONDS- if timeout_seconds is None- else timeout_seconds+ phase_timeout_seconds = SHOW_RUNTIME_REQUEST_TIMEOUT_SECONDS if timeout_seconds is None else timeout_seconds+ return await self._request_runtime_transport(+ method,+ base_url,+ path,+ process=process,+ headers=request_headers,+ body=body,+ phase_timeout_seconds=phase_timeout_seconds,+ total_timeout_seconds=timeout_seconds,)- async with httpx.AsyncClient(- timeout=httpx.Timeout(phase_timeout_seconds, connect=5.0)- ) as client:- request = client.request(- method,- f"{ready.base_url}{path}",- headers=request_headers,- content=body,- )- if timeout_seconds is None:- return await request- try:- return await asyncio.wait_for(- request,- timeout=timeout_seconds,- )- except (asyncio.TimeoutError, httpx.ReadTimeout) as exc:- raise ShowRuntimeRequestTimeoutError(- f"Show Runtime request exceeded {timeout_seconds:g} seconds"- ) from excasync def request_global(self,@@ -544,21 +774,70 @@ class ShowRuntimeManager:body: bytes | None = None,) -> httpx.Response:"""Request a capability-independent Runtime resource without an app context."""- ready = await self.ensure()- if not ready.available or not ready.base_url:- raise RuntimeError(ready.reason or "show runtime unavailable")+ base_url = self._base_url+ process = self._process+ if base_url is None:+ ready = await self.ensure()+ if not ready.available or not ready.base_url:+ raise self._unavailable_error(ready)+ base_url = ready.base_url+ process = self._processblocked = {SHOW_RUNTIME_PROTOCOL_HEADER.lower(),SHOW_RUNTIME_CONTEXT_HEADER.lower(),SHOW_RUNTIME_BASE_HEADER.lower(),}- forwarded = {- key: value- for key, value in (headers or {}).items()- if key.lower() not in blocked- }- 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=forwarded, content=body)+ forwarded = {key: value for key, value in (headers or {}).items() if key.lower() not in blocked}+ return await self._request_runtime_transport(+ method,+ base_url,+ path,+ process=process,+ headers=forwarded,+ body=body,+ phase_timeout_seconds=30.0,+ )++ async def _request_runtime_transport(+ self,+ method: str,+ base_url: str,+ path: str,+ *,+ process: subprocess.Popen[str] | None,+ headers: dict[str, str],+ body: bytes | None,+ phase_timeout_seconds: float,+ total_timeout_seconds: float | None = None,+ ) -> httpx.Response:+ """Own transport failures and publish their recovery evidence."""+ try:+ async with httpx.AsyncClient(timeout=httpx.Timeout(phase_timeout_seconds, connect=5.0)) as client:+ request = client.request(method, f"{base_url}{path}", headers=headers, content=body)+ if total_timeout_seconds is None:+ return await request+ try:+ return await asyncio.wait_for(request, timeout=total_timeout_seconds)+ except (asyncio.TimeoutError, httpx.ReadTimeout) as exc:+ raise ShowRuntimeRequestTimeoutError(+ f"Show Runtime request exceeded {total_timeout_seconds:g} seconds"+ ) from exc+ except (ShowRuntimeRequestTimeoutError, httpx.RequestError) as exc:+ async with self._lock:+ if self._base_url == base_url and self._process is process:+ self._base_url = None+ self._clear_capability_state()+ if isinstance(exc, ShowRuntimeRequestTimeoutError):+ raise+ evidence = ShowRuntimeFailureEvidence(+ ShowRuntimeFailureDimension.RUNTIME,+ "runtime_proxy_failed",+ )+ raise ShowRuntimeUnavailableError(+ "runtime_proxy_failed",+ classify_show_runtime_failure(evidence),+ show_runtime_recovery_action(evidence),+ ) from excasync def prewarm_session(self,@@ -639,11 +918,23 @@ class ShowRuntimeManager:) -> ShowRuntimeWebSocketTarget:ready = await self.ensure()if not ready.available or not ready.base_url:- raise RuntimeError(ready.reason or "show runtime unavailable")+ raise self._unavailable_error(ready)await self._negotiate_context_key_capability(ready.base_url)url = f"{ready.base_url.replace('http://', 'ws://', 1).replace('https://', 'wss://', 1)}{path}"return ShowRuntimeWebSocketTarget(url=url, headers=envelope.headers())+ def _unavailable_error(self, availability: ShowRuntimeAvailability) -> ShowRuntimeUnavailableError:+ reason = availability.reason+ failure_class = availability.failure_class+ recovery_action = availability.recovery_action+ if reason is None or failure_class is None or recovery_action is None:+ raise AssertionError("unavailable Show Runtime must publish complete recovery evidence")+ return ShowRuntimeUnavailableError(+ reason,+ failure_class,+ recovery_action,+ )+async def context_key_capability(self) -> ShowRuntimeContextCapability:ready = await self.ensure()if not ready.available or not ready.base_url:@@ -806,85 +1097,38 @@ class ShowRuntimeManager:except Exception: # pragma: no cover - defensive; sweeping must never block spawnlogger.debug("Orphan show runtime sweep skipped", exc_info=True)- async def _resolve_managed_availability(self) -> ShowRuntimeAvailability:- if self._command_explicit and self.command != _RUNTIME_BIN:- command = _resolve_command(self.command)- return self._publish_install_availability(- command=command,- install_reason=None if command else "runtime_command_missing",- )- if self.runtime_source == _RUNTIME_SOURCE_MANIFEST:- if self._managed_command and not self.force_install:- return self._publish_install_availability(command=self._managed_command)- command = (- None- if self.force_install or self.manifest_url- else self._installed_manifest_runtime_command(offline=self.offline)- )- if command:- return self._publish_install_availability(command=command)- admission, _operation = await asyncio.to_thread(- self._attempt_managed_install,- force=self.force_install,- offline=self.offline,- automatic=True,+ async def _resolve_managed_availability(+ self,+ *,+ automatic: bool = True,+ ) -> ShowRuntimeAvailability:+ if self._command_explicit:+ return self._publish_explicit_command_availability(+ self._resolve_explicit_command_availability())- if admission.command:- return admission- if self.manifest_url and not self.force_install:- command = self._installed_manifest_runtime_command(offline=self.offline)- if command:- return self._publish_install_availability(- command=command,- policy_reason=admission.policy_reason,- )- if self._managed_command:- return self._publish_install_availability(- command=self._managed_command,- policy_reason=admission.policy_reason,- )- return admission- if self.runtime_source == _RUNTIME_SOURCE_ARCHIVE:- admission, _operation = await asyncio.to_thread(- self._attempt_managed_install,- force=self.force_install,- offline=self.offline,- automatic=True,+ if not self.force_install and self._managed_command:+ return self._publish_install_availability(command=self._managed_command)+ if (+ not self.force_install+ and self.runtime_source != _RUNTIME_SOURCE_ARCHIVE+ and not (self.runtime_source == _RUNTIME_SOURCE_MANIFEST and self.manifest_url)+ ):+ command = await asyncio.to_thread(+ self._safe_installed_managed_runtime_command,+ offline=True,)- if admission.command:- return admission- command = self._installed_archive_runtime_command()- if command:- return self._publish_install_availability(- command=command,- policy_reason=admission.policy_reason,- )- if self._managed_command:- return self._publish_install_availability(- command=self._managed_command,- policy_reason=admission.policy_reason,- )- else:- managed = self._managed_bin_path()- resolved = _resolve_executable_path(managed)- if resolved:- return self._publish_install_availability(command=[resolved])- if self._managed_command:- return self._publish_install_availability(command=self._managed_command)- if self.runtime_source == _RUNTIME_SOURCE_GITHUB:- command = self._installed_github_runtime_command()if command:return self._publish_install_availability(command=command)admission, _operation = await asyncio.to_thread(self._attempt_managed_install,force=self.force_install,offline=self.offline,- automatic=True,+ automatic=automatic,)return admission- async def _resolve_managed_command(self) -> list[str] | None:- availability = await self._resolve_managed_availability()+ async def _resolve_managed_command(self, *, automatic: bool = True) -> list[str] | None:+ availability = await self._resolve_managed_availability(automatic=automatic)return availability.commanddef _attempt_managed_install(@@ -892,14 +1136,124 @@ class ShowRuntimeManager:*,force: bool,offline: bool,- automatic: bool = False,+ automatic: bool,) -> tuple[ShowRuntimeAvailability, _ShowRuntimeOperationOutcome]:+ admission: ShowRuntimeAvailability | None = None+ operation: _ShowRuntimeOperationOutcome | None = None+ pending_exception: BaseException | None = None+ stack: contextlib.ExitStack | None = None+ try:+ self._install_evidence = None+ self._download_error = None+ stack = contextlib.ExitStack()+ admission = self._availability+ operation = _ShowRuntimeOperationOutcome(+ _ShowRuntimeOperationState.NOT_APPLICABLE,+ admission.reason or "runtime_unavailable",+ )+ preflight = self._managed_install_preflight(+ force=force,+ automatic=automatic,+ )+ if preflight is not None:+ admission, operation = preflight+ else:+ acquired, guard_reason = stack.enter_context(self._install_guard_locked())+ if not acquired:+ command = None if force else self._safe_installed_managed_runtime_command(offline=offline)+ if command:+ admission = self._publish_install_availability(command=command)+ operation = _ShowRuntimeOperationOutcome(+ _ShowRuntimeOperationState.COMPLETED,+ None,+ )+ else:+ reason = guard_reason or "runtime_install_guard_unavailable"+ admission = self._publish_install_availability(+ install_reason=reason,+ )+ operation = _ShowRuntimeOperationOutcome(+ _ShowRuntimeOperationState.NOT_APPLICABLE,+ reason,+ )+ else:+ preflight = self._managed_install_preflight(+ force=force,+ automatic=automatic,+ )+ if preflight is not None:+ admission, operation = preflight+ else:+ raw_attempt = self._install_managed_runtime_locked(+ force=force,+ offline=offline,+ )+ attempt = (+ raw_attempt+ if isinstance(raw_attempt, _ManagedInstallAttempt)+ else _ManagedInstallAttempt(+ raw_attempt,+ None if raw_attempt else self._install_reason or "runtime_install_failed",+ )+ )+ if attempt.command:+ admission = self._publish_install_availability(command=attempt.command)+ operation = _ShowRuntimeOperationOutcome(+ _ShowRuntimeOperationState.COMPLETED,+ None,+ )+ else:+ reason = attempt.operation_reason or "runtime_install_failed"+ installed_command = self._safe_installed_managed_runtime_command(offline=True)+ admission = (+ self._publish_install_availability(command=installed_command)+ if installed_command+ else self._publish_install_availability(install_reason=reason)+ )+ operation = _ShowRuntimeOperationOutcome(+ _ShowRuntimeOperationState.FAILED,+ reason,+ )+ except OSError:+ reason = self._install_reason or "runtime_install_failed"+ installed_command = self._safe_installed_managed_runtime_command(offline=True)+ admission = (+ self._publish_install_availability(command=installed_command)+ if installed_command+ else self._publish_install_availability(install_reason=reason)+ )+ operation = _ShowRuntimeOperationOutcome(+ _ShowRuntimeOperationState.FAILED,+ reason,+ )+ logger.exception("Show Runtime install admission raised")+ except BaseException as exc:+ pending_exception = exc+ finally:+ if admission is None or operation is None:+ admission = self._availability+ operation = _ShowRuntimeOperationOutcome(+ _ShowRuntimeOperationState.NOT_APPLICABLE,+ admission.reason or "runtime_unavailable",+ )+ if stack is not None:+ stack.close()+ if pending_exception is not None:+ raise pending_exception+ return admission, operation++ def _managed_install_preflight(+ self,+ *,+ force: bool,+ automatic: bool,+ ) -> tuple[ShowRuntimeAvailability, _ShowRuntimeOperationOutcome] | None:if self._command_explicit:- command = _resolve_command(self.command)- availability = self._publish_install_availability(- command=command,- install_reason=None if command else "runtime_command_missing",+ availability = self._publish_explicit_command_availability(+ self._resolve_explicit_command_availability())+ command = availability.command+ reason = availability.reasonif force:operation = _ShowRuntimeOperationOutcome(_ShowRuntimeOperationState.NOT_APPLICABLE,@@ -913,7 +1267,7 @@ class ShowRuntimeManager:else:operation = _ShowRuntimeOperationOutcome(_ShowRuntimeOperationState.FAILED,- "runtime_command_missing",+ reason or "runtime_command_missing",)return availability, operationskipped_reason = self._managed_install_opt_out_reason(automatic=automatic)@@ -926,97 +1280,46 @@ class ShowRuntimeManager:availability = self._publish_install_availability(command=self._managed_command)operation = _ShowRuntimeOperationOutcome(_ShowRuntimeOperationState.COMPLETED, None)return availability, operation- if automatic and not force and self._install_attempted:- reason = self._install_reason or "runtime_install_failed"- availability = self._publish_install_availability(install_reason=reason)- operation = _ShowRuntimeOperationOutcome(- _ShowRuntimeOperationState.FAILED,- reason,- )- return availability, operation-- with self._install_guard_locked() as (acquired, guard_reason):- if not acquired:- command = None if force else self._installed_managed_runtime_command(offline=offline)- if command:- availability = self._publish_install_availability(command=command)- operation = _ShowRuntimeOperationOutcome(- _ShowRuntimeOperationState.COMPLETED,- None,- )- return availability, operation- reason = guard_reason or "runtime_install_guard_unavailable"- availability = self._publish_install_availability(install_reason=reason)- operation = _ShowRuntimeOperationOutcome(- _ShowRuntimeOperationState.FAILED,- reason,- )- return availability, operation-- skipped_reason = self._managed_install_opt_out_reason(automatic=automatic)- if skipped_reason:- return self._publish_policy_skip(skipped_reason), _ShowRuntimeOperationOutcome(- _ShowRuntimeOperationState.NOT_APPLICABLE,- skipped_reason,- )- if self._managed_command and not force:- availability = self._publish_install_availability(command=self._managed_command)- operation = _ShowRuntimeOperationOutcome(- _ShowRuntimeOperationState.COMPLETED,- None,- )- return availability, operation- if automatic and not force and self._install_attempted:- reason = self._install_reason or "runtime_install_failed"- availability = self._publish_install_availability(install_reason=reason)- operation = _ShowRuntimeOperationOutcome(- _ShowRuntimeOperationState.FAILED,- reason,- )- return availability, operation-- if automatic:- self._install_attempted = True- raw_attempt = self._install_managed_runtime_locked(- force=force,- offline=offline,- automatic=automatic,- )- attempt = (- raw_attempt- if isinstance(raw_attempt, _ManagedInstallAttempt)- else _ManagedInstallAttempt(- raw_attempt,- None if raw_attempt else self._install_reason or "runtime_install_failed",- )- )- if attempt.command:- availability = self._publish_install_availability(command=attempt.command)- operation = _ShowRuntimeOperationOutcome(- _ShowRuntimeOperationState.COMPLETED,- None,- )- return availability, operation- reason = attempt.operation_reason- installed_command = self._installed_managed_runtime_command(offline=True)- availability = (- self._publish_install_availability(command=installed_command)- if installed_command- else self._publish_install_availability(install_reason=reason)- )- operation = _ShowRuntimeOperationOutcome(- _ShowRuntimeOperationState.FAILED,- reason,- )- return availability, operation+ return Nonedef _managed_install_opt_out_reason(self, *, automatic: bool) -> str | None:- if automatic and _env_flag_enabled("VIBE_INSTALL_SKIP_SHOW_RUNTIME", default=False):+ if automatic and _env_flag_enabled(+ "VIBE_INSTALL_SKIP_SHOW_RUNTIME",+ default=False,+ ):return "VIBE_INSTALL_SKIP_SHOW_RUNTIME"if automatic and not self.auto_install:return "VIBE_SHOW_RUNTIME_AUTO_INSTALL"return None+ def _complete_runtime_start_admission(+ self,+ availability: ShowRuntimeAvailability,+ operation: _ShowRuntimeOperationOutcome,+ *,+ base_url: str | None,+ ) -> ShowRuntimeAvailability:+ """Publish exactly one start outcome before an admission can leave."""+ published = availability+ if operation.state is _ShowRuntimeOperationState.COMPLETED:+ if not base_url:+ raise AssertionError("completed Show Runtime start admission requires a base URL")+ self._base_url = base_url+ published = self._publish_runtime_availability(+ ShowRuntimeServingState.SERVING,+ base_url,+ )+ elif operation.state is _ShowRuntimeOperationState.FAILED:+ try:+ self.stop()+ except OSError: # pragma: no cover - process cleanup must not hide the outcome+ logger.warning("Show Runtime start cleanup failed", exc_info=True)+ published = self._publish_runtime_availability(+ ShowRuntimeServingState.START_FAILED,+ runtime_reason=operation.reason,+ )+ return published+def _publish_policy_skip(self, reason: str) -> ShowRuntimeAvailability:if self._managed_command:return self._publish_install_availability(command=self._managed_command, policy_reason=reason)@@ -1027,7 +1330,7 @@ class ShowRuntimeManager:install_state=(ShowRuntimeInstallState.INSTALLED if disk_install else ShowRuntimeInstallState.ABSENT),policy_reason=reason,)- command = self._installed_managed_runtime_command(offline=True)+ command = self._safe_installed_managed_runtime_command(offline=True)return self._publish_install_availability(command=command, policy_reason=reason)def _publish_install_availability(@@ -1037,17 +1340,28 @@ class ShowRuntimeManager:install_state: ShowRuntimeInstallState | None = None,policy_reason: str | None = None,install_reason: str | None = None,+ install_failure_class: ShowRuntimeFailureClass | None = None,) -> ShowRuntimeAvailability:+ install_evidence = (+ self._install_evidence+ if install_reason is not None and self._install_reason == install_reason+ else None+ )if command:self._managed_command = command- self._install_reason = None- else:+ self._install_evidence = None+ elif install_reason is not None and install_evidence is None:self._install_reason = install_reason+ install_evidence = self._install_evidence+ elif install_reason is None:+ self._install_evidence = Noneavailability = ShowRuntimeAvailability.from_install(command=command,install=install_state,policy_reason=policy_reason,install_reason=install_reason,+ install_evidence=install_evidence,+ install_failure_class=install_failure_class,)self._availability = availabilityreturn availability@@ -1063,6 +1377,11 @@ class ShowRuntimeManager:install = self._availability.installif command:install = ShowRuntimeInstallState.INSTALLED+ runtime_evidence = ShowRuntimeFailureEvidence(+ ShowRuntimeFailureDimension.RUNTIME,+ runtime_reason,+ )+ runtime_failure_class = classify_show_runtime_failure(runtime_evidence) if runtime_reason else Noneavailability = replace(self._availability,install=install,@@ -1070,6 +1389,8 @@ class ShowRuntimeManager:runtime=runtime,base_url=base_url,runtime_reason=runtime_reason,+ runtime_failure_class=runtime_failure_class,+ runtime_recovery_action=(show_runtime_recovery_action(runtime_evidence) if runtime_reason else None),)self._availability = availabilityreturn availability@@ -1102,6 +1423,7 @@ class ShowRuntimeManager:command=None,install_reason=None,install_failure_class=None,+ install_recovery_action=None,)try:if os.path.lexists(path):@@ -1120,7 +1442,6 @@ class ShowRuntimeManager:*,force: bool,offline: bool,- automatic: bool = False,) -> _ManagedInstallAttempt:command: list[str] | Noneif self.runtime_source == _RUNTIME_SOURCE_MANIFEST:@@ -1156,6 +1477,17 @@ class ShowRuntimeManager:return [resolved] if resolved else Nonereturn None+ def _safe_installed_managed_runtime_command(self, *, offline: bool) -> list[str] | None:+ evidence = self._install_evidence+ download_error = self._download_error+ try:+ return self._installed_managed_runtime_command(offline=offline)+ except (OSError, ValueError):+ return None+ finally:+ self._install_evidence = evidence+ self._download_error = download_error+def _clean_after_managed_install(self, command: list[str]) -> None:try:if self.runtime_source == _RUNTIME_SOURCE_MANIFEST:@@ -1163,9 +1495,7 @@ class ShowRuntimeManager:packaged = self.manifest_path is None and self.manifest_url is Noneremoved = self._clean_manifest_install_dirs(keep_previous=_MANAGED_RUNTIME_ROLLBACK_INSTALLS,- manifest_source=(- _PACKAGED_RUNTIME_MANIFEST_SOURCE if packaged else _CUSTOM_MANIFEST_LINEAGE- ),+ manifest_source=(_PACKAGED_RUNTIME_MANIFEST_SOURCE if packaged else _CUSTOM_MANIFEST_LINEAGE),protected_install_dirs=protected_install_dirs,)if removed:@@ -1182,15 +1512,20 @@ class ShowRuntimeManager:logger.warning("Failed to clean stale managed Show Runtime installs", exc_info=True)def status(self, *, offline: bool | None = None) -> dict[str, Any]:- configured_command = _resolve_command(self.command) if self._command_explicit else None+ explicit_availability = (+ self._resolve_explicit_command_availability()+ if self._command_explicit+ else None+ )+ configured_command = explicit_availability.command if explicit_availability else Nonedisk_install = (self._persisted_manifest_disk_install()- if not configured_command and self.runtime_source == _RUNTIME_SOURCE_MANIFEST+ if explicit_availability is None and self.runtime_source == _RUNTIME_SOURCE_MANIFESTelse None)manifest = (self._load_runtime_manifest(offline=offline)- if self.runtime_source == _RUNTIME_SOURCE_MANIFEST+ if explicit_availability is None and self.runtime_source == _RUNTIME_SOURCE_MANIFESTelse None)platform_tag = _runtime_platform_tag()@@ -1204,9 +1539,12 @@ class ShowRuntimeManager:installed_runtime_version: str | None = Noneinstalled_matches: bool | None = Nonegithub_source_status: dict[str, Any] | None = None- installed = configured_command is not None+ installed = (+ explicit_availability is not None+ and explicit_availability.install is ShowRuntimeInstallState.INSTALLED+ )manifest_status = _manifest_status_payload(manifest)- if not configured_command and self.runtime_source == _RUNTIME_SOURCE_MANIFEST:+ if explicit_availability is None and self.runtime_source == _RUNTIME_SOURCE_MANIFEST:if disk_install:installed = Trueinstalled_dir = disk_install.install_dir@@ -1229,7 +1567,7 @@ class ShowRuntimeManager:installed_command = self._manifest_runtime_command(candidate, node)if installed_command:break- elif not configured_command and self.runtime_source == _RUNTIME_SOURCE_ARCHIVE:+ elif explicit_availability is None and self.runtime_source == _RUNTIME_SOURCE_ARCHIVE:installed_dir = self._archive_install_dir()installed_command = self._archive_runtime_command(installed_dir, node or ["node"])installed = installed_command is not None@@ -1241,24 +1579,30 @@ class ShowRuntimeManager:"sha256": None,"size": None,}- elif not configured_command and self.runtime_source == _RUNTIME_SOURCE_GITHUB:+ elif explicit_availability is None and self.runtime_source == _RUNTIME_SOURCE_GITHUB:installed_dir = self._github_source_dir()installed_command = self._github_runtime_command(installed_dir, node or ["node"])installed = installed_command is not Nonegithub_source_status = self._github_source_status(installed_dir)- elif not configured_command and self.runtime_source == _RUNTIME_SOURCE_NPM:+ elif explicit_availability is None and self.runtime_source == _RUNTIME_SOURCE_NPM:managed = _resolve_executable_path(self._managed_bin_path())installed_command = [managed] if managed else Noneinstalled = installed_command is not Noneif installed and manifest is not None and archive is not None and installed_matches is not True:installed_matches = False- install_payload = ShowRuntimeAvailability.from_install(- command=installed_command,- install=(ShowRuntimeInstallState.INSTALLED if installed else ShowRuntimeInstallState.ABSENT),- install_dir=installed_dir if installed else None,- install_runtime_version=installed_runtime_version,- install_matches_manifest=installed_matches,- ).as_payload()["install"]+ if explicit_availability is not None:+ status_availability = explicit_availability+ else:+ status_availability = ShowRuntimeAvailability.from_install(+ command=installed_command,+ install=(ShowRuntimeInstallState.INSTALLED if installed else ShowRuntimeInstallState.ABSENT),+ install_dir=installed_dir if installed else None,+ install_runtime_version=installed_runtime_version,+ install_matches_manifest=installed_matches,+ )+ status_payload = status_availability.as_payload()+ install_payload = status_payload["install"]+ runtime_payload = status_payload["runtime"]return {"provider": self.runtime_source,"platform": platform_tag,@@ -1270,14 +1614,10 @@ class ShowRuntimeManager:"archive": archive_status or _archive_status_payload(archive),"github_source": github_source_status,"install": install_payload,- "runtime": {- "state": ShowRuntimeServingState.UNCHECKED.value,- "reason": None,- "base_url": None,- },+ "runtime": runtime_payload,"command": installed_command,- "reason": self._install_reason,- "download_error": self._download_error,+ "reason": explicit_availability.reason if explicit_availability else self._install_reason,+ "download_error": None if explicit_availability else self._download_error,}def probe_archive_reachability(self, *, timeout: float = 10.0) -> dict[str, Any]:@@ -2417,28 +2757,6 @@ class ShowRuntimeManager:except Exception:logger.warning("Failed to release Show Runtime install guard", exc_info=True)- def _reuse_verified_manifest_command(self, *, offline: bool | None = None) -> list[str] | None:- """Best-effort read-only fallback: reuse a verified installed runtime."""- try:- node = _resolve_node_command()- manifest = self._load_runtime_manifest(offline=offline)- if not node or not manifest:- return None- # Mirror the normal install path: an unsupported Node version must- # not be reported as a usable runtime.- if not self._manifest_node_supported(node, manifest):- return None- archive = self._manifest_archive_for_platform(manifest)- if not archive:- return None- command = self._verified_manifest_runtime_command_for_manifest(manifest, archive, node)- return self._managed_install_operation_command(- command,- replacement_required=False,- )- except Exception:- return None-def _install_manifest_runtime_locked(self, *, force: bool, offline: bool) -> list[str] | None:node = _resolve_node_command()if not node:@@ -2471,7 +2789,11 @@ class ShowRuntimeManager:verified_existing_command,replacement_required=False,)- archive_path = self._resolve_manifest_archive(archive, offline=offline)+ archive_path = self._resolve_manifest_archive(+ archive,+ offline=offline,+ provenance=("packaged" if manifest.source == _PACKAGED_RUNTIME_MANIFEST_SOURCE else "configured"),+ )if not archive_path:return self._managed_install_operation_command(verified_existing_command,@@ -2523,11 +2845,17 @@ class ShowRuntimeManager:def _load_runtime_manifest(self, *, offline: bool | None = None) -> ShowRuntimeManifest | None:payload: bytes | None = Nonesource = ""+ provenance = "configured" if self.manifest_path or self.manifest_url else "packaged"if self.manifest_path:- if not self.manifest_path.exists():- self._install_reason = "runtime_manifest_missing"+ try:+ exists = self.manifest_path.exists()+ payload = self.manifest_path.read_bytes() if exists else None+ except OSError:+ self._record_install_failure("runtime_manifest_invalid", provenance=provenance)+ return None+ if payload is None:+ self._record_install_failure("runtime_manifest_missing", provenance=provenance)return None- payload = self.manifest_path.read_bytes()source = str(self.manifest_path)elif self.manifest_url:if self.offline if offline is None else offline:@@ -2542,18 +2870,25 @@ class ShowRuntimeManager:source = self.manifest_urlexcept Exception as exc:logger.exception("Failed to download Show Runtime manifest from %s", self.manifest_url)- self._install_reason = "runtime_manifest_download_failed"- self._download_error = _runtime_download_error(exc, self.manifest_url)+ self._record_download_failure(+ "runtime_manifest_download_failed",+ exc,+ self.manifest_url,+ provenance="configured",+ )return Noneelse:try:resource = package_resources.files("vibe").joinpath(_RUNTIME_MANIFEST_RESOURCE)except Exception:resource = None- if resource is None or not resource.is_file():- self._install_reason = "runtime_manifest_missing"+ try:+ payload = resource.read_bytes() if resource is not None and resource.is_file() else None+ except OSError:+ payload = None+ if payload is None:+ self._record_install_failure("runtime_manifest_missing", provenance=provenance)return None- payload = resource.read_bytes()source = _PACKAGED_RUNTIME_MANIFEST_SOURCEdigest = hashlib.sha256(payload).hexdigest()try:@@ -2578,10 +2913,10 @@ class ShowRuntimeManager:source=source,)except Exception:- self._install_reason = "runtime_manifest_invalid"+ self._record_install_failure("runtime_manifest_invalid", provenance=provenance)return Noneif manifest.schema_version != 1 or not manifest.runtime_version or not manifest.archives:- self._install_reason = "runtime_manifest_invalid"+ self._record_install_failure("runtime_manifest_invalid", provenance=provenance)return Nonereturn manifest@@ -2602,7 +2937,13 @@ class ShowRuntimeManager:return Nonereturn archive- def _resolve_manifest_archive(self, archive: ShowRuntimeArchive, *, offline: bool | None = None) -> Path | None:+ def _resolve_manifest_archive(+ self,+ archive: ShowRuntimeArchive,+ *,+ offline: bool | None = None,+ provenance: str,+ ) -> Path | None:cached = self.runtime_dir / "downloads" / f"{archive.sha256}.tgz"if cached.exists() and self._downloaded_archive_matches(cached, archive):self._download_error = None@@ -2632,8 +2973,12 @@ class ShowRuntimeManager:except Exception as exc:logger.exception("Failed to download Show Runtime archive from %s", archive.url)tmp_path.unlink(missing_ok=True)- self._install_reason = "runtime_archive_download_failed"- self._download_error = _runtime_download_error(exc, archive.url)+ self._record_download_failure(+ "runtime_archive_download_failed",+ exc,+ archive.url,+ provenance=provenance,+ )return Nonedef _downloaded_archive_matches(self, path: Path, archive: ShowRuntimeArchive) -> bool:@@ -2844,18 +3189,21 @@ class ShowRuntimeManager:if self.archive_path:if self.archive_path.exists():return self.archive_path- self._install_reason = "runtime_archive_missing"+ self._record_install_failure("runtime_archive_missing", provenance="configured")return Nonepackaged = self._copy_packaged_runtime_archive()if packaged:return packagedif not self.archive_url:- self._install_reason = "runtime_archive_missing"+ self._record_install_failure("runtime_archive_missing", provenance="packaged")return Noneif self.offline if offline is None else offline:self._install_reason = "runtime_archive_unavailable_offline"return None- return self._download_runtime_archive(self.archive_url)+ return self._download_runtime_archive(+ self.archive_url,+ provenance=self._archive_url_provenance,+ )def _copy_packaged_runtime_archive(self) -> Path | None:try:@@ -2870,7 +3218,7 @@ class ShowRuntimeManager:shutil.copyfileobj(source, destination)return target- def _download_runtime_archive(self, archive_url: str) -> Path | None:+ def _download_runtime_archive(self, archive_url: str, *, provenance: str) -> Path | None:target = self.runtime_dir / "downloads" / _runtime_archive_name()target.parent.mkdir(parents=True, exist_ok=True)try:@@ -2883,8 +3231,12 @@ class ShowRuntimeManager:self._download_error = Noneexcept Exception as exc:logger.exception("Failed to download prebuilt Show Runtime from %s", archive_url)- self._install_reason = "runtime_archive_download_failed"- self._download_error = _runtime_download_error(exc, archive_url)+ self._record_download_failure(+ "runtime_archive_download_failed",+ exc,+ archive_url,+ provenance=provenance,+ )return Nonereturn target@@ -2958,8 +3310,12 @@ class ShowRuntimeManager: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")+ try:+ git = _resolve_command("git")+ npm = _resolve_command("npm")+ except (OSError, ValueError):+ git = None+ npm = Noneif not git:self._install_reason = "runtime_git_missing"return self._github_install_attempt(@@ -3112,7 +3468,10 @@ class ShowRuntimeManager:def _install_npm_runtime(self, *, force: bool | None = None) -> list[str] | None:replacement_required = self.force_install if force is None else force- npm = _resolve_command("npm")+ try:+ npm = _resolve_command("npm")+ except (OSError, ValueError):+ npm = Noneif not npm:self._install_reason = "runtime_npm_missing"return self._managed_install_operation_command(@@ -3671,9 +4030,12 @@ def _resolve_command(command: str) -> list[str] | None:def _resolve_node_command() -> list[str] | None:configured = os.environ.get("VIBE_SHOW_RUNTIME_NODE_BIN")- if configured:- return _resolve_command(configured)- return _resolve_command("node")+ try:+ if configured:+ return _resolve_command(configured)+ return _resolve_command("node")+ except (OSError, ValueError):+ return Nonedef _resolve_executable_path(path: Path) -> str | None:diff --git a/core/show_runtime_failures.py b/core/show_runtime_failures.pyindex e3a544a92..995afb9c2 100644--- a/core/show_runtime_failures.py+++ b/core/show_runtime_failures.py@@ -1,5 +1,6 @@from __future__ import annotations+from dataclasses import dataclassfrom enum import Enum@@ -8,24 +9,396 @@ class ShowRuntimeFailureClass(str, Enum):PERMANENT = "permanent"CONFIGURED = "configured"CHECKSUM = "checksum"+ UNCLASSIFIED = "unclassified"-_TRANSIENT_FAILURES = frozenset(- {- "runtime_archive_download_failed",+class ShowRuntimeFailureDimension(str, Enum):+ POLICY = "policy"+ INSTALL = "install"+ RUNTIME = "runtime"+++class ShowRuntimeRecoveryAction(str, Enum):+ REPAIR = "repair"+ CHANGE_SETTING = "change_setting"+ NO_LOCAL_ACTION = "no_local_action"+++@dataclass(frozen=True)+class ShowRuntimeFailureEvidence:+ dimension: ShowRuntimeFailureDimension+ reason: str | None+ provenance: str | None = None+ retryable: bool | None = None+++@dataclass(frozen=True)+class ShowRuntimeFailureDeclaration:+ reason: str+ dimension: ShowRuntimeFailureDimension+ owning_artifact: str+ failure_class: ShowRuntimeFailureClass+ recovery_action: ShowRuntimeRecoveryAction+ user_owned: bool = False+ provenance: str | None = None+ retryable: bool | None = None+++_FAILURE_DECLARATION_ROWS = (+ # Policy owns these settings; the manager never reinterprets an install+ # or runtime token as a policy decision.+ ShowRuntimeFailureDeclaration(+ "VIBE_INSTALL_SKIP_SHOW_RUNTIME",+ ShowRuntimeFailureDimension.POLICY,+ "install-policy",+ ShowRuntimeFailureClass.CONFIGURED,+ ShowRuntimeRecoveryAction.CHANGE_SETTING,+ True,+ ),+ ShowRuntimeFailureDeclaration(+ "VIBE_SHOW_RUNTIME_AUTO_INSTALL",+ ShowRuntimeFailureDimension.POLICY,+ "install-policy",+ ShowRuntimeFailureClass.CONFIGURED,+ ShowRuntimeRecoveryAction.CHANGE_SETTING,+ True,+ ),+ ShowRuntimeFailureDeclaration(+ "runtime_unavailable",+ ShowRuntimeFailureDimension.RUNTIME,+ "runtime-admission",+ ShowRuntimeFailureClass.UNCLASSIFIED,+ ShowRuntimeRecoveryAction.REPAIR,+ ),+ ShowRuntimeFailureDeclaration(+ "runtime_proxy_failed",+ ShowRuntimeFailureDimension.RUNTIME,+ "runtime-request",+ ShowRuntimeFailureClass.UNCLASSIFIED,+ ShowRuntimeRecoveryAction.REPAIR,+ ),+ ShowRuntimeFailureDeclaration(+ "runtime_start_url_timeout",+ ShowRuntimeFailureDimension.RUNTIME,+ "runtime-start",+ ShowRuntimeFailureClass.UNCLASSIFIED,+ ShowRuntimeRecoveryAction.REPAIR,+ ),+ ShowRuntimeFailureDeclaration(+ "runtime_start_process_unavailable",+ ShowRuntimeFailureDimension.RUNTIME,+ "runtime-start",+ ShowRuntimeFailureClass.UNCLASSIFIED,+ ShowRuntimeRecoveryAction.REPAIR,+ ),+ ShowRuntimeFailureDeclaration(+ "runtime_start_health_timeout",+ ShowRuntimeFailureDimension.RUNTIME,+ "runtime-start",+ ShowRuntimeFailureClass.UNCLASSIFIED,+ ShowRuntimeRecoveryAction.REPAIR,+ ),+ ShowRuntimeFailureDeclaration(+ "runtime_start_attempt_failed",+ ShowRuntimeFailureDimension.RUNTIME,+ "runtime-start",+ ShowRuntimeFailureClass.UNCLASSIFIED,+ ShowRuntimeRecoveryAction.REPAIR,+ ),+ ShowRuntimeFailureDeclaration(+ "runtime_start_command_unavailable",+ ShowRuntimeFailureDimension.RUNTIME,+ "managed-runtime-command",+ ShowRuntimeFailureClass.UNCLASSIFIED,+ ShowRuntimeRecoveryAction.REPAIR,+ ),+ ShowRuntimeFailureDeclaration(+ "runtime_start_command_invalid",+ ShowRuntimeFailureDimension.RUNTIME,+ "explicit-runtime-command",+ ShowRuntimeFailureClass.CONFIGURED,+ ShowRuntimeRecoveryAction.CHANGE_SETTING,+ True,+ ),+ ShowRuntimeFailureDeclaration(+ "runtime_start_node_command_invalid",+ ShowRuntimeFailureDimension.RUNTIME,+ "node-configuration",+ ShowRuntimeFailureClass.CONFIGURED,+ ShowRuntimeRecoveryAction.CHANGE_SETTING,+ True,+ ),+ ShowRuntimeFailureDeclaration(+ "runtime_command_missing",+ ShowRuntimeFailureDimension.INSTALL,+ "explicit-runtime-command",+ ShowRuntimeFailureClass.CONFIGURED,+ ShowRuntimeRecoveryAction.CHANGE_SETTING,+ True,+ ),+ ShowRuntimeFailureDeclaration(+ "runtime_node_missing",+ ShowRuntimeFailureDimension.INSTALL,+ "node-installation",+ ShowRuntimeFailureClass.CONFIGURED,+ ShowRuntimeRecoveryAction.CHANGE_SETTING,+ True,+ ),+ ShowRuntimeFailureDeclaration(+ "runtime_node_unsupported",+ ShowRuntimeFailureDimension.INSTALL,+ "node-installation",+ ShowRuntimeFailureClass.CONFIGURED,+ ShowRuntimeRecoveryAction.CHANGE_SETTING,+ True,+ ),+ ShowRuntimeFailureDeclaration(+ "runtime_git_missing",+ ShowRuntimeFailureDimension.INSTALL,+ "git-installation",+ ShowRuntimeFailureClass.CONFIGURED,+ ShowRuntimeRecoveryAction.CHANGE_SETTING,+ True,+ ),+ ShowRuntimeFailureDeclaration(+ "runtime_npm_missing",+ ShowRuntimeFailureDimension.INSTALL,+ "npm-installation",+ ShowRuntimeFailureClass.CONFIGURED,+ ShowRuntimeRecoveryAction.CHANGE_SETTING,+ True,+ ),+ ShowRuntimeFailureDeclaration("runtime_install_already_running",+ ShowRuntimeFailureDimension.INSTALL,+ "install-admission",+ ShowRuntimeFailureClass.UNCLASSIFIED,+ ShowRuntimeRecoveryAction.REPAIR,+ ),+ ShowRuntimeFailureDeclaration(+ "runtime_install_guard_unavailable",+ ShowRuntimeFailureDimension.INSTALL,+ "install-admission",+ ShowRuntimeFailureClass.UNCLASSIFIED,+ ShowRuntimeRecoveryAction.REPAIR,+ ),+ ShowRuntimeFailureDeclaration("runtime_install_failed",+ ShowRuntimeFailureDimension.INSTALL,+ "managed-install",+ ShowRuntimeFailureClass.UNCLASSIFIED,+ ShowRuntimeRecoveryAction.REPAIR,+ ),+ ShowRuntimeFailureDeclaration(+ "runtime_install_missing_bin",+ ShowRuntimeFailureDimension.INSTALL,+ "managed-install",+ ShowRuntimeFailureClass.UNCLASSIFIED,+ ShowRuntimeRecoveryAction.REPAIR,+ ),+ ShowRuntimeFailureDeclaration(+ "runtime_manifest_missing",+ ShowRuntimeFailureDimension.INSTALL,+ "packaged-manifest",+ ShowRuntimeFailureClass.UNCLASSIFIED,+ ShowRuntimeRecoveryAction.REPAIR,+ provenance="packaged",+ ),+ ShowRuntimeFailureDeclaration(+ "runtime_manifest_missing",+ ShowRuntimeFailureDimension.INSTALL,+ "configured-manifest",+ ShowRuntimeFailureClass.CONFIGURED,+ ShowRuntimeRecoveryAction.CHANGE_SETTING,+ user_owned=True,+ provenance="configured",+ ),+ ShowRuntimeFailureDeclaration(+ "runtime_manifest_invalid",+ ShowRuntimeFailureDimension.INSTALL,+ "packaged-manifest",+ ShowRuntimeFailureClass.UNCLASSIFIED,+ ShowRuntimeRecoveryAction.REPAIR,+ provenance="packaged",+ ),+ ShowRuntimeFailureDeclaration(+ "runtime_manifest_invalid",+ ShowRuntimeFailureDimension.INSTALL,+ "configured-manifest",+ ShowRuntimeFailureClass.CONFIGURED,+ ShowRuntimeRecoveryAction.CHANGE_SETTING,+ user_owned=True,+ provenance="configured",+ ),+ ShowRuntimeFailureDeclaration(+ "runtime_manifest_download_failed",+ ShowRuntimeFailureDimension.INSTALL,+ "manifest-provider",+ ShowRuntimeFailureClass.TRANSIENT,+ ShowRuntimeRecoveryAction.REPAIR,+ ),+ ShowRuntimeFailureDeclaration("runtime_manifest_download_failed",- }+ ShowRuntimeFailureDimension.INSTALL,+ "configured-manifest-url",+ ShowRuntimeFailureClass.CONFIGURED,+ ShowRuntimeRecoveryAction.CHANGE_SETTING,+ user_owned=True,+ provenance="configured",+ retryable=False,+ ),+ ShowRuntimeFailureDeclaration(+ "runtime_manifest_unavailable_offline",+ ShowRuntimeFailureDimension.INSTALL,+ "offline-policy",+ ShowRuntimeFailureClass.CONFIGURED,+ ShowRuntimeRecoveryAction.CHANGE_SETTING,+ True,+ ),+ ShowRuntimeFailureDeclaration(+ "runtime_archive_missing",+ ShowRuntimeFailureDimension.INSTALL,+ "packaged-archive",+ ShowRuntimeFailureClass.UNCLASSIFIED,+ ShowRuntimeRecoveryAction.REPAIR,+ provenance="packaged",+ ),+ ShowRuntimeFailureDeclaration(+ "runtime_archive_missing",+ ShowRuntimeFailureDimension.INSTALL,+ "configured-archive",+ ShowRuntimeFailureClass.CONFIGURED,+ ShowRuntimeRecoveryAction.CHANGE_SETTING,+ user_owned=True,+ provenance="configured",+ ),+ ShowRuntimeFailureDeclaration(+ "runtime_archive_probe_not_applicable",+ ShowRuntimeFailureDimension.INSTALL,+ "archive-provider",+ ShowRuntimeFailureClass.UNCLASSIFIED,+ ShowRuntimeRecoveryAction.REPAIR,+ ),+ ShowRuntimeFailureDeclaration(+ "runtime_archive_probe_unsupported",+ ShowRuntimeFailureDimension.INSTALL,+ "archive-provider",+ ShowRuntimeFailureClass.UNCLASSIFIED,+ ShowRuntimeRecoveryAction.REPAIR,+ ),+ ShowRuntimeFailureDeclaration(+ "runtime_archive_url_unsupported",+ ShowRuntimeFailureDimension.INSTALL,+ "archive-provider",+ ShowRuntimeFailureClass.PERMANENT,+ ShowRuntimeRecoveryAction.CHANGE_SETTING,+ True,+ ),+ ShowRuntimeFailureDeclaration(+ "runtime_platform_unsupported",+ ShowRuntimeFailureDimension.INSTALL,+ "runtime-platform",+ ShowRuntimeFailureClass.PERMANENT,+ ShowRuntimeRecoveryAction.NO_LOCAL_ACTION,+ ),+ ShowRuntimeFailureDeclaration(+ "runtime_archive_download_failed",+ ShowRuntimeFailureDimension.INSTALL,+ "archive-provider",+ ShowRuntimeFailureClass.TRANSIENT,+ ShowRuntimeRecoveryAction.REPAIR,+ ),+ ShowRuntimeFailureDeclaration(+ "runtime_archive_download_failed",+ ShowRuntimeFailureDimension.INSTALL,+ "configured-archive-url",+ ShowRuntimeFailureClass.CONFIGURED,+ ShowRuntimeRecoveryAction.CHANGE_SETTING,+ user_owned=True,+ provenance="configured",+ retryable=False,+ ),+ ShowRuntimeFailureDeclaration(+ "runtime_archive_download_failed",+ ShowRuntimeFailureDimension.INSTALL,+ "packaged-archive-url",+ ShowRuntimeFailureClass.UNCLASSIFIED,+ ShowRuntimeRecoveryAction.REPAIR,+ provenance="packaged",+ retryable=False,+ ),+ ShowRuntimeFailureDeclaration(+ "runtime_archive_unavailable_offline",+ ShowRuntimeFailureDimension.INSTALL,+ "offline-policy",+ ShowRuntimeFailureClass.CONFIGURED,+ ShowRuntimeRecoveryAction.CHANGE_SETTING,+ True,+ ),+ ShowRuntimeFailureDeclaration(+ "runtime_archive_size_mismatch",+ ShowRuntimeFailureDimension.INSTALL,+ "archive-provider",+ ShowRuntimeFailureClass.UNCLASSIFIED,+ ShowRuntimeRecoveryAction.REPAIR,+ ),+ ShowRuntimeFailureDeclaration(+ "runtime_archive_checksum_mismatch",+ ShowRuntimeFailureDimension.INSTALL,+ "archive-provider",+ ShowRuntimeFailureClass.CHECKSUM,+ ShowRuntimeRecoveryAction.REPAIR,+ ),+ ShowRuntimeFailureDeclaration(+ "runtime_github_source_update_failed",+ ShowRuntimeFailureDimension.INSTALL,+ "github-provider",+ ShowRuntimeFailureClass.UNCLASSIFIED,+ ShowRuntimeRecoveryAction.REPAIR,+ ),+ ShowRuntimeFailureDeclaration(+ "runtime_source_unsupported",+ ShowRuntimeFailureDimension.INSTALL,+ "runtime-source-configuration",+ ShowRuntimeFailureClass.PERMANENT,+ ShowRuntimeRecoveryAction.CHANGE_SETTING,+ True,+ ),)+if len({(row.reason, row.provenance, row.retryable) for row in _FAILURE_DECLARATION_ROWS}) != len(+ _FAILURE_DECLARATION_ROWS+):+ raise RuntimeError("Show Runtime failure evidence must have one declaration")++SHOW_RUNTIME_FAILURE_DECLARATIONS = {+ (row.reason, row.provenance, row.retryable): row for row in _FAILURE_DECLARATION_ROWS+}+++def _failure_declaration(evidence: ShowRuntimeFailureEvidence) -> ShowRuntimeFailureDeclaration | None:+ keys = (+ (evidence.reason or "", evidence.provenance, evidence.retryable),+ (evidence.reason or "", evidence.provenance, None),+ (evidence.reason or "", None, evidence.retryable),+ (evidence.reason or "", None, None),+ )+ for key in dict.fromkeys(keys):+ declaration = SHOW_RUNTIME_FAILURE_DECLARATIONS.get(key)+ if declaration is not None and declaration.dimension is evidence.dimension:+ return declaration+ return None+++def classify_show_runtime_failure(evidence: ShowRuntimeFailureEvidence) -> ShowRuntimeFailureClass:+ """Classify only what the owning failure evidence can prove."""+ declaration = _failure_declaration(evidence)+ return declaration.failure_class if declaration else ShowRuntimeFailureClass.UNCLASSIFIED+-def classify_show_runtime_failure(reason: str | None) -> ShowRuntimeFailureClass:- """Classify an install outcome without deciding its retry policy."""- if reason == "runtime_archive_checksum_mismatch":- return ShowRuntimeFailureClass.CHECKSUM- if reason and reason.endswith("_unavailable_offline"):- return ShowRuntimeFailureClass.CONFIGURED- if reason in _TRANSIENT_FAILURES:- return ShowRuntimeFailureClass.TRANSIENT- return ShowRuntimeFailureClass.PERMANENT+def show_runtime_recovery_action(+ evidence: ShowRuntimeFailureEvidence,+) -> ShowRuntimeRecoveryAction:+ """Publish the user obligation proved by the owning failure dimension."""+ declaration = _failure_declaration(evidence)+ return declaration.recovery_action if declaration else ShowRuntimeRecoveryAction.REPAIRdiff --git a/docs/plans/show-runtime-availability.md b/docs/plans/show-runtime-availability.mdindex 8fecea147..c29ea9704 100644--- a/docs/plans/show-runtime-availability.md+++ b/docs/plans/show-runtime-availability.md@@ -500,25 +500,135 @@ serves a verified archive.stay undocumented until then, because `@avibe/show-runtime` is not on thepublic registry today.-### W4 — Bounded retry instead of a lifetime latch (repo: `avibe`)--Replace `_install_attempted` with the module's existing retry convention-(`_install_retry_deadline` / `_install_retry_attempt`, mirroring-`_capability_retry_deadline` and `_show_runtime_capability_retry_delay`), and-classify `_install_reason`:--- **transient** — `runtime_archive_download_failed`,- `runtime_manifest_download_failed`: exponential backoff, roughly 5 s → 5 min.-- **permanent** — `runtime_platform_unsupported`, `runtime_node_unsupported`,- `runtime_archive_checksum_mismatch`, `runtime_source_unsupported`,- `runtime_archive_url_unsupported`: stay latched.-- **configured** — `*_unavailable_offline`: neither retry nor latch.--Retries are request-driven; introduce no new background timer. Then ensure all-three opportunities actually attempt installation: installer-(`install.sh` `prepare_show_runtime`, `install.ps1` `Prepare-ShowRuntime`),-startup reconcile (`vibe/api.py` `reconcile_startup_dependencies`), and the-`/show/` request path.+### W4 — Truthful recovery evidence; bounded retry deferred (repo: `avibe`)++PR #1640 attempted to replace a lifetime latch with bounded automatic retry.+Nine reviewed implementation heads produced 28 findings and no clean pass. The+retry identity, trigger policy, budget, record, disposition, and pre-probe+mechanisms repeatedly generated fresh races and projection gaps. The review+breaker therefore froze that design. PR #1640 deletes the retry machinery without+replacement and keeps only the parts that converged: declared failure data,+structured evidence, typed transport errors, and truthful manual recovery. Issue+#1637 remains open for a separately designed bounded-retry change.++The retained rules are normative:++1. **No request-path health pre-probe.** If `_base_url` is set, `request()` uses+ that snapshot directly. A transport-level failure with no HTTP response is the+ detector and invalidates that snapshot under the admission lock only while both+ its URL and tracked process still match, so a delayed failure from an old process+ cannot invalidate its replacement. The next request then re-enters admission.+ An HTTP response, including a 5xx response from the sidecar, proves transport+ succeeded and does not invalidate the runtime. No await may occur between+ reading `_base_url` and selecting it for the request.+2. **Owning operations normalize only operational I/O.** Every command-resolution+ and runtime-metadata path converts `OSError` subclasses into typed failure+ evidence before returning to the UI, and request transport catches the specific+ `httpx` network exceptions it owns. Programming defects such as `TypeError` and+ `AttributeError` propagate unchanged. A malformed user command is input+ evidence, so command parsing converts it at the command-resolution boundary.+ Explicit-command resolution has one owner shared by startup admission, install+ preflight, and status. It returns an existing `ShowRuntimeAvailability` carrying+ either the resolved command or complete reason/class/action evidence. Only the+ explicit-configuration flag may mean "no override"; a parse failure may never be+ collapsed to `None`, because that would let status fall through to an unrelated+ managed provider and report a runtime that startup will refuse.+3. **Retry now renders its one expected page response.** One click performs exactly+ one fetch. A direct 2xx HTML response is rendered into the current document from+ a private script scope, so repeated recovery-page renders cannot collide on+ top-level bindings. A redirect, non-2xx response, or non-HTML response is never+ treated as page content and instead returns control to normal browser navigation;+ in particular, expired credentials navigate to login rather than rendering a 401+ JSON body. This corrects the earlier R7 rule, whose unconditional one-response+ rendering made authentication responses indistinguishable from page responses.++Install-lock contention remains `not_applicable`: another process owns progress,+so this caller did not run a provider. Recovery remains request-driven; no+background timer or automatic attempt budget exists in PR #1640.++**Installed runtimes are resolved before mutation when installed evidence proves+the selected input.** Startup admission first projects the shared explicit-command+owner when an override exists. Otherwise it reuses the in-memory managed command,+then performs one offline, read-only lookup for manifest, GitHub source, and npm.+A hit never enters provider installation. An absent runtime,+`force_install=True`, or a remote manifest enters mutating admission. Archive is+intentionally different: a configured local archive is new input, so the provider+attempts publication first and falls back to the installed archive only when that+attempt fails. The master regression test that replaces an old installed archive+with a changed local archive is the contract guard. Archive URL downloads after a+process restart are existing behavior tracked separately in issue #1657. This+boundary is independent of the deleted retry machinery.++**Failure classification is declared data and published by the evidence owner.**+Each `(reason, provenance, retryable)` key has one declaration carrying its+dimension, owning artifact, class, and user ownership. Provenance and retryability+are optional evidence discriminators; lookup prefers the fully measured key and+falls back to a less-specific declaration, while an undeclared outcome remains+unclassified and repairable. Classification and recovery action are total lookups+over that declaration. A configured manifest and the packaged+manifest may publish the same failure reason, but their provenance keeps the+user's change-setting obligation distinct from repair of packaged bytes. The same+rule applies to archives: a missing configured path is a user-owned setting error,+while absent packaged bytes remain repairable. An AST census derives this set from+every archive reason emitted under a positive `self.archive_path` guard and requires+configured and packaged declarations for each one; declaration coverage is not a+hand-written sibling list.++Download classification consumes the `retryable` fact already measured by+`dependency_error_details`. A retryable manifest or archive failure remains+transient and repairable. A non-retryable failure changes a setting only when its+URL provenance is configured; the same failure against packaged or default release+input remains repairable and makes no claim about user ownership. The evidence-key+census derives every field stored by the shared download-error owner and requires+each field either to participate in declaration selection or to appear once in the+explicitly irrelevant set. This census failed on `retryable` before the field was+plumbed, and it prevents a later discriminator from being silently dropped.++This is the final failure-classification fold change in PR #1640. Any later finding+in this class is filed and handled in a follow-up PR rather than re-entering this+branch. Install admission clears operation-local evidence before+any provider runs, so a later I/O failure cannot inherit an earlier operation's+reason, provenance, or download detail. A managed+command that disappears is runtime evidence owned by the managed artifact and is+not classified as a user configuration error; an explicit command failure remains+configured. The page consumes the published class and action and never rebuilds+either from a reason prefix or nearby state.++Every policy, install, and runtime payload is serialized by+`ShowRuntimeAvailability`. Status may select which availability it reports, but it+may not hand-build a partial dimension for one provider path. A module-wide AST+census rejects any dimension-shaped dictionary outside the serializer, so improving+one branch cannot leave its managed sibling on an older schema. Review attribution+uses behavior rather than line blame: a hoist or extraction may re-blame unchanged+bytes, so a head counts as introducing a finding only when the cited value or+behavior differs from its predecessor.++**Runtime transport is exception-closed for evidence.** `request()` and+`request_global()` share one manager-owned transport boundary. A transport+exception publishes reason, class, and recovery action through+`ShowRuntimeUnavailableError`; an explicit total deadline remains the distinct+`ShowRuntimeRequestTimeoutError`. The UI catches only those typed outcomes. Its+former fallback, which fabricated recovery facts for arbitrary exceptions, is+deleted. Unknown programming errors stay loud instead of acquiring evidence no+owner published.++**Manual recovery is truthful and authorized.** There are exactly three user+obligations the page can present: run a repair, change a setting or prerequisite+the owner controls, or accept that no local action can help. The recovery header+requests an explicit action; it never grants authority. Only the authenticated+instance owner is shown Retry now, while public and limited viewers receive a+manual reload action they can perform themselves.++The freeze chose deletion over extraction because the seam crosses fields inside+shared admission functions. Re-extracting the retained subset from master would+rewrite the same regions that produced the findings while discarding the review+history. Deleting the enumerated retry symbols is mechanically verifiable and+introduces no replacement state machine, class, or module-level table.+One late review finding was blamed to that deletion commit: its total status+boundary converted a malformed explicit command to `None` and discarded the+evidence needed to distinguish "not configured" from "configured incorrectly."+The forward stop condition was not violated by that stock finding, but the record+must not claim the deletion commit introduced zero defects.**Through one admission path.** This requirement was missing from the firstversion of this spec, and its absence produced four review findings across two@@ -530,7 +640,7 @@ method admits an install, and it owns all four of:`VIBE_INSTALL_SKIP_SHOW_RUNTIME`);2. serialization — one lock covering every provider, not just the manifestprovider's `_install_guard_locked`;-3. the retry classification above;+3. the failure classification and recovery evidence above;4. writing the resulting command into shared manager state, so a later callerreuses it instead of installing again.@@ -1085,7 +1195,7 @@ Note for expectation-setting: this fixes transient failures only. It would nothave helped a user who cannot reach `github.com` at all; that is W3.**Acceptance:** after a simulated download failure, a later `/show/` request-retries once the backoff expires and succeeds, with no service restart. A forced+can try again and succeed, with no service restart. A forcedrepair whose replacement package fails reports the repair as failed with its realreason, reports the old runtime as still installed, and leaves it on disk; astartability check that cannot reach a verdict refuses the reinstall instead of@@ -1117,8 +1227,16 @@ adopted as the managed baseline.- Split `SHOW_RUNTIME_RECOVERY_LOADING_DELAY_SECONDS` into two constants: thepage's loading-state delay and the node CLI's `--fallback-delay-seconds`.- Render a terminal failure immediately instead of after the 30 s delay.-- Poll so the page self-recovers once the runtime installs, without a manual- reload.+- Defer automatic polling to PR 2c′; PR 2c keeps a truthful manual recovery+ surface and an authenticated Retry-now action.++Recovery copy projects the user's obligation from published evidence. A repair+command is shown only when local repair can address the+failure; a deliberate policy opt-out names the setting to change; and an+unsupported platform states that no local repair or retry changes the fact. The+page never maps failure class to retry behavior. Install, runtime, and policy+publish their recovery action inside their own dimensions, with no flat+top-level mirror for a consumer to mispair.All user-visible strings go through `vibe/i18n/`.@@ -1134,12 +1252,10 @@ as a rule because the reduced signal looked adequate each time.inherits this, including `vibe doctor`'s repair verifier, which is what made ita finding here. A freshly started runtime must answer a request before itcounts as serving.-- The recovery page's poll decides whether to keep waiting by checking that it is- still the recovery page, not by comparing the current failure reason. A failure- that changes from transient to `checksum` or configured therefore keeps- displaying the old copy forever. The poll must carry the reason from the- admission outcome above and re-render when it changes, including into a- terminal state where polling stops.+- Automatic recovery is deferred to PR 2c′. Until then the recovery page offers a+ manual reload plus an authenticated owner-only Retry-now action. PR 2c′ may poll+ only from a manager-owned admission signal, never from a browser counter. Its+ design remains open in #1637 rather than being implied by PR #1640.**A probe proves only the state it was calibrated for.** The first attempt at thefix above reused `_healthy()` exactly as the already-running path calls it: one@@ -1310,7 +1426,8 @@ exposure predates these PRs and shipping the truthful row strictly reduces it.| 2b | W5 readiness proof | avibe | `ensure()` health-probes a fresh start; `doctor` inherits it. Independent of 2a. Bounded retry plus Doctor's three-state startability; claims nothing about replacement. || 2b′ | W4 replacement operation contract | avibe | What `prepare()` claims, what a provider must prove, install-state ownership, build provenance, and destructive cache/delegate boundaries. Split out of 2b after six findings-bearing heads; checkout ownership is not shipped here. || 2b″ | Protect the managed GitHub checkout | avibe | Replace master's unconditional checkout takeover with a three-valued decision that keeps undetermined ownership away from both checkout movement and build-evidence destruction. |-| 2c | W4 retry + W5 page | avibe | Retry classification and the recovery page/poll, on top of 2a's reason. |+| 2c | W4 evidence + W5 page | avibe | Declared failure classification, typed transport evidence, operational-I/O normalization, and an honest manual recovery page. Retry ownership was frozen and deleted. |+| 2c′ | Bounded automatic recovery | avibe | Open issue #1637. Design the bound separately before reintroducing any automatic poller or retry state. || 3 | W1 | vibe-show-runtime | Independent; effect appears at the next runtime release. || 4 | W3.1 | avibe | Source ladder. Valuable on its own — removes the single point of failure using only tiers that exist today. || 5 | W3.0 | vibe-show-runtime | Version scheme. Prerequisite for 6 and 7. Gate on owner confirmation. |@@ -1382,8 +1499,10 @@ real `~/.avibe`.- W3.3: the npm tarball's outer sha256 is *not* used for verification; the innerarchive is verified after extraction; the mirror base URL is used when theprimary registry is unreachable.-- W4: reason classification; backoff schedule; permanent reasons stay latched;- offline neither retries nor latches.+- W4: owner-published failure classification; typed transport evidence; one-fetch+ explicit recovery; failed replacement remains independent from runtime+ usability; local I/O is normalized into typed evidence. Bounded retry remains+ open in #1637.- W5: reason-specific copy; terminal failures render immediately; i18n coverage.**Pipeline tests**: extend `tests/test_show_runtime_manifest_packaging.py` withdiff --git a/tests/test_show_runtime_archive_cleanup.py b/tests/test_show_runtime_archive_cleanup.pyindex c236e971c..2560d0adc 100644--- a/tests/test_show_runtime_archive_cleanup.py+++ b/tests/test_show_runtime_archive_cleanup.py@@ -535,7 +535,11 @@ def test_install_guard_unavailable_falls_back_to_verified_install(tmp_path: Pathreal_open = os.openmonkeypatch.setattr(os, "open", _unwritable_open)- availability, operation = manager._attempt_managed_install(force=False, offline=True)+ availability, operation = manager._attempt_managed_install(+ force=False,+ offline=True,+ automatic=False,+ )command = availability.commandassert command is not None and command[-1].endswith("cli.js")@@ -672,7 +676,11 @@ def test_forced_prepare_fails_structured_when_guard_unavailable(tmp_path: Path,monkeypatch.setattr("os.open", _unwritable_open)- availability, operation = manager._attempt_managed_install(force=True, offline=True)+ availability, operation = manager._attempt_managed_install(+ force=True,+ offline=True,+ automatic=False,+ )command = availability.commandassert command is None@@ -680,11 +688,12 @@ def test_forced_prepare_fails_structured_when_guard_unavailable(tmp_path: Path,assert manager._install_reason == "runtime_install_guard_unavailable"-def test_lock_fallback_enforces_manifest_node_requirement(tmp_path: Path, monkeypatch) -> None:+def test_installed_manifest_command_enforces_node_requirement(tmp_path: Path, monkeypatch) -> None:from core import show_runtime as modulemonkeypatch.setattr(module, "_runtime_platform_tag", lambda: "test")monkeypatch.setattr(module, "_resolve_node_command", lambda: ["node"])+ monkeypatch.setattr(module, "_node_version", lambda _command: "18.0.0")manifest_payload = {"schema_version": 1,"runtime_version": "v2",@@ -721,18 +730,33 @@ def test_lock_fallback_enforces_manifest_node_requirement(tmp_path: Path, monkeycli_path.parent.mkdir(parents=True, exist_ok=True)cli_path.write_text("runtime", encoding="utf-8")- from storage.lock import MigrationFileLock+ command = manager._installed_manifest_runtime_command(offline=True)- def _unwritable_lock(self, *args, **kwargs):- raise OSError("read-only filesystem")+ # The installed files verify, but Node is below the manifest minimum, so+ # the installed-command resolver must not hand back an unusable command.+ assert command is None- monkeypatch.setattr(MigrationFileLock, "acquire", _unwritable_lock)- command = manager._reuse_verified_manifest_command()[email protected]("failure_type", [OSError, ValueError])+def test_policy_skip_normalizes_installed_command_resolution_errors(+ tmp_path: Path,+ monkeypatch,+ failure_type: type[Exception],+) -> None:+ manager = ShowRuntimeManager(+ runtime_dir=tmp_path / "show-runtime",+ runtime_source="archive",+ )- # The installed files verify, but Node is below the manifest minimum, so- # the fallback must not hand back an unusable command.- assert command is None+ def _fail(*, offline: bool):+ raise failure_type(f"cannot resolve installed command (offline={offline})")++ monkeypatch.setattr(manager, "_installed_managed_runtime_command", _fail)++ availability = manager._publish_policy_skip("VIBE_SHOW_RUNTIME_AUTO_INSTALL")++ assert availability.command is None+ assert availability.policy_reason == "VIBE_SHOW_RUNTIME_AUTO_INSTALL"def test_dry_run_planning_failure_returns_structured_report(tmp_path: Path, monkeypatch) -> None:diff --git a/tests/test_show_runtime_protocol.py b/tests/test_show_runtime_protocol.pyindex ca3539494..20d9cc3d1 100644--- a/tests/test_show_runtime_protocol.py+++ b/tests/test_show_runtime_protocol.py@@ -15,6 +15,7 @@ from core.show_runtime import (ShowRuntimeProtocolEnvelope,ShowRuntimeRequestTimeoutError,ShowRuntimeResult,+ ShowRuntimeUnavailableError,)@@ -108,7 +109,7 @@ def test_show_live_015_transient_probe_keeps_shared_request_live_and_retries(])- async def ensure():+ async def ensure(*, automatic=True):return ShowRuntimeResult(True, manager._base_url)async def probe(base_url):@@ -171,7 +172,7 @@ def test_show_runtime_request_accepts_per_call_timeout_without_changing_connect_captured_deadlines = []original_wait_for = asyncio.wait_for- async def ensure():+ async def ensure(*, automatic=True):return ShowRuntimeResult(True, manager._base_url)async def negotiate(_base_url):@@ -212,7 +213,10 @@ def test_show_runtime_request_accepts_per_call_timeout_without_changing_connect_assert captured_deadlines == ([] if timeout_seconds is None else [timeout_seconds])-def test_show_runtime_default_read_timeout_is_not_converted(monkeypatch, tmp_path):+def test_show_runtime_default_read_timeout_is_owner_published_not_request_deadline(+ monkeypatch,+ tmp_path,+):manager = _manager(tmp_path)manager._base_url = "http://127.0.0.1:4173"read_timeout = httpx.ReadTimeout(@@ -220,7 +224,7 @@ def test_show_runtime_default_read_timeout_is_not_converted(monkeypatch, tmp_patrequest=httpx.Request("GET", manager._base_url),)- async def ensure():+ async def ensure(*, automatic=True):return ShowRuntimeResult(True, manager._base_url)async def negotiate(_base_url):@@ -245,10 +249,13 @@ def test_show_runtime_default_read_timeout_is_not_converted(monkeypatch, tmp_patmonkeypatch.setattr(show_runtime.asyncio, "wait_for", unexpected_wait_for)envelope = ShowRuntimeProtocolEnvelope(ShowRuntimeContext.PRIVATE)- with pytest.raises(httpx.ReadTimeout) as raised:+ with pytest.raises(ShowRuntimeUnavailableError) as raised:asyncio.run(manager.request("GET", "/sessions/ses/app/src/main.tsx", envelope=envelope))- assert raised.value is read_timeout+ assert raised.value.reason == "runtime_proxy_failed"+ assert raised.value.failure_class.value == "unclassified"+ assert raised.value.__cause__ is read_timeout+ assert manager._base_url is Nonedef test_show_runtime_explicit_read_timeout_is_converted(monkeypatch, tmp_path):@@ -259,7 +266,7 @@ def test_show_runtime_explicit_read_timeout_is_converted(monkeypatch, tmp_path):request=httpx.Request("GET", manager._base_url),)- async def ensure():+ async def ensure(*, automatic=True):return ShowRuntimeResult(True, manager._base_url)async def negotiate(_base_url):@@ -291,13 +298,14 @@ def test_show_runtime_explicit_read_timeout_is_converted(monkeypatch, tmp_path):)assert raised.value.__cause__ is read_timeout+ assert manager._base_url is Nonedef test_show_runtime_request_enforces_timeout_as_total_deadline(monkeypatch, tmp_path):manager = _manager(tmp_path)manager._base_url = "http://127.0.0.1:4173"- async def ensure():+ async def ensure(*, automatic=True):return ShowRuntimeResult(True, manager._base_url)async def negotiate(_base_url):@@ -327,6 +335,7 @@ def test_show_runtime_request_enforces_timeout_as_total_deadline(monkeypatch, tmtimeout_seconds=0.01,))+ assert manager._base_url is Nonedef test_show_live_014_capability_cache_resets_with_process_base_and_manager_lifetime(@@ -347,7 +356,7 @@ def test_show_live_014_capability_cache_resets_with_process_base_and_manager_lif])- async def ensure():+ async def ensure(*, automatic=True):return ShowRuntimeResult(True, manager._base_url)async def probe(base_url):diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.pyindex 2e53c0c96..3c017f03e 100644--- a/tests/test_ui_show_pages.py+++ b/tests/test_ui_show_pages.py@@ -1,32 +1,42 @@+import astimport asyncioimport base64+import errnoimport hashlib+import inspectimport ioimport jsonimport os+import reimport shutilimport socketimport sslimport structimport subprocessimport tarfile+import textwrapimport threadingimport urllib.errorimport urllib.parseimport zlib+from contextlib import nullcontextfrom pathlib import Pathfrom types import SimpleNamespace-from unittest.mock import patch+from unittest.mock import AsyncMock, patchimport httpximport pytest+import core.dependency_network as dependency_network+import core.show_runtime as show_runtime+import core.show_runtime_failures as show_runtime_failures_modulefrom starlette.websockets import WebSocketDisconnectfrom config import paths+from core import show_pages as show_pages_modulefrom core.show_pages import (SHOW_ACCESS_ENTRY_VALUE_MAX_LENGTH,SHOW_ACCESS_VISITOR_GROUP_MAX_COUNT,- SHOW_RUNTIME_RECOVERY_LOADING_DELAY_SECONDS,+ SHOW_PAGE_RUNTIME_RECOVERY_LOADING_DELAY_SECONDS,VISIBILITIES,ShowPageError,ShowPageStore,@@ -36,15 +46,28 @@ from core.show_pages import (show_public_event_write_token,)from core.show_runtime import (+ SHOW_RUNTIME_CLI_FALLBACK_DELAY_SECONDS,ShowRuntimeContext,ShowRuntimeManager,+ ShowRuntimeProtocolEnvelope,ShowRuntimeRequestTimeoutError,+ ShowRuntimeServingState,+ ShowRuntimeUnavailableError,ShowRuntimeWebSocketTarget,_runtime_download_error,_runtime_platform_tag,_safe_extract_tar,set_show_runtime_manager_for_tests,)+from core.show_runtime_failures import (+ SHOW_RUNTIME_FAILURE_DECLARATIONS,+ ShowRuntimeFailureClass,+ ShowRuntimeFailureDimension,+ ShowRuntimeFailureEvidence,+ ShowRuntimeRecoveryAction,+ classify_show_runtime_failure,+ show_runtime_recovery_action,+)from storage import resource_access_servicefrom tests.ui_server_test_helpers import _mock_interface, _remote_peer, _save_configfrom tests.ui_server_test_helpers import csrf_headers, remote_session_cookie@@ -93,6 +116,7 @@ class _FakeShowRuntimeManager:body: bytes = b"Runtime Show Page",fail: bool = False,error: Exception | None = None,+ failure_reason: str = "runtime_proxy_failed",status_code: int = 200,extra_headers: dict[str, str] | None = None,headers_by_path: dict[str, dict[str, str]] | None = None,@@ -102,16 +126,31 @@ class _FakeShowRuntimeManager:self.body = bodyself.fail = failself.error = error+ self.failure_reason = failure_reasonself.status_code = status_codeself.extra_headers = extra_headers or {}self.headers_by_path = headers_by_path or {}self.bodies_by_path = bodies_by_path or {}self.status_by_path = status_by_path or {}self.calls = []+ self.automatic_calls = []self.websocket_paths = []self.websocket_headers = []self.stopped = False+ def _unavailable_error(self):+ declaration = SHOW_RUNTIME_FAILURE_DECLARATIONS.get((self.failure_reason, None, None))+ evidence = ShowRuntimeFailureEvidence(+ declaration.dimension if declaration else ShowRuntimeFailureDimension.RUNTIME,+ self.failure_reason,+ )+ failure_class = classify_show_runtime_failure(evidence)+ return ShowRuntimeUnavailableError(+ self.failure_reason,+ failure_class,+ show_runtime_recovery_action(evidence),+ )+async def request(self,method,@@ -121,19 +160,25 @@ class _FakeShowRuntimeManager:headers=None,body=None,timeout_seconds=None,+ automatic=True,):import httpxself.calls.append((method, path, envelope.headers(headers), body, timeout_seconds))+ self.automatic_calls.append(automatic)if self.error is not None:raise self.errorif self.fail:- raise RuntimeError("runtime unavailable")- headers = {+ raise self._unavailable_error()+ headers = (+ {"content-type": "text/html; charset=utf-8","set-cookie": "__Host-vibe_remote_session=attacker","x-runtime-private-header": "secret",- } | self.extra_headers | self.headers_by_path.get(path, {})+ }+ | self.extra_headers+ | self.headers_by_path.get(path, {})+ )return httpx.Response(self.status_by_path.get(path, self.status_code),content=self.bodies_by_path.get(path, self.body),@@ -145,12 +190,16 @@ class _FakeShowRuntimeManager:self.calls.append((method, path, headers or {}, body))if self.fail:- raise RuntimeError("runtime unavailable")- response_headers = {+ raise self._unavailable_error()+ response_headers = (+ {"content-type": "text/html; charset=utf-8","set-cookie": "__Host-vibe_remote_session=attacker","x-runtime-private-header": "secret",- } | self.extra_headers | self.headers_by_path.get(path, {})+ }+ | self.extra_headers+ | self.headers_by_path.get(path, {})+ )return httpx.Response(self.status_by_path.get(path, self.status_code),content=self.bodies_by_path.get(path, self.body),@@ -167,6 +216,47 @@ class _FakeShowRuntimeManager:self.stopped = True+def _runtime_manager_with_failing_transport(monkeypatch, tmp_path):+ manager = ShowRuntimeManager(+ command=str(tmp_path / "configured-runtime"),+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ )++ class FakeProcess:+ pid = 321++ def poll(self):+ return None++ manager._base_url = "http://127.0.0.1:49321"+ manager._process = FakeProcess()+ manager._availability = manager._publish_runtime_availability(+ ShowRuntimeServingState.SERVING,+ manager._base_url,+ )+ monkeypatch.setattr(manager, "_healthy", lambda _base_url: asyncio.sleep(0, result=True))+ monkeypatch.setattr(+ manager,+ "_negotiate_context_key_capability",+ lambda _base_url: asyncio.sleep(0),+ )++ def stop():+ manager._process = None+ manager._base_url = None++ async def fail_request(_client, method, url, **_kwargs):+ raise httpx.ConnectError(+ "Show Runtime transport unavailable",+ request=httpx.Request(method, url),+ )++ monkeypatch.setattr(manager, "stop", stop)+ monkeypatch.setattr("core.show_runtime.httpx.AsyncClient.request", fail_request)+ return manager++@pytest.fixture(autouse=True)def _hermetic_show_runtime(monkeypatch):monkeypatch.setattr("core.show_runtime._node_version", lambda node: (22, 16, 0))@@ -398,7 +488,7 @@ def _install_remote_manifest_runtime(monkeypatch, tmp_path: Path):runtime_dir=runtime_dir,manifest_url=manifest_url,)- result = manager.prepare()+ result = manager.prepare(automatic=True)assert result["install"]["state"] == "installed"install_dir = Path(result["command"][1]).parents[4]return runtime_dir, manifest_url, install_dir, result["command"]@@ -457,6 +547,26 @@ def test_private_show_page_requires_remote_login(monkeypatch, tmp_path):assert response.headers["Location"] == "/auth/login?next=%2Fshow%2Fses123%2F"+def test_retry_now_html_request_preserves_remote_login_redirect(monkeypatch, tmp_path):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ _save_config(tmp_path)+ _create_show_page("ses123", "private")++ response = app.test_client().get(+ "/show/ses123/",+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ headers={+ "Accept": "text/html",+ "X-Avibe-Show-Recovery-Retry": "1",+ },+ follow_redirects=False,+ )++ assert response.status_code == 302+ assert response.headers["Location"] == "/auth/login?next=%2Fshow%2Fses123%2F"++def test_private_show_page_serves_locally(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))_save_config(tmp_path)@@ -1887,10 +1997,13 @@ def test_show_page_history_route_uses_recovery_when_runtime_unavailable(monkeypaassert response.status_code == 200assert b"Loading Show Page" in response.content- assert b"Ready to visualize" in response.content- assert b"standard shadcn variables" in response.content- assert b"--background" in response.content- assert b"components from @/components/ui and @avibe/show-ui" not in response.content+ assert b"The Show Runtime is unavailable" in response.content+ if surface == "private":+ assert b"vibe doctor repair show-runtime" in response.content+ else:+ assert b"vibe doctor repair show-runtime" not in response.content+ assert b"Reload this page to try the request again" in response.content+ assert b"src/App.tsx" not in response.contentassert [call[1] for call in manager.calls] == ["/sessions/ses123/app/"]@@ -2682,7 +2795,7 @@ def test_show_annotation_bootstrap_asset_proxies_to_runtime(monkeypatch, tmp_pat@pytest.mark.parametrize("surface", ["private", "public"])@pytest.mark.parametrize("runtime_path", ["__show/annotation.js", "__show/runtime-probe"])-def test_show_protocol_timeout_remains_runtime_unavailable(+def test_show_protocol_transport_failure_remains_runtime_unavailable(monkeypatch,tmp_path,surface,@@ -2696,9 +2809,7 @@ def test_show_protocol_timeout_remains_runtime_unavailable(else:share_id = _create_show_page("ses123", "public")path = f"/p/{share_id}/{runtime_path}"- manager = _FakeShowRuntimeManager(- error=ShowRuntimeRequestTimeoutError("Show Runtime request exceeded 30 seconds")- )+ manager = _FakeShowRuntimeManager(fail=True)set_show_runtime_manager_for_tests(manager)try:response = app.test_client().get(path, base_url="http://127.0.0.1:5123")@@ -2706,7 +2817,10 @@ def test_show_protocol_timeout_remains_runtime_unavailable(set_show_runtime_manager_for_tests(None)assert response.status_code == 503- assert response.get_json() == {"error": "show_runtime_unavailable"}+ assert response.get_json() == {+ "error": "show_runtime_unavailable",+ "reason": "runtime_proxy_failed",+ }assert manager.calls[0][4] is None@@ -2954,27 +3068,212 @@ def test_public_show_page_does_not_inject_write_runtime_config(monkeypatch, tmp_assert "token-ses123" not in body-def test_private_show_page_falls_back_to_static_when_runtime_unavailable(monkeypatch, tmp_path):+def test_private_show_page_falls_back_to_runtime_recovery(monkeypatch, tmp_path, caplog):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))monkeypatch.setattr("core.show_git.show_git_checkpointing_active", lambda: True)_save_config(tmp_path)_create_show_page("ses123", "private")- set_show_runtime_manager_for_tests(_FakeShowRuntimeManager(fail=True))+ set_show_runtime_manager_for_tests(+ _FakeShowRuntimeManager(fail=True, failure_reason="runtime_archive_download_failed")+ )try:- response = app.test_client().get("/show/ses123/", base_url="http://127.0.0.1:5123")+ with caplog.at_level("WARNING"):+ 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"Loading Show Page" in response.content- assert b"Ready to visualize" in response.content- assert b"Copy prompt" in response.content- assert b"History is saved automatically around each turn" in response.content- assert b"Never add remotes, push, or publish" in response.content+ assert response.headers["X-Avibe-Show-Recovery"] == "1"+ assert response.headers["X-Avibe-Show-Recovery-Reason"] == "runtime_archive_download_failed"+ assert response.headers["X-Avibe-Show-Recovery-Class"] == "transient"+ assert b"The Show Runtime is unavailable" in response.content+ assert b"vibe doctor repair show-runtime" in response.content+ assert b"runtime_archive_download_failed" in response.content+ assert b"X-Avibe-Show-Recovery-Poll" not in response.content+ assert b"window.setInterval" not in response.content+ assert b"window.setTimeout" not in response.content+ assert response.content.count(b"fetch(window.location.href") == 1+ assert b"document.write(html)" in response.content+ assert b"(() => {" in response.content+ assert b"})();" in response.content+ assert b'"Accept": "text/html"' in response.content+ assert b"response.redirected || !response.ok || !contentType.includes(\"text/html\")" in response.content+ assert b"window.location.assign(response.url || window.location.href)" in response.content+ assert response.content.index(b"response.redirected") < response.content.index(b"response.text()")+ assert b"window.location.reload" not in response.content+ assert b"X-Avibe-Show-Recovery-Retry" in response.content+ assert b"Math.min(30000, retryDelayMs * 2)" not in response.content+ assert b"checksRemaining" not in response.content+ assert b'|| "runtime_unavailable"' not in response.content+ assert b'|| "unclassified"' not in response.content+ assert b'|| "manual_only"' not in response.content+ assert b"src/App.tsx" not in response.contentassert b'src="./src/main.tsx"' not in response.content+ assert "Show runtime unavailable (runtime_archive_download_failed)" in caplog.text+++def test_show_recovery_retry_now_is_explicit_intent(monkeypatch, tmp_path):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ _save_config(tmp_path)+ _create_show_page("ses123", "private")+ manager = _FakeShowRuntimeManager(fail=True, failure_reason="runtime_start_health_timeout")+ set_show_runtime_manager_for_tests(manager)+ try:+ response = app.test_client().get(+ "/show/ses123/",+ base_url="http://127.0.0.1:5123",+ headers={"X-Avibe-Show-Recovery-Retry": "1"},+ )+ finally:+ set_show_runtime_manager_for_tests(None)++ assert response.status_code == 200+ assert manager.automatic_calls == [False]+ assert b"runtime_start_health_timeout" in response.content+ assert b"vibe doctor repair show-runtime" in response.content++[email protected]("surface", ("public", "private-viewer"))+def test_show_recovery_retry_header_cannot_bypass_for_viewers(monkeypatch, tmp_path, surface):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config = _save_config(tmp_path)+ visibility = "public" if surface == "public" else "private"+ share_id = _create_show_page("ses123", visibility)+ manager = _FakeShowRuntimeManager(fail=True, failure_reason="runtime_start_health_timeout")+ set_show_runtime_manager_for_tests(manager)+ client = app.test_client()+ if surface == "private-viewer":+ client.set_cookie(+ remote_access.SESSION_COOKIE_NAME,+ _active_org_cookie(config, "[email protected]", "viewer-1", role="viewer"),+ domain="alex.avibe.bot",+ )+ path = "/show/ses123/"+ else:+ path = f"/p/{share_id}/"+ try:+ response = client.get(+ path,+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ headers={"X-Avibe-Show-Recovery-Retry": "1"},+ )+ finally:+ set_show_runtime_manager_for_tests(None)++ assert response.status_code == 200+ assert manager.automatic_calls == [True]+ assert b"show-runtime-retry-now" not in response.content+ assert b"vibe doctor repair show-runtime" not in response.content+ assert b"X-Avibe-Show-Recovery-Poll" not in response.content+ assert b"Reload this page to try the request again" in response.content+++ ("reason", "language", "expected"),+ (+ ("VIBE_SHOW_RUNTIME_AUTO_INSTALL", "en", "Automatic Show Runtime installation is disabled"),+ ("VIBE_INSTALL_SKIP_SHOW_RUNTIME", "zh", "配置已关闭 Show Runtime 自动安装"),+ ),+)+def test_show_recovery_projects_policy_owner_evidence(monkeypatch, tmp_path, reason, language, expected):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ monkeypatch.delenv("VIBE_INSTALL_SKIP_SHOW_RUNTIME", raising=False)+ if reason == "VIBE_INSTALL_SKIP_SHOW_RUNTIME":+ monkeypatch.setenv("VIBE_INSTALL_SKIP_SHOW_RUNTIME", "1")+ _save_config(tmp_path)+ _create_show_page("ses123", "private")+ manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ runtime_source="npm",+ auto_install=reason != "VIBE_SHOW_RUNTIME_AUTO_INSTALL",+ )+ 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-Language": language},+ )+ finally:+ set_show_runtime_manager_for_tests(None)++ body = response.content.decode("utf-8")+ assert expected in body+ assert reason in body+ assert "runtime_proxy_failed" not in body+ assert "show-runtime-retry-now" in body+++ ("language", "expected_heading", "expected_status"),+ [+ (+ "en",+ "No action is available here",+ "No action on this machine can change it",+ ),+ (+ "zh",+ "此处没有可用操作",+ "这台机器上的任何操作都无法改变这一结果",+ ),+ ],+)+def test_unsupported_platform_recovery_offers_no_impossible_local_action(+ monkeypatch,+ tmp_path,+ language,+ expected_heading,+ expected_status,+):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ _save_config(tmp_path)+ _create_show_page("ses123", "private")+ set_show_runtime_manager_for_tests(+ _FakeShowRuntimeManager(fail=True, failure_reason="runtime_platform_unsupported")+ )+ try:+ response = app.test_client().get(+ "/show/ses123/",+ base_url="http://127.0.0.1:5123",+ headers={"Accept-Language": language},+ )+ finally:+ set_show_runtime_manager_for_tests(None)++ body = response.content.decode("utf-8")+ assert expected_heading in body+ assert expected_status in body+ assert "vibe doctor repair show-runtime" not in body+ assert "show-runtime-retry-now" not in body+ assert "X-Avibe-Show-Recovery-Retry" not in body+++def test_show_runtime_recovery_uses_request_language(monkeypatch, tmp_path):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ _save_config(tmp_path)+ _create_show_page("ses123", "private")+ set_show_runtime_manager_for_tests(+ _FakeShowRuntimeManager(fail=True, failure_reason="runtime_archive_unavailable_offline")+ )+ try:+ response = app.test_client().get(+ "/show/ses123/",+ base_url="http://127.0.0.1:5123",+ headers={"Accept-Language": "zh-CN,zh;q=0.9"},+ )+ finally:+ set_show_runtime_manager_for_tests(None)++ body = response.content.decode("utf-8")+ assert '<html lang="zh" data-show-runtime-reason="runtime_archive_unavailable_offline"' in body+ assert "Avibe 当前处于离线模式" in body+ assert "修改下方所示的设置或前置条件" in body-def test_private_show_page_recovery_reports_history_unavailable_without_git(monkeypatch, tmp_path):+def test_private_show_page_recovery_does_not_blame_page_source_without_git(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))monkeypatch.setattr("core.show_git.show_git_checkpointing_active", lambda: False)_save_config(tmp_path)@@ -2986,12 +3285,12 @@ def test_private_show_page_recovery_reports_history_unavailable_without_git(monkset_show_runtime_manager_for_tests(None)assert response.status_code == 200- assert b"Automatic Show Page history is unavailable" in response.contentassert b"History is saved automatically around each turn" not in response.contentassert b"git restore --source" not in response.content+ assert b"src/App.tsx" not in response.content-def test_private_show_page_recovery_uses_self_managed_history_contract(monkeypatch, tmp_path):+def test_private_show_page_recovery_does_not_emit_history_contract(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))monkeypatch.setattr("core.show_git.show_git_checkpointing_active", lambda: True)_save_config(tmp_path)@@ -3004,11 +3303,9 @@ def test_private_show_page_recovery_uses_self_managed_history_contract(monkeypatset_show_runtime_manager_for_tests(None)assert response.status_code == 200- assert b"shadow history continues automatically" in response.content- assert b"not Avibe history" in response.content- assert b"Only if the user explicitly asks to recover from Avibe history" in response.contentassert b"History is saved automatically around each turn" not in response.contentassert b"Restore only via" not in response.content+ assert b"vibe doctor repair show-runtime" in response.contentdef test_private_show_page_static_fallback_denies_dot_leading_segments(monkeypatch, tmp_path):@@ -3549,21 +3846,23 @@ def test_public_show_page_denies_at_fs_extra_leading_slash_symlink_escape(monkey)-def test_show_page_recovery_loading_holds_before_ready(monkeypatch, tmp_path):+def test_show_page_terminal_runtime_failure_renders_immediately(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))_save_config(tmp_path)_create_show_page("ses123", "private")- set_show_runtime_manager_for_tests(_FakeShowRuntimeManager(fail=True))+ set_show_runtime_manager_for_tests(+ _FakeShowRuntimeManager(fail=True, failure_reason="runtime_node_unsupported")+ )try:response = app.test_client().get("/show/ses123/", base_url="http://127.0.0.1:5123")finally:set_show_runtime_manager_for_tests(None)body = response.content.decode("utf-8")- loading_delay = f"{SHOW_RUNTIME_RECOVERY_LOADING_DELAY_SECONDS}s"- assert f"show-recovery-loading-out 0.18s ease {loading_delay} forwards" in body- assert f"show-recovery-panel-in 0.22s ease {loading_delay} forwards" in body- assert "ease 5s forwards" not in body+ assert "show-recovery-loading-out 0.18s ease 0s forwards" in body+ assert "show-recovery-panel-in 0.22s ease 0s forwards" in body+ assert f"ease {SHOW_PAGE_RUNTIME_RECOVERY_LOADING_DELAY_SECONDS}s forwards" not in body+ assert "The installed Node.js runtime is missing or is not supported." in bodydef test_private_show_page_api_does_not_fall_back_to_static(monkeypatch, tmp_path):@@ -3579,6 +3878,7 @@ def test_private_show_page_api_does_not_fall_back_to_static(monkeypatch, tmp_patassert response.status_code == 503assert response.get_json()["error"] == "show_runtime_unavailable"+ assert response.get_json()["reason"] == "runtime_proxy_failed"assert b"secret" not in response.content@@ -3668,15 +3968,11 @@ def test_show_page_api_timeout_is_distinct_from_runtime_unavailable(assert response.get_json() == {"error": "show_runtime_request_timeout"}-def test_show_page_api_connect_timeout_remains_runtime_unavailable(monkeypatch, tmp_path):+def test_show_page_api_transport_failure_uses_manager_evidence(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))_save_config(tmp_path)_create_show_page("ses123", "private")- timeout = httpx.ConnectTimeout(- "Show Runtime connection timed out",- request=httpx.Request("GET", "http://127.0.0.1/api/slow"),- )- manager = _FakeShowRuntimeManager(error=timeout)+ manager = _runtime_manager_with_failing_transport(monkeypatch, tmp_path)set_show_runtime_manager_for_tests(manager)try:response = app.test_client().get(@@ -3687,7 +3983,80 @@ def test_show_page_api_connect_timeout_remains_runtime_unavailable(monkeypatch,set_show_runtime_manager_for_tests(None)assert response.status_code == 503- assert response.get_json() == {"error": "show_runtime_unavailable"}+ assert response.get_json() == {+ "error": "show_runtime_unavailable",+ "reason": "runtime_proxy_failed",+ }+++ ("accept_language", "reload_copy"),+ (+ ("en-US,en;q=0.9", "Reload this page to try the request again."),+ ("zh-CN,zh;q=0.9", "请重新加载此页面,再次尝试请求"),+ ),+)+def test_public_show_transport_failure_remains_manually_retryable(+ monkeypatch,+ tmp_path,+ accept_language,+ reload_copy,+):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ _save_config(tmp_path)+ share_id = _create_show_page("ses123", "public")+ manager = _runtime_manager_with_failing_transport(monkeypatch, tmp_path)+ set_show_runtime_manager_for_tests(manager)+ try:+ first = app.test_client().get(+ f"/p/{share_id}/",+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ headers={"Accept-Language": accept_language},+ )+ response = app.test_client().get(+ f"/p/{share_id}/",+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ headers={"Accept-Language": accept_language},+ )+ finally:+ set_show_runtime_manager_for_tests(None)++ body = response.content.decode("utf-8")+ first_body = first.content.decode("utf-8")+ assert first.headers["X-Avibe-Show-Recovery-Reason"] == "runtime_proxy_failed"+ assert "X-Avibe-Show-Recovery-Poll" not in first_body+ assert response.status_code == 200+ assert response.headers["X-Avibe-Show-Recovery-Reason"] == "runtime_command_missing"+ assert response.headers["X-Avibe-Show-Recovery-Class"] == "configured"+ assert "X-Avibe-Show-Recovery-Poll" not in body+ assert "show-runtime-retry-now" not in body+ assert "vibe doctor repair show-runtime" not in body+ assert reload_copy in body+++def test_show_page_does_not_fabricate_recovery_evidence_for_programming_errors(+ monkeypatch,+ tmp_path,+):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ _save_config(tmp_path)+ _create_show_page("ses123", "private")+ set_show_runtime_manager_for_tests(+ _FakeShowRuntimeManager(error=RuntimeError("unowned failure"))+ )+ 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 == 500+ assert response.headers.get("X-Avibe-Show-Recovery") is None+ assert b"runtime_proxy_failed" not in response.contentdef test_private_show_page_records_show_event(monkeypatch, tmp_path):@@ -6200,32 +6569,1263 @@ def test_show_runtime_manager_reports_missing_command(tmp_path):assert result.reason == "runtime_command_missing"-def test_show_runtime_manager_passes_runtime_options(monkeypatch, tmp_path):- from core.show_pages import SHOW_RUNTIME_RECOVERY_LOADING_DELAY_SECONDS+ ("dimension", "reason", "expected"),+ [+ (ShowRuntimeFailureDimension.INSTALL, "runtime_archive_download_failed", ShowRuntimeFailureClass.TRANSIENT),+ (ShowRuntimeFailureDimension.INSTALL, "runtime_manifest_download_failed", ShowRuntimeFailureClass.TRANSIENT),+ (ShowRuntimeFailureDimension.INSTALL, "runtime_install_failed", ShowRuntimeFailureClass.UNCLASSIFIED),+ (ShowRuntimeFailureDimension.INSTALL, "runtime_node_missing", ShowRuntimeFailureClass.CONFIGURED),+ (ShowRuntimeFailureDimension.RUNTIME, "runtime_start_url_timeout", ShowRuntimeFailureClass.UNCLASSIFIED),+ (+ ShowRuntimeFailureDimension.RUNTIME,+ "runtime_start_process_unavailable",+ ShowRuntimeFailureClass.UNCLASSIFIED,+ ),+ (ShowRuntimeFailureDimension.RUNTIME, "runtime_start_health_timeout", ShowRuntimeFailureClass.UNCLASSIFIED),+ (ShowRuntimeFailureDimension.RUNTIME, "runtime_start_attempt_failed", ShowRuntimeFailureClass.UNCLASSIFIED),+ (+ ShowRuntimeFailureDimension.RUNTIME,+ "runtime_start_command_unavailable",+ ShowRuntimeFailureClass.UNCLASSIFIED,+ ),+ (ShowRuntimeFailureDimension.RUNTIME, "runtime_start_command_invalid", ShowRuntimeFailureClass.CONFIGURED),+ (ShowRuntimeFailureDimension.RUNTIME, "runtime_start_node_command_invalid", ShowRuntimeFailureClass.CONFIGURED),+ (ShowRuntimeFailureDimension.RUNTIME, "runtime_proxy_failed", ShowRuntimeFailureClass.UNCLASSIFIED),+ (ShowRuntimeFailureDimension.INSTALL, "runtime_archive_checksum_mismatch", ShowRuntimeFailureClass.CHECKSUM),+ (ShowRuntimeFailureDimension.INSTALL, "runtime_platform_unsupported", ShowRuntimeFailureClass.PERMANENT),+ (ShowRuntimeFailureDimension.INSTALL, "runtime_node_unsupported", ShowRuntimeFailureClass.CONFIGURED),+ (ShowRuntimeFailureDimension.INSTALL, "runtime_source_unsupported", ShowRuntimeFailureClass.PERMANENT),+ (ShowRuntimeFailureDimension.INSTALL, "runtime_archive_url_unsupported", ShowRuntimeFailureClass.PERMANENT),+ (+ ShowRuntimeFailureDimension.INSTALL,+ "runtime_archive_unavailable_offline",+ ShowRuntimeFailureClass.CONFIGURED,+ ),+ (+ ShowRuntimeFailureDimension.INSTALL,+ "runtime_manifest_unavailable_offline",+ ShowRuntimeFailureClass.CONFIGURED,+ ),+ ],+)+def test_show_runtime_failure_classification(dimension, reason, expected):+ assert classify_show_runtime_failure(ShowRuntimeFailureEvidence(dimension, reason)) is expected- captured = {}- class FakeProcess:- def poll(self):- return None+ ("provenance", "expected_class", "expected_action"),+ (+ ("configured", ShowRuntimeFailureClass.CONFIGURED, ShowRuntimeRecoveryAction.CHANGE_SETTING),+ ("packaged", ShowRuntimeFailureClass.UNCLASSIFIED, ShowRuntimeRecoveryAction.REPAIR),+ ),+)+def test_manifest_failure_classification_uses_published_provenance(+ provenance,+ expected_class,+ expected_action,+):+ evidence = ShowRuntimeFailureEvidence(+ ShowRuntimeFailureDimension.INSTALL,+ "runtime_manifest_invalid",+ provenance,+ )- def fake_popen(command, **kwargs):- captured["command"] = command- return FakeProcess()+ assert classify_show_runtime_failure(evidence) is expected_class+ assert show_runtime_recovery_action(evidence) is expected_action- async def fake_startup_url(*, deadline):- captured["startup_deadline"] = deadline- return "http://127.0.0.1:12345"- manager = ShowRuntimeManager(- command="/bin/echo",- workspace_root=tmp_path / "show",- runtime_dir=tmp_path / "runtime",- )- monkeypatch.setattr("core.show_runtime._resolve_command", lambda command: [command])- monkeypatch.setattr("core.show_runtime.subprocess.Popen", fake_popen)- monkeypatch.setattr(manager, "_read_startup_url", fake_startup_url)- monkeypatch.setattr(manager, "_healthy", lambda _base_url: asyncio.sleep(0, result=True))+ ("provenance", "expected_class", "expected_action"),+ (+ ("configured", ShowRuntimeFailureClass.CONFIGURED, ShowRuntimeRecoveryAction.CHANGE_SETTING),+ ("packaged", ShowRuntimeFailureClass.UNCLASSIFIED, ShowRuntimeRecoveryAction.REPAIR),+ ),+)+def test_archive_failure_classification_uses_published_provenance(+ provenance,+ expected_class,+ expected_action,+):+ evidence = ShowRuntimeFailureEvidence(+ ShowRuntimeFailureDimension.INSTALL,+ "runtime_archive_missing",+ provenance,+ )++ assert classify_show_runtime_failure(evidence) is expected_class+ assert show_runtime_recovery_action(evidence) is expected_action+++ ("reason", "provenance", "retryable", "expected_class", "expected_action"),+ (+ (+ "runtime_manifest_download_failed",+ "configured",+ False,+ ShowRuntimeFailureClass.CONFIGURED,+ ShowRuntimeRecoveryAction.CHANGE_SETTING,+ ),+ (+ "runtime_manifest_download_failed",+ "configured",+ True,+ ShowRuntimeFailureClass.TRANSIENT,+ ShowRuntimeRecoveryAction.REPAIR,+ ),+ (+ "runtime_archive_download_failed",+ "configured",+ False,+ ShowRuntimeFailureClass.CONFIGURED,+ ShowRuntimeRecoveryAction.CHANGE_SETTING,+ ),+ (+ "runtime_archive_download_failed",+ "packaged",+ False,+ ShowRuntimeFailureClass.UNCLASSIFIED,+ ShowRuntimeRecoveryAction.REPAIR,+ ),+ (+ "runtime_archive_download_failed",+ "configured",+ True,+ ShowRuntimeFailureClass.TRANSIENT,+ ShowRuntimeRecoveryAction.REPAIR,+ ),+ (+ "runtime_archive_download_failed",+ "packaged",+ True,+ ShowRuntimeFailureClass.TRANSIENT,+ ShowRuntimeRecoveryAction.REPAIR,+ ),+ ),+)+def test_download_failure_classification_uses_owner_evidence(+ reason,+ provenance,+ retryable,+ expected_class,+ expected_action,+):+ evidence = ShowRuntimeFailureEvidence(+ ShowRuntimeFailureDimension.INSTALL,+ reason,+ provenance,+ retryable,+ )++ assert classify_show_runtime_failure(evidence) is expected_class+ assert show_runtime_recovery_action(evidence) is expected_action+++def test_show_runtime_failure_declarations_are_total_and_owner_safe():+ assert len(SHOW_RUNTIME_FAILURE_DECLARATIONS) == len(set(SHOW_RUNTIME_FAILURE_DECLARATIONS))+ assert all(+ declaration.owning_artifact and declaration.dimension+ for declaration in SHOW_RUNTIME_FAILURE_DECLARATIONS.values()+ )+ assert all(+ declaration.user_owned+ for declaration in SHOW_RUNTIME_FAILURE_DECLARATIONS.values()+ if declaration.failure_class is ShowRuntimeFailureClass.CONFIGURED+ )+++def test_download_failure_declaration_keys_cover_owner_stored_fields():+ details_tree = ast.parse(textwrap.dedent(inspect.getsource(dependency_network.dependency_error_details)))+ owner_stored_fields: set[str] = set()++ class DownloadDetailFieldVisitor(ast.NodeVisitor):+ def visit_Dict(self, node: ast.Dict) -> None:+ owner_stored_fields.update(+ key.value+ for key in node.keys+ if isinstance(key, ast.Constant) and isinstance(key.value, str)+ )+ self.generic_visit(node)++ def visit_Call(self, node: ast.Call) -> None:+ if isinstance(node.func, ast.Attribute) and node.func.attr == "update":+ owner_stored_fields.update(keyword.arg for keyword in node.keywords if keyword.arg)+ self.generic_visit(node)++ DownloadDetailFieldVisitor().visit(details_tree)+ declaration_lookup_tree = ast.parse(+ textwrap.dedent(inspect.getsource(show_runtime_failures_module._failure_declaration))+ )+ declaration_key_fields = {+ node.attr+ for node in ast.walk(declaration_lookup_tree)+ if isinstance(node, ast.Attribute)+ and isinstance(node.value, ast.Name)+ and node.value.id == "evidence"+ }+ explicitly_irrelevant = {+ "attempts",+ "exception_type",+ "host",+ "http_status",+ "kind",+ "message",+ "retry_after_seconds",+ "url",+ }++ assert owner_stored_fields - explicitly_irrelevant <= declaration_key_fields+++def test_archive_failure_provenance_census_matches_archive_path_emissions():+ manager_tree = ast.parse(textwrap.dedent(inspect.getsource(ShowRuntimeManager))).body[0]+ configured_archive_reasons: set[str] = set()++ def archive_path_guard(test: ast.expr) -> bool | None:+ if (+ isinstance(test, ast.Attribute)+ and isinstance(test.value, ast.Name)+ and test.value.id == "self"+ and test.attr == "archive_path"+ ):+ return True+ if isinstance(test, ast.UnaryOp) and isinstance(test.op, ast.Not):+ nested = archive_path_guard(test.operand)+ return None if nested is None else not nested+ if (+ isinstance(test, ast.Compare)+ and len(test.ops) == 1+ and len(test.comparators) == 1+ and isinstance(test.comparators[0], ast.Constant)+ and test.comparators[0].value is None+ ):+ nested = archive_path_guard(test.left)+ if nested is None:+ return None+ if isinstance(test.ops[0], (ast.IsNot, ast.NotEq)):+ return True+ if isinstance(test.ops[0], (ast.Is, ast.Eq)):+ return False+ return None++ class ArchivePathEmissionVisitor(ast.NodeVisitor):+ def __init__(self) -> None:+ self.archive_path_is_set = False++ def visit_If(self, node: ast.If) -> None:+ previous = self.archive_path_is_set+ guard = archive_path_guard(node.test)+ self.archive_path_is_set = previous or guard is True+ for child in node.body:+ self.visit(child)+ self.archive_path_is_set = previous or guard is False+ for child in node.orelse:+ self.visit(child)+ self.archive_path_is_set = previous++ def visit_Constant(self, node: ast.Constant) -> None:+ if (+ self.archive_path_is_set+ and isinstance(node.value, str)+ and node.value.startswith("runtime_archive_")+ ):+ configured_archive_reasons.add(node.value)++ ArchivePathEmissionVisitor().visit(manager_tree)+ declared_provenance = {+ reason: {+ provenance+ for (declared_reason, provenance, _retryable), declaration in SHOW_RUNTIME_FAILURE_DECLARATIONS.items()+ if declared_reason == reason and "archive" in declaration.owning_artifact+ }+ for reason in configured_archive_reasons+ }+ assert declared_provenance == {+ reason: {"configured", "packaged"} for reason in configured_archive_reasons+ }+ assert {+ declaration.reason+ for declaration in SHOW_RUNTIME_FAILURE_DECLARATIONS.values()+ if declaration.provenance == "configured" and declaration.owning_artifact == "configured-archive"+ } == configured_archive_reasons+++def test_show_runtime_reason_literals_have_declared_evidence():+ source = inspect.getsource(show_runtime)+ reason_literals = {+ value+ for value in re.findall(r'(["\'])(runtime_[a-z0-9_]+)\1', source)+ if value[1] not in {"runtime_source", "runtime_version"}+ }+ declared = {reason for reason, _provenance, _retryable in SHOW_RUNTIME_FAILURE_DECLARATIONS}+ assert {value for _quote, value in reason_literals} <= declared+++def test_show_runtime_dimensions_are_serialized_only_by_availability_owner():+ module_tree = ast.parse(inspect.getsource(show_runtime))+ offenders: list[tuple[int, tuple[str, ...], tuple[str, ...]]] = []++ class DimensionPayloadVisitor(ast.NodeVisitor):+ def __init__(self) -> None:+ self.scope: list[str] = []++ def visit_ClassDef(self, node: ast.ClassDef) -> None:+ self.scope.append(node.name)+ self.generic_visit(node)+ self.scope.pop()++ def visit_FunctionDef(self, node: ast.FunctionDef) -> None:+ self.scope.append(node.name)+ self.generic_visit(node)+ self.scope.pop()++ visit_AsyncFunctionDef = visit_FunctionDef++ def visit_Dict(self, node: ast.Dict) -> None:+ keys = {+ key.value+ for key in node.keys+ if isinstance(key, ast.Constant) and isinstance(key.value, str)+ }+ dimension_shape = "state" in keys and "reason" in keys and bool(+ keys & {"failure_class", "recovery_action", "base_url", "command", "install_dir"}+ )+ if dimension_shape and self.scope[-2:] != ["ShowRuntimeAvailability", "as_payload"]:+ offenders.append((node.lineno, tuple(self.scope), tuple(sorted(keys))))+ self.generic_visit(node)++ DimensionPayloadVisitor().visit(module_tree)+ assert offenders == []+++def test_runtime_request_uses_existing_base_without_health_preprobe(monkeypatch, tmp_path):+ manager = ShowRuntimeManager(+ command="/bin/runtime-cli",+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ )+ manager._base_url = "http://127.0.0.1:4173"+ manager._availability = manager._publish_runtime_availability(+ ShowRuntimeServingState.SERVING,+ manager._base_url,+ )+ monkeypatch.setattr(+ manager,+ "_healthy",+ lambda _base_url: (_ for _ in ()).throw(AssertionError("request path must not pre-probe")),+ )+ monkeypatch.setattr(manager, "_negotiate_context_key_capability", AsyncMock())+ transport = AsyncMock(return_value=SimpleNamespace(status_code=200))+ monkeypatch.setattr(manager, "_request_runtime_transport", transport)++ asyncio.run(+ manager.request(+ "GET",+ "/sessions/ses123/app/",+ envelope=ShowRuntimeProtocolEnvelope(ShowRuntimeContext.PRIVATE),+ )+ )++ assert transport.await_count == 1+++def test_unreadable_manifest_is_typed_install_evidence(monkeypatch, tmp_path):+ manifest_path = tmp_path / "runtime-manifest.json"+ manifest_path.write_text("{}", encoding="utf-8")+ manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ runtime_source="manifest",+ manifest_path=manifest_path,+ )+ real_read_bytes = Path.read_bytes++ def unreadable(path):+ if path == manifest_path:+ raise PermissionError("manifest is unreadable")+ return real_read_bytes(path)++ monkeypatch.setattr(Path, "read_bytes", unreadable)++ payload = manager.prepare(automatic=True)++ assert payload["ok"] is False+ assert payload["install"]["reason"] == "runtime_manifest_invalid"+ assert payload["install"]["failure_class"] == "configured"+ assert payload["install"]["recovery_action"] == "change_setting"+++def test_invalid_packaged_manifest_remains_repairable(monkeypatch, tmp_path):+ packaged_manifest = tmp_path / show_runtime._RUNTIME_MANIFEST_RESOURCE+ packaged_manifest.write_text("{}", encoding="utf-8")+ monkeypatch.setattr("core.show_runtime.package_resources.files", lambda _package: tmp_path)+ manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ runtime_source="manifest",+ )++ payload = manager.prepare(automatic=True)++ assert payload["install"]["reason"] == "runtime_manifest_invalid"+ assert payload["install"]["failure_class"] == "unclassified"+ assert payload["install"]["recovery_action"] == "repair"+++def test_new_install_admission_does_not_reuse_stale_failure_evidence(monkeypatch, tmp_path):+ manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ runtime_source="npm",+ )+ manager._install_reason = "runtime_node_missing"+ manager._download_error = {"kind": "network", "message": "stale download"}+ monkeypatch.setattr(+ manager,+ "_install_managed_runtime_locked",+ lambda **_kwargs: (_ for _ in ()).throw(PermissionError("runtime directory is not writable")),+ )++ payload = manager.prepare(automatic=True)++ assert payload["install"]["reason"] == "runtime_install_failed"+ assert payload["install"]["failure_class"] == "unclassified"+ assert payload["install"]["recovery_action"] == "repair"+ assert payload["status"]["download_error"] is None+++def test_show_runtime_install_io_exception_is_structured(monkeypatch, tmp_path):+ manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ runtime_source="npm",+ )+ monkeypatch.setattr(+ manager,+ "_install_managed_runtime_locked",+ lambda **_kwargs: (_ for _ in ()).throw(OSError("spawn failed")),+ )++ payload = manager.prepare(automatic=True)++ assert payload["ok"] is False+ assert payload["reason"] == "runtime_install_failed"+++def test_install_guard_contention_is_not_an_attempt_failure(monkeypatch, tmp_path):+ manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ runtime_source="npm",+ )+ monkeypatch.setattr(+ manager,+ "_install_guard_locked",+ lambda: nullcontext((False, "runtime_install_guard_unavailable")),+ )++ payload = manager.prepare(automatic=True)++ assert payload["ok"] is False+ assert payload["reason"] == "runtime_install_guard_unavailable"+ assert payload["install"]["failure_class"] == "unclassified"+++def test_failed_forced_replacement_does_not_block_installed_runtime(monkeypatch, tmp_path):+ command = [str(tmp_path / "runtime-cli")]+ manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ runtime_source="npm",+ )++ def install(*, force=None):+ manager._install_reason = "runtime_install_failed"+ return None++ monkeypatch.setattr(manager, "_install_npm_runtime", install)+ monkeypatch.setattr(manager, "_installed_managed_runtime_command", lambda *, offline: command)++ payload = manager.prepare(force=True, automatic=False)++ assert payload["ok"] is False+ assert payload["install"]["state"] == "installed"+ assert asyncio.run(manager._resolve_managed_command()) == command+++def test_start_admission_stays_serialized(monkeypatch, tmp_path):+ manager = ShowRuntimeManager(+ command="/bin/runtime-cli",+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ )+ observed = []+ real_admission = manager._admit_runtime_start++ async def observe_admission(*, automatic):+ observed.append(manager._lock.locked())+ return await real_admission(automatic=automatic)++ monkeypatch.setattr(manager, "_admit_runtime_start", observe_admission)+ monkeypatch.setattr(manager, "stop", lambda: None)+ monkeypatch.setattr("core.show_runtime._resolve_command", lambda command: [command])+ monkeypatch.setattr(manager, "_read_startup_url", lambda *, deadline: asyncio.sleep(0, result=None))+ monkeypatch.setattr(+ "core.show_runtime.subprocess.Popen", lambda *_args, **_kwargs: SimpleNamespace(poll=lambda: None)+ )++ asyncio.run(manager.ensure())++ assert observed == [True]+++ ("configured_env", "command", "expected_reason"),+ ((None, "'unterminated", "runtime_start_command_invalid"),),+)+def test_start_admission_publishes_malformed_configured_commands(+ monkeypatch,+ tmp_path,+ configured_env,+ command,+ expected_reason,+):+ if configured_env is None:+ monkeypatch.delenv("VIBE_SHOW_RUNTIME_NODE_BIN", raising=False)+ else:+ monkeypatch.setenv("VIBE_SHOW_RUNTIME_NODE_BIN", configured_env)+ manager = ShowRuntimeManager(+ command=command,+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ )++ result = asyncio.run(manager.ensure())++ assert result.runtime_reason == expected_reason+ assert result.runtime_failure_class is ShowRuntimeFailureClass.CONFIGURED+ assert result.runtime_recovery_action is ShowRuntimeRecoveryAction.CHANGE_SETTING+++def test_malformed_explicit_command_evidence_is_shared_by_status_prepare_and_start(+ monkeypatch,+ tmp_path,+):+ manager = ShowRuntimeManager(+ command="'unterminated",+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ runtime_source="npm",+ )+ monkeypatch.setattr(+ manager,+ "_managed_bin_path",+ lambda: pytest.fail("an explicit command must not inspect a managed provider"),+ )+ monkeypatch.setattr(+ manager,+ "_install_managed_runtime_locked",+ lambda **_kwargs: pytest.fail("an explicit command must not enter managed installation"),+ )++ status = manager.status()+ prepared = manager.prepare()+ started = asyncio.run(manager.ensure())++ for runtime in (status["runtime"], prepared["runtime"], started.as_payload()["runtime"]):+ assert runtime == {+ "state": "start_failed",+ "reason": "runtime_start_command_invalid",+ "failure_class": "configured",+ "recovery_action": "change_setting",+ "base_url": None,+ }+ assert status["install"]["state"] == "absent"+ assert status["command"] is None+ assert status["reason"] == "runtime_start_command_invalid"+ assert prepared["ok"] is False+ assert prepared["reason"] == "runtime_start_command_invalid"+++def test_managed_status_runtime_dimension_uses_availability_schema(monkeypatch, tmp_path):+ manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ runtime_source="npm",+ )+ monkeypatch.setattr("core.show_runtime._resolve_command", lambda _command: None)++ assert manager.status()["runtime"] == {+ "state": "unchecked",+ "reason": None,+ "failure_class": None,+ "recovery_action": None,+ "base_url": None,+ }+++ ("provider", "resolver_name"),+ (+ ("manifest-cache", "_installed_manifest_runtime_command"),+ ("github-source", "_installed_github_runtime_command"),+ ("npm", None),+ ),+)+def test_installed_managed_provider_is_resolved_before_mutation(+ monkeypatch,+ tmp_path,+ provider,+ resolver_name,+):+ command = [str(tmp_path / f"{provider}-runtime")]+ manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ runtime_source=provider,+ )+ if resolver_name == "_installed_manifest_runtime_command":+ monkeypatch.setattr(manager, resolver_name, lambda *, offline: command)+ elif resolver_name is not None:+ monkeypatch.setattr(manager, resolver_name, lambda: command)+ else:+ monkeypatch.setattr(manager, "_managed_bin_path", lambda: Path(command[0]))+ monkeypatch.setattr("core.show_runtime._resolve_executable_path", lambda _path: command[0])+ monkeypatch.setattr(+ manager,+ "_attempt_managed_install",+ lambda **_kwargs: pytest.fail("an installed runtime must not enter a mutating provider"),+ )++ availability = asyncio.run(manager._resolve_managed_availability())++ assert availability.command == command+ assert availability.install.value == "installed"+++ ("installed", "force"),+ ((False, False), (True, True)),+ ids=("absent", "forced"),+)+def test_managed_resolution_mutates_when_install_is_owed(monkeypatch, tmp_path, installed, force):+ existing_command = [str(tmp_path / "existing-runtime")]+ installed_command = [str(tmp_path / "installed-runtime")]+ manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ runtime_source="npm",+ force_install=force,+ )+ disk_reads = []+ attempts = []++ def read_installed(*, offline):+ disk_reads.append(offline)+ return existing_command if installed else None++ def install(**kwargs):+ attempts.append(kwargs)+ availability = manager._publish_install_availability(command=installed_command)+ operation = show_runtime._ShowRuntimeOperationOutcome(+ show_runtime._ShowRuntimeOperationState.COMPLETED,+ None,+ )+ return availability, operation++ monkeypatch.setattr(manager, "_safe_installed_managed_runtime_command", read_installed)+ monkeypatch.setattr(manager, "_attempt_managed_install", install)++ availability = asyncio.run(manager._resolve_managed_availability())++ assert disk_reads == ([] if force else [True])+ assert attempts == [{"force": force, "offline": False, "automatic": True}]+ assert availability.command == installed_command+++def test_remote_manifest_bypasses_disk_resolution_until_admission(monkeypatch, tmp_path):+ manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ runtime_source="manifest-cache",+ manifest_url="https://example.test/show-runtime-manifest.json",+ )+ command = [str(tmp_path / "installed-runtime")]+ attempts = []+ monkeypatch.setattr(+ manager,+ "_safe_installed_managed_runtime_command",+ lambda **_kwargs: pytest.fail("a remote manifest must be admitted before disk reuse"),+ )++ def install(**kwargs):+ attempts.append(kwargs)+ availability = manager._publish_install_availability(command=command)+ operation = show_runtime._ShowRuntimeOperationOutcome(+ show_runtime._ShowRuntimeOperationState.COMPLETED,+ None,+ )+ return availability, operation++ monkeypatch.setattr(manager, "_attempt_managed_install", install)++ availability = asyncio.run(manager._resolve_managed_availability())++ assert attempts == [{"force": False, "offline": False, "automatic": True}]+ assert availability.command == command+++def test_explicit_runtime_ignores_unrelated_malformed_node_override(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_SHOW_RUNTIME_NODE_BIN", "'unterminated")+ manager = ShowRuntimeManager(+ command="/bin/runtime-cli",+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ )+ monkeypatch.setattr(manager, "_healthy", lambda _base_url: asyncio.sleep(0, result=False))+ monkeypatch.setattr(manager, "stop", lambda: None)+ monkeypatch.setattr("core.show_runtime._resolve_command", lambda command: [command])+ monkeypatch.setattr(+ "core.show_runtime.subprocess.Popen", lambda *_args, **_kwargs: SimpleNamespace(poll=lambda: None)+ )+ monkeypatch.setattr(+ manager,+ "_read_startup_url",+ lambda *, deadline: asyncio.sleep(0, result=None),+ )++ result = asyncio.run(manager.ensure())++ assert result.runtime_reason == "runtime_start_url_timeout"+ assert result.runtime_reason != "runtime_start_node_command_invalid"+++def test_managed_runtime_normalizes_malformed_node_override(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_SHOW_RUNTIME_NODE_BIN", "'unterminated")+ manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ runtime_source="archive",+ )++ result = manager.prepare(automatic=True)++ assert result["reason"] == "runtime_node_missing"+ assert result["install"]["failure_class"] == "configured"+ assert result["install"]["recovery_action"] == "change_setting"+++def test_archive_explicit_attempt_does_not_fall_through_to_generic_install(monkeypatch, tmp_path):+ from core import show_runtime as srt++ manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ runtime_source="archive",+ )+ attempts = []++ def failed_archive(*, force, offline, automatic):+ attempts.append((force, offline, automatic))+ admission = manager._publish_install_availability(install_reason="runtime_archive_download_failed")+ return admission, srt._ShowRuntimeOperationOutcome(+ srt._ShowRuntimeOperationState.FAILED,+ "runtime_archive_download_failed",+ )++ monkeypatch.setattr(manager, "_attempt_managed_install", failed_archive)++ result = asyncio.run(manager._resolve_managed_availability(automatic=False))++ assert result.install_reason == "runtime_archive_download_failed"+ assert attempts == [(False, False, False)]++[email protected]("entrypoint", ("request", "request_global"))+def test_runtime_request_transport_boundary_publishes_recovery_evidence(+ monkeypatch,+ tmp_path,+ entrypoint,+):+ manager = _runtime_manager_with_failing_transport(monkeypatch, tmp_path)++ async def request_runtime():+ if entrypoint == "request":+ return await manager.request(+ "GET",+ "/sessions/ses123/app/",+ envelope=ShowRuntimeProtocolEnvelope(ShowRuntimeContext.PRIVATE),+ )+ return await manager.request_global("GET", "/_show-runtime/vendor/hash/runtime.js")++ with pytest.raises(ShowRuntimeUnavailableError) as raised:+ asyncio.run(request_runtime())++ assert raised.value.reason == "runtime_proxy_failed"+ assert raised.value.failure_class is ShowRuntimeFailureClass.UNCLASSIFIED+ assert raised.value.recovery_action is ShowRuntimeRecoveryAction.REPAIR+ assert manager._base_url is None+ assert manager._availability.runtime is ShowRuntimeServingState.SERVING++ admissions = []++ async def admit(*_args, **_kwargs):+ admissions.append(True)+ return SimpleNamespace(available=True, base_url="http://127.0.0.1:49322")++ async def successful_request(_client, method, url, **_kwargs):+ return httpx.Response(200, request=httpx.Request(method, url))++ monkeypatch.setattr(manager, "ensure", admit)+ monkeypatch.setattr("core.show_runtime.httpx.AsyncClient.request", successful_request)+ assert asyncio.run(request_runtime()).status_code == 200+ assert admissions == [True]+++def test_runtime_transport_response_does_not_invalidate_base_url(monkeypatch, tmp_path):+ manager = _runtime_manager_with_failing_transport(monkeypatch, tmp_path)+ base_url = manager._base_url++ async def server_error(_client, method, url, **_kwargs):+ return httpx.Response(503, request=httpx.Request(method, url))++ monkeypatch.setattr("core.show_runtime.httpx.AsyncClient.request", server_error)++ response = asyncio.run(manager.request_global("GET", "/health"))++ assert response.status_code == 503+ assert manager._base_url == base_url+++def test_delayed_transport_failure_does_not_invalidate_replacement_process(monkeypatch, tmp_path):+ manager = _runtime_manager_with_failing_transport(monkeypatch, tmp_path)+ base_url = manager._base_url+ replacement_process = SimpleNamespace(pid=654, poll=lambda: None)++ async def fail_after_replacement(_client, method, url, **_kwargs):+ manager._process = replacement_process+ manager._base_url = base_url+ raise httpx.ConnectError("old runtime failed late", request=httpx.Request(method, url))++ monkeypatch.setattr("core.show_runtime.httpx.AsyncClient.request", fail_after_replacement)++ with pytest.raises(ShowRuntimeUnavailableError):+ asyncio.run(manager.request_global("GET", "/health"))++ assert manager._process is replacement_process+ assert manager._base_url == base_url+++def test_runtime_transport_programming_error_stays_loud(monkeypatch, tmp_path):+ manager = _runtime_manager_with_failing_transport(monkeypatch, tmp_path)+ base_url = manager._base_url+ error = TypeError("request construction defect")++ async def fail_programming(_client, _method, _url, **_kwargs):+ raise error++ monkeypatch.setattr("core.show_runtime.httpx.AsyncClient.request", fail_programming)++ with pytest.raises(TypeError) as raised:+ asyncio.run(manager.request_global("GET", "/health"))++ assert raised.value is error+ assert manager._base_url == base_url+++def test_recovery_fact_consumption_census_has_no_default_producer():+ facts = ("reason", "failure_class", "recovery_action")+ projection = ast.parse(textwrap.dedent(inspect.getsource(ui_server._show_page_runtime_failure_evidence)))+ assert not any(isinstance(node, (ast.If, ast.IfExp)) for node in ast.walk(projection))+ returns = [node for node in ast.walk(projection) if isinstance(node, ast.Return)]+ assert len(returns) == 1+ assert isinstance(returns[0].value, ast.Tuple)+ assert tuple(element.attr for element in returns[0].value.elts if isinstance(element, ast.Attribute)) == facts++ exception_owner = ast.parse(textwrap.dedent(inspect.getsource(ShowRuntimeUnavailableError.__init__)))+ assignments = {+ target.attr+ for node in ast.walk(exception_owner)+ if isinstance(node, ast.Assign)+ for target in node.targets+ if isinstance(target, ast.Attribute) and isinstance(target.value, ast.Name) and target.value.id == "self"+ }+ assert assignments == set(facts)++ response_source = inspect.getsource(ui_server._show_page_recovery_response)+ html_source = inspect.getsource(show_pages_module.show_page_runtime_recovery_html)+ for fact, header, dataset in (+ ("reason", "X-Avibe-Show-Recovery-Reason", "data-show-runtime-reason"),+ ("failure_class", "X-Avibe-Show-Recovery-Class", "data-show-runtime-class"),+ ):+ assert response_source.count(header) == 1+ assert fact in response_source+ assert html_source.count(dataset) == 1+ assert fact in html_source++ recovery_source = inspect.getsource(show_pages_module._show_runtime_recovery_script)+ assert '|| "runtime_unavailable"' not in recovery_source+ assert '|| "unclassified"' not in recovery_source+ assert "checksRemaining" not in recovery_source+ assert "X-Avibe-Show-Recovery-Poll" not in recovery_source+++def test_runtime_http_transport_census_closes_every_direct_client_path():+ manager_tree = ast.parse(textwrap.dedent(inspect.getsource(ShowRuntimeManager)))+ functions = {+ node.name: node+ for node in manager_tree.body[0].body+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))+ }+ direct_clients = {+ name+ for name, function in functions.items()+ if any(isinstance(node, ast.Attribute) and node.attr == "AsyncClient" for node in ast.walk(function))+ }+ assert direct_clients == {+ "_healthy",+ "_probe_context_key_capability",+ "_request_runtime_transport",+ }+ for request_owner in ("request", "request_global"):+ calls = [+ node+ for node in ast.walk(functions[request_owner])+ if isinstance(node, ast.Call)+ and isinstance(node.func, ast.Attribute)+ and node.func.attr == "_request_runtime_transport"+ ]+ assert len(calls) == 1+ for internal_probe in ("_healthy", "_probe_context_key_capability"):+ assert any(isinstance(node, ast.Try) and node.handlers for node in ast.walk(functions[internal_probe]))+++def test_provider_install_entrypoints_converge_on_single_admission_owner():+ manager_tree = ast.parse(textwrap.dedent(inspect.getsource(ShowRuntimeManager))).body[0]+ functions = {+ node.name: node for node in manager_tree.body if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))+ }+ provider_methods = {+ "_install_manifest_runtime_locked",+ "_install_archive_runtime",+ "_install_github_runtime",+ "_install_npm_runtime",+ }+ direct_provider_callers = {+ function.name+ for function in functions.values()+ if any(+ isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.func.attr in provider_methods+ for node in ast.walk(function)+ )+ }+ assert direct_provider_callers == {"_install_managed_runtime_locked"}++ owner_callers = {+ function.name+ for function in functions.values()+ if any(+ isinstance(node, ast.Call)+ and isinstance(node.func, ast.Attribute)+ and node.func.attr == "_install_managed_runtime_locked"+ for node in ast.walk(function)+ )+ }+ assert owner_callers == {"_attempt_managed_install"}++ admission_callers = {+ function.name+ for function in functions.values()+ if any(+ isinstance(node, ast.Attribute) and node.attr == "_attempt_managed_install" for node in ast.walk(function)+ )+ }+ assert admission_callers == {"_resolve_managed_availability", "prepare"}+++def test_explicit_command_resolution_has_one_owner_and_four_consumers():+ manager_tree = ast.parse(textwrap.dedent(inspect.getsource(ShowRuntimeManager))).body[0]+ functions = {+ node.name: node for node in manager_tree.body if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))+ }+ direct_resolvers = {+ function.name+ for function in functions.values()+ if any(+ isinstance(node, ast.Call)+ and isinstance(node.func, ast.Name)+ and node.func.id == "_resolve_command"+ and node.args+ and isinstance(node.args[0], ast.Attribute)+ and isinstance(node.args[0].value, ast.Name)+ and node.args[0].value.id == "self"+ and node.args[0].attr == "command"+ for node in ast.walk(function)+ )+ }+ assert direct_resolvers == {"_resolve_explicit_command_availability"}++ consumers = {+ function.name+ for function in functions.values()+ if any(+ isinstance(node, ast.Call)+ and isinstance(node.func, ast.Attribute)+ and node.func.attr == "_resolve_explicit_command_availability"+ for node in ast.walk(function)+ )+ }+ assert consumers == {+ "_admit_runtime_start",+ "_managed_install_preflight",+ "_resolve_managed_availability",+ "status",+ }+++ ("spawn_error", "expected_reason", "expected_class", "expected_action"),+ (+ (+ FileNotFoundError(errno.ENOENT, "command disappeared"),+ "runtime_start_command_invalid",+ ShowRuntimeFailureClass.CONFIGURED,+ ShowRuntimeRecoveryAction.CHANGE_SETTING,+ ),+ (+ OSError(errno.EMFILE, "process table unavailable"),+ "runtime_start_attempt_failed",+ ShowRuntimeFailureClass.UNCLASSIFIED,+ ShowRuntimeRecoveryAction.REPAIR,+ ),+ ),+)+def test_start_admission_normalizes_spawn_exceptions(+ monkeypatch,+ tmp_path,+ spawn_error,+ expected_reason,+ expected_class,+ expected_action,+):+ manager = ShowRuntimeManager(+ command="/bin/runtime-cli",+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ )+ spawn_calls = []++ def fail_spawn(*_args, **_kwargs):+ spawn_calls.append(True)+ raise spawn_error++ monkeypatch.setattr("core.show_runtime._resolve_command", lambda command: [command])+ monkeypatch.setattr("core.show_runtime.subprocess.Popen", fail_spawn)++ first = asyncio.run(manager.ensure())+ second = asyncio.run(manager.ensure())++ assert first.reason == expected_reason+ assert first.runtime_failure_class is expected_class+ assert first.runtime_recovery_action is expected_action+ assert second.reason == expected_reason+ assert second.runtime_recovery_action is expected_action+ assert spawn_calls == [True, True]+++def test_managed_spawn_command_loss_is_repairable_evidence(monkeypatch, tmp_path):+ manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ runtime_source="npm",+ )++ async def managed_command(*, automatic):+ return manager._publish_install_availability(command=["managed-runtime"])++ monkeypatch.setattr(manager, "_resolve_managed_availability", managed_command)+ monkeypatch.setattr(+ "core.show_runtime.subprocess.Popen",+ lambda *_args, **_kwargs: (_ for _ in ()).throw(FileNotFoundError(errno.ENOENT, "gone")),+ )++ result = asyncio.run(manager.ensure())++ assert result.runtime_reason == "runtime_start_command_unavailable"+ assert result.runtime_failure_class is ShowRuntimeFailureClass.UNCLASSIFIED+ assert result.runtime_recovery_action is ShowRuntimeRecoveryAction.REPAIR++[email protected]("failure_phase", ("establish", "readiness"))+def test_start_admission_closes_establishment_and_readiness_exceptions(+ monkeypatch,+ tmp_path,+ failure_phase,+):+ manager = ShowRuntimeManager(+ command="/bin/runtime-cli",+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ )+ attempts = []++ class FakeProcess:+ def poll(self):+ return None++ monkeypatch.setattr("core.show_runtime._resolve_command", lambda command: [command])++ def stop():+ manager._process = None+ manager._base_url = None++ monkeypatch.setattr(manager, "stop", stop)+ if failure_phase == "establish":+ real_mkdir = Path.mkdir++ def fail_runtime_mkdir(path, *args, **kwargs):+ if path == manager.runtime_dir:+ attempts.append("establish")+ raise PermissionError("runtime directory is read-only")+ return real_mkdir(path, *args, **kwargs)++ monkeypatch.setattr(Path, "mkdir", fail_runtime_mkdir)+ else:+ monkeypatch.setattr(+ "core.show_runtime.subprocess.Popen",+ lambda *_args, **_kwargs: attempts.append("readiness") or FakeProcess(),+ )++ async def fail_readiness(*, deadline):+ raise OSError("startup log became unreadable")++ monkeypatch.setattr(manager, "_read_startup_url", fail_readiness)++ first = asyncio.run(manager.ensure())+ second = asyncio.run(manager.ensure())++ assert first.reason == "runtime_start_attempt_failed"+ assert first.runtime_failure_class is ShowRuntimeFailureClass.UNCLASSIFIED+ assert second.reason == "runtime_start_attempt_failed"+ assert attempts == [failure_phase, failure_phase]+++def test_cancelled_start_admission_stops_spawned_child_before_propagating(monkeypatch, tmp_path):+ manager = ShowRuntimeManager(+ command="/bin/runtime-cli",+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ )+ started = asyncio.Event()+ stopped = []++ class FakeProcess:+ def poll(self):+ return None++ async def wait_forever(*, deadline):+ started.set()+ await asyncio.Event().wait()++ monkeypatch.setattr("core.show_runtime._resolve_command", lambda command: [command])+ monkeypatch.setattr(+ "core.show_runtime.subprocess.Popen",+ lambda *_args, **_kwargs: FakeProcess(),+ )+ monkeypatch.setattr(manager, "_read_startup_url", wait_forever)++ def stop():+ if manager._process is not None:+ stopped.append(manager._process)+ manager._process = None+ manager._base_url = None++ monkeypatch.setattr(manager, "stop", stop)++ async def cancel_start():+ task = asyncio.create_task(manager.ensure())+ await started.wait()+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task++ asyncio.run(cancel_start())++ assert len(stopped) == 1+ assert manager._process is None+++def test_start_owner_normalizes_install_resolution_io_failure(monkeypatch, tmp_path):+ manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ runtime_source="npm",+ )++ async def fail_install_resolution(*, automatic):+ raise OSError("install owner escaped unexpectedly")++ monkeypatch.setattr(manager, "_resolve_managed_availability", fail_install_resolution)++ result = asyncio.run(manager.ensure())++ assert result.runtime_reason == "runtime_start_attempt_failed"+ assert result.runtime_failure_class is ShowRuntimeFailureClass.UNCLASSIFIED+ assert result.runtime_recovery_action is ShowRuntimeRecoveryAction.REPAIR++[email protected]("owner", ("install", "start"))+def test_admission_owners_propagate_programming_errors(monkeypatch, tmp_path, owner):+ manager = ShowRuntimeManager(+ command="/bin/runtime-cli" if owner == "start" else None,+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ runtime_source="npm",+ )+ if owner == "install":+ monkeypatch.setattr(+ manager,+ "_install_managed_runtime_locked",+ lambda **_kwargs: (_ for _ in ()).throw(TypeError("provider contract defect")),+ )+ operation = lambda: manager.prepare(automatic=True)+ else:+ monkeypatch.setattr("core.show_runtime._resolve_command", lambda command: [command])+ monkeypatch.setattr(+ "core.show_runtime.subprocess.Popen",+ lambda *_args, **_kwargs: (_ for _ in ()).throw(TypeError("spawn contract defect")),+ )+ operation = lambda: asyncio.run(manager.ensure())++ with pytest.raises(TypeError, match="contract defect"):+ operation()+++def test_show_runtime_manager_passes_runtime_options(monkeypatch, tmp_path):+ captured = {}++ class FakeProcess:+ def poll(self):+ return None++ def fake_popen(command, **kwargs):+ captured["command"] = command+ return FakeProcess()++ async def fake_startup_url(*, deadline):+ captured["startup_deadline"] = deadline+ return "http://127.0.0.1:12345"++ manager = ShowRuntimeManager(+ command="/bin/echo",+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ )+ monkeypatch.setattr("core.show_runtime._resolve_command", lambda command: [command])+ monkeypatch.setattr("core.show_runtime.subprocess.Popen", fake_popen)+ monkeypatch.setattr(manager, "_read_startup_url", fake_startup_url)+ monkeypatch.setattr(manager, "_healthy", lambda _base_url: asyncio.sleep(0, result=True))result = asyncio.run(manager.ensure())@@ -6233,7 +7833,7 @@ def test_show_runtime_manager_passes_runtime_options(monkeypatch, tmp_path):cache_index = captured["command"].index("--cache-root")assert captured["command"][cache_index + 1] == str(tmp_path / "runtime" / "vite-cache")index = captured["command"].index("--fallback-delay-seconds")- assert captured["command"][index + 1] == str(SHOW_RUNTIME_RECOVERY_LOADING_DELAY_SECONDS)+ assert captured["command"][index + 1] == str(SHOW_RUNTIME_CLI_FALLBACK_DELAY_SECONDS)assert captured["startup_deadline"] > 0@@ -6724,6 +8324,40 @@ def test_show_runtime_manager_reuses_installed_prebuilt_runtime_without_archive(assert manager._install_reason is None+ ("configured", "expected_class", "expected_action"),+ (+ (True, "configured", "change_setting"),+ (False, "unclassified", "repair"),+ ),+)+def test_missing_archive_publishes_source_owned_recovery_evidence(+ monkeypatch,+ tmp_path,+ configured,+ expected_class,+ expected_action,+):+ manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ runtime_source="archive",+ archive_path=tmp_path / "missing.tgz" if configured else None,+ archive_url=None if configured else "",+ )+ monkeypatch.setattr(+ "core.show_runtime._resolve_command",+ lambda command: ["/bin/node"] if command == "node" else None,+ )+ monkeypatch.setattr(manager, "_copy_packaged_runtime_archive", lambda: None)++ result = manager.prepare()++ assert result["reason"] == "runtime_archive_missing"+ assert result["install"]["failure_class"] == expected_class+ assert result["install"]["recovery_action"] == expected_action++def test_show_runtime_manager_forced_archive_fallback_reports_failed_operation_and_installed_state(monkeypatch,tmp_path,@@ -6943,6 +8577,8 @@ def test_show_runtime_manager_preserves_structured_http_download_error(monkeypatassert result["ok"] is Falseassert result["reason"] == "runtime_archive_download_failed"+ assert result["install"]["failure_class"] == "configured"+ assert result["install"]["recovery_action"] == "change_setting"assert result["status"]["download_error"] == {"kind": "http","message": "HTTP 404 Not Found",@@ -6956,6 +8592,104 @@ def test_show_runtime_manager_preserves_structured_http_download_error(monkeypatassert "secret" not in json.dumps(result)+ ("retryable", "expected_class", "expected_action"),+ (+ (False, "configured", "change_setting"),+ (True, "transient", "repair"),+ ),+)+def test_manifest_download_failure_publishes_measured_retryability(+ monkeypatch,+ tmp_path,+ retryable,+ expected_class,+ expected_action,+):+ manifest_url = "https://example.test/show-runtime-manifest.json"+ manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ manifest_url=manifest_url,+ )+ monkeypatch.setattr(+ "core.show_runtime._resolve_command",+ lambda command: ["/bin/node"] if command == "node" else None,+ )++ def fail_manifest(*_args, **_kwargs):+ raise dependency_network.DependencyNetworkError(+ {+ "kind": "network" if retryable else "http",+ "message": "manifest unavailable",+ "url": manifest_url,+ "host": "example.test",+ "exception_type": "HTTPError",+ "retryable": retryable,+ "attempts": 1,+ }+ )++ monkeypatch.setattr("core.show_runtime.fetch_bytes", fail_manifest)++ result = manager.prepare()++ assert result["reason"] == "runtime_manifest_download_failed"+ assert result["install"]["failure_class"] == expected_class+ assert result["install"]["recovery_action"] == expected_action+++ ("configured", "expected_class", "expected_action"),+ (+ (True, "configured", "change_setting"),+ (False, "unclassified", "repair"),+ ),+)+def test_archive_download_failure_publishes_url_provenance(+ monkeypatch,+ tmp_path,+ configured,+ expected_class,+ expected_action,+):+ archive_url = "https://example.test/runtime.tgz"+ monkeypatch.delenv("VIBE_SHOW_RUNTIME_ARCHIVE_URL", raising=False)+ manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ runtime_source="archive",+ archive_url=archive_url if configured else None,+ )+ monkeypatch.setattr(+ "core.show_runtime._resolve_command",+ lambda command: ["/bin/node"] if command == "node" else None,+ )+ monkeypatch.setattr(manager, "_copy_packaged_runtime_archive", lambda: None)++ def fail_archive(*_args, **_kwargs):+ raise dependency_network.DependencyNetworkError(+ {+ "kind": "http",+ "message": "HTTP 404 Not Found",+ "url": archive_url,+ "host": "example.test",+ "exception_type": "HTTPError",+ "http_status": 404,+ "retryable": False,+ "attempts": 1,+ }+ )++ monkeypatch.setattr("core.show_runtime.fetch_to_path", fail_archive)++ result = manager.prepare()++ assert result["reason"] == "runtime_archive_download_failed"+ assert result["install"]["failure_class"] == expected_class+ assert result["install"]["recovery_action"] == expected_action++def test_show_runtime_manager_retries_transient_archive_failure(monkeypatch, tmp_path):archive_path = _write_runtime_archive(tmp_path)archive_url = "https://example.test/runtime.tgz"@@ -7554,6 +9288,8 @@ def test_show_runtime_forced_prepare_refuses_explicit_command_replacement(monkeyassert result["policy"] == {"state": "allowed","reason": None,+ "failure_class": None,+ "recovery_action": None,}assert result["install"]["state"] == "installed"assert result["install"]["command"] == [str(local_bin)]@@ -7781,7 +9517,7 @@ def test_show_runtime_prepare_policy_truth_table(monkeypatch.setattr(manager,"_install_managed_runtime_locked",- lambda *, force, offline, automatic: calls.append((force, offline, automatic)) or command,+ lambda *, force, offline: calls.append((force, offline)) or command,)monkeypatch.setattr(manager, "status", lambda **_kwargs: {})@@ -7791,11 +9527,13 @@ def test_show_runtime_prepare_policy_truth_table(assert result["policy"] == {"state": "skipped" if expected_skip else "allowed","reason": skip_reason if expected_skip else None,+ "failure_class": "configured" if expected_skip else None,+ "recovery_action": "change_setting" if expected_skip else None,}assert result["install"]["state"] == ("absent" if expected_skip else "installed")assert result["runtime"]["state"] == "unchecked"assert result["ok"] is (not expected_skip)- assert calls == ([] if expected_skip else [(force, False, automatic)])+ assert calls == ([] if expected_skip else [(force, False)])def test_show_runtime_automatic_opt_out_does_not_fetch_remote_manifest(monkeypatch, tmp_path):@@ -7835,6 +9573,8 @@ def test_show_runtime_remote_manifest_install_remains_installed_when_source_is_uassert skipped["policy"] == {"state": "skipped","reason": "VIBE_SHOW_RUNTIME_AUTO_INSTALL",+ "failure_class": "configured",+ "recovery_action": "change_setting",}assert skipped["install"]["state"] == "installed"assert skipped["runtime"]["state"] == "unchecked"@@ -7886,6 +9626,7 @@ def test_show_runtime_status_keeps_installed_identity_separate_from_selected_man"state": "installed","reason": None,"failure_class": None,+ "recovery_action": None,"command": command,"install_dir": str(install_dir),"runtime_version": "runtime-test-ref",@@ -7979,12 +9720,12 @@ def test_show_runtime_policy_skip_preserves_independent_installed_state(tmp_path@pytest.mark.parametrize(- ("reason", "expected_class"),+ ("reason", "expected_class", "expected_action"),(- ("runtime_archive_download_failed", "transient"),- ("runtime_platform_unsupported", "permanent"),- ("runtime_archive_unavailable_offline", "configured"),- ("runtime_archive_checksum_mismatch", "checksum"),+ ("runtime_archive_download_failed", "transient", "repair"),+ ("runtime_platform_unsupported", "permanent", "no_local_action"),+ ("runtime_archive_unavailable_offline", "configured", "change_setting"),+ ("runtime_archive_checksum_mismatch", "checksum", "repair"),),)def test_show_runtime_availability_classifies_install_failure(@@ -7992,6 +9733,7 @@ def test_show_runtime_availability_classifies_install_failure(tmp_path,reason,expected_class,+ expected_action,):manager = ShowRuntimeManager(workspace_root=tmp_path / "show",@@ -7999,19 +9741,20 @@ def test_show_runtime_availability_classifies_install_failure(runtime_source="npm",)- def fail_install(*, force, offline, automatic):+ def fail_install(*, force, offline):manager._install_reason = reasonreturn Nonemonkeypatch.setattr(manager, "_install_managed_runtime_locked", fail_install)- result = manager.prepare()+ result = manager.prepare(automatic=True)assert result["policy"]["state"] == "allowed"assert result["install"] == {"state": "failed","reason": reason,"failure_class": expected_class,+ "recovery_action": expected_action,"command": None,"install_dir": None,"runtime_version": None,@@ -8032,13 +9775,13 @@ def test_show_runtime_prepare_options_do_not_mutate_shared_manager_state(monkeypmonkeypatch.setattr(manager,"_install_managed_runtime_locked",- lambda *, force, offline, automatic: calls.append((force, offline, automatic)) or ["/tmp/runtime"],+ lambda *, force, offline: calls.append((force, offline)) or ["/tmp/runtime"],)result = manager.prepare(force=True, offline=True)assert result["install"]["state"] == "installed"- assert calls == [(True, True, False)]+ assert calls == [(True, True)]assert manager.force_install is Falseassert manager.offline is False@@ -8054,8 +9797,8 @@ def test_show_runtime_prepare_and_request_share_one_install_admission(monkeypatccommand = [str(tmp_path / "runtime" / "avibe-show-runtime")]calls = []- def install(*, force, offline, automatic):- calls.append((force, offline, automatic))+ def install(*, force, offline):+ calls.append((force, offline))entered.set()assert release.wait(timeout=5)return command@@ -8075,7 +9818,7 @@ def test_show_runtime_prepare_and_request_share_one_install_admission(monkeypatcresolved = asyncio.run(resolve_during_prepare())prepare_thread.join(timeout=5)- assert calls == [(False, False, False)]+ assert calls == [(False, False)]assert prepared[0]["install"]["state"] == "installed"assert resolved.install.value == "installed"assert resolved.command == command@@ -8097,7 +9840,7 @@ def test_show_runtime_manager_installs_without_blocking_event_loop(monkeypatch,monkeypatch.setattr(manager,"_install_managed_runtime_locked",- lambda *, force, offline, automatic: fake_install(),+ lambda *, force, offline: fake_install(),)calls = []@@ -8108,7 +9851,10 @@ def test_show_runtime_manager_installs_without_blocking_event_loop(monkeypatch,monkeypatch.setattr("core.show_runtime.asyncio.to_thread", fake_to_thread)assert asyncio.run(manager._resolve_managed_command()) == [str(manager._managed_bin_path())]- assert [call.__name__ for call in calls] == ["_attempt_managed_install"]+ assert [call.__name__ for call in calls] == [+ "_safe_installed_managed_runtime_command",+ "_attempt_managed_install",+ ]def test_show_runtime_manager_fails_closed_when_manifest_is_absent(tmp_path):@@ -8259,44 +10005,6 @@ def test_show_runtime_manager_reuses_installed_github_runtime_without_git(monkeyassert 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",@@ -9100,8 +10808,9 @@ def test_public_show_page_skips_remote_login_but_requires_public_host(monkeypatcassert response.status_code == 200assert b"Loading Show Page" in response.content- assert b"Ready to visualize" in response.content- assert b"Copy prompt" in response.content+ assert b"The Show Runtime is unavailable" in response.content+ assert b"vibe doctor repair show-runtime" not in response.content+ assert b"Reload this page to try the request again" in response.contentassert b'src="./src/main.tsx"' not in response.contentmismatch = app.test_client().get(diff --git a/tests/test_vibe_cli.py b/tests/test_vibe_cli.pyindex 3ae768da9..be1c247be 100644--- a/tests/test_vibe_cli.py+++ b/tests/test_vibe_cli.py@@ -2327,6 +2327,7 @@ def test_repair_show_runtime_first_github_install_failure_does_not_claim_preserv"state": "absent","reason": None,"failure_class": None,+ "recovery_action": None,"command": None,"install_dir": None,"runtime_version": None,diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex 1a41d16d3..5aebf7bc3 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -29,6 +29,33 @@"heading": "You do not have access to this page","message": "Please contact the page owner to be added to the allowed list.","back": "Back to home"+ },+ "runtimeRecovery": {+ "title": "Show Runtime unavailable",+ "loading": "Loading Show Page",+ "eyebrow": "Show Page",+ "heading": "The Show Runtime is unavailable",+ "downloadMessage": "Avibe could not download the files needed to run this Show Page.",+ "offlineMessage": "Avibe is in offline mode and no verified Show Runtime archive is available.",+ "nodeMessage": "The installed Node.js runtime is missing or is not supported.",+ "platformMessage": "This platform is not supported by the current Show Runtime release.",+ "verificationMessage": "The Show Runtime files did not pass integrity verification.",+ "configurationMessage": "The configured Show Runtime source cannot be used.",+ "policyMessage": "Automatic Show Runtime installation is disabled by configuration.",+ "installMessage": "Avibe could not install the Show Runtime.",+ "startMessage": "The Show Runtime is installed but could not start.",+ "unavailableMessage": "Avibe could not start the service that renders this Show Page.",+ "repairHeading": "Repair the Show Runtime",+ "repairMessage": "Run this command in a terminal:",+ "settingsHeading": "Change the Show Runtime setting",+ "settingsMessage": "Change the setting or prerequisite shown below, then reload this page. The instance owner can also choose Retry now for one explicit attempt.",+ "unsupportedHeading": "No action is available here",+ "unsupportedMessage": "The reason is recorded below. No action on this machine can change it.",+ "ownerActionHeading": "Instance owner action required",+ "ownerActionMessage": "Reload this page to try the request again. If it still fails, ask the Avibe instance owner to run the available recovery action.",+ "reasonLabel": "Reason",+ "sessionLabel": "Session",+ "retryNow": "Retry now"}},"harness": {diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex f0b2420a5..db7b15af5 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -29,6 +29,33 @@"heading": "你无权访问此页面","message": "请联系页面所有者,将你的邮箱加入允许访问名单。","back": "返回首页"+ },+ "runtimeRecovery": {+ "title": "Show Runtime 暂时不可用",+ "loading": "正在加载 Show Page",+ "eyebrow": "Show Page",+ "heading": "Show Runtime 暂时不可用",+ "downloadMessage": "Avibe 无法下载运行此 Show Page 所需的文件。",+ "offlineMessage": "Avibe 当前处于离线模式,且没有可用的已验证 Show Runtime 归档。",+ "nodeMessage": "Node.js 未安装,或当前版本不受支持。",+ "platformMessage": "当前 Show Runtime 版本不支持此平台。",+ "verificationMessage": "Show Runtime 文件未通过完整性校验。",+ "configurationMessage": "当前配置的 Show Runtime 来源不可用。",+ "policyMessage": "配置已关闭 Show Runtime 自动安装。",+ "installMessage": "Avibe 无法安装 Show Runtime。",+ "startMessage": "Show Runtime 已安装,但无法启动。",+ "unavailableMessage": "Avibe 无法启动用于渲染此 Show Page 的服务。",+ "repairHeading": "修复 Show Runtime",+ "repairMessage": "请在终端运行以下命令:",+ "settingsHeading": "修改 Show Runtime 设置",+ "settingsMessage": "请修改下方所示的设置或前置条件,然后重新加载此页面。实例所有者也可以点击“立即重试”,发起一次显式尝试。",+ "unsupportedHeading": "此处没有可用操作",+ "unsupportedMessage": "原因记录如下;这台机器上的任何操作都无法改变这一结果。",+ "ownerActionHeading": "需要实例所有者处理",+ "ownerActionMessage": "请重新加载此页面,再次尝试请求;若仍然失败,请联系 Avibe 实例所有者执行可用的恢复操作。",+ "reasonLabel": "原因",+ "sessionLabel": "会话",+ "retryNow": "立即重试"}},"harness": {diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex eb274406a..5e6895fba 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -23,7 +23,7 @@ from datetime import datetime, timezonefrom enum import Enumfrom pathlib import Pathfrom types import SimpleNamespace-from typing import Any, Callable, Mapping+from typing import TYPE_CHECKING, Any, Callable, Mappingfrom urllib.parse import parse_qsl, quote, unquote, urlencode, urlparse, urlsplit, urlunsplitimport psutil@@ -81,6 +81,9 @@ from vibe.sentry_integration import init_sentryfrom storage.delivery_states import ADMITTED_DELIVERY_STATESfrom vibe.ui_memory_routes import register_memory_routes+if TYPE_CHECKING:+ from core.show_runtime import ShowRuntimeUnavailableError+logger = logging.getLogger(__name__)@@ -12895,8 +12898,8 @@ def _show_page_file_not_found_response():return response-def _show_page_runtime_unavailable_response():- return jsonify({"error": "show_runtime_unavailable"}), 503+def _show_page_runtime_unavailable_response(reason: str):+ return jsonify({"error": "show_runtime_unavailable", "reason": reason}), 503def _show_page_runtime_timeout_response():@@ -12922,14 +12925,16 @@ def _is_show_annotation_asset(asset_path: str) -> bool:def _show_page_runtime_error_response(asset_path: str, exc: Exception):- from core.show_runtime import ShowRuntimeRequestTimeoutError+ from core.show_runtime import ShowRuntimeRequestTimeoutError, ShowRuntimeUnavailableErrorif _is_show_page_api_handler_path(asset_path) and isinstance(exc,ShowRuntimeRequestTimeoutError,):return _show_page_runtime_timeout_response()- return _show_page_runtime_unavailable_response()+ if not isinstance(exc, ShowRuntimeUnavailableError):+ raise AssertionError("Show Runtime error response requires owner-published evidence")+ return _show_page_runtime_unavailable_response(exc.reason)def _is_show_page_entry_asset(asset_path: str) -> bool:@@ -13097,10 +13102,50 @@ def _is_denied_show_page_at_fs_path(decoded: str, *, session_id: str, confine_toreturn any(part.startswith(".") for part in workspace_relative.parts)-def _show_page_recovery_response(session_id: str):+def _show_page_runtime_failure_evidence(exc: "ShowRuntimeUnavailableError"):+ return (+ exc.reason,+ exc.failure_class,+ exc.recovery_action,+ )+++def _log_show_runtime_unavailable(reason: str, *, public: bool, fallback: bool) -> None:+ if fallback:+ target = "fallback public Show Page response" if public else "fallback Show Page response"+ else:+ target = "static public Show Page" if public else "static Show Page"+ message = f"Show runtime unavailable (%s); serving {target}"+ logger.warning(message, reason, exc_info=True)+++def _show_page_recovery_response(+ session_id: str,+ *,+ reason: str,+ failure_class,+ recovery_action,+ retry_authorized: bool,+):from core.show_pages import show_page_runtime_recovery_html- return Response(show_page_runtime_recovery_html(session_id), status=200, mimetype="text/html; charset=utf-8")+ response = Response(+ show_page_runtime_recovery_html(+ session_id,+ reason=reason,+ failure_class=failure_class,+ recovery_action=recovery_action,+ retry_authorized=retry_authorized,+ language=_request_ui_language(),+ ),+ status=200,+ mimetype="text/html; charset=utf-8",+ )+ response.headers["Cache-Control"] = "no-store"+ response.headers["X-Avibe-Show-Recovery"] = "1"+ response.headers["X-Avibe-Show-Recovery-Reason"] = reason+ response.headers["X-Avibe-Show-Recovery-Class"] = failure_class.value+ return responsedef _show_page_file_response(root: Path, asset_path: str):@@ -13131,6 +13176,11 @@ def _show_page_runtime_failure_response(session_id: str,asset_path: str,starlette_request: FastAPIRequest,+ *,+ reason: str,+ failure_class,+ recovery_action,+ retry_authorized: bool,):if not _is_show_page_spa_route_request(asset_path, starlette_request):return None@@ -13138,7 +13188,13 @@ def _show_page_runtime_failure_response(static_response = _show_page_file_response(page_dir, asset_path)if static_response.status_code != 404:return static_response- return _show_page_recovery_response(session_id)+ return _show_page_recovery_response(+ session_id,+ reason=reason,+ failure_class=failure_class,+ recovery_action=recovery_action,+ retry_authorized=retry_authorized,+ )def _show_session_event_error_response(exc: Exception):@@ -14138,7 +14194,7 @@ async def show_runtime_vendor_asset(vendor_path: str):runtime_path = f"{_SHOW_RUNTIME_VENDOR_PREFIX}/{quote(vendor_path, safe='/@:-._~')}"if request._request.url.query:runtime_path = f"{runtime_path}?{request._request.url.query}"- from core.show_runtime import get_show_runtime_manager+ from core.show_runtime import ShowRuntimeUnavailableError, get_show_runtime_managerforwarded_headers = _show_runtime_forwarded_headers(request._request.headers)try:@@ -14148,8 +14204,8 @@ async def show_runtime_vendor_asset(vendor_path: str):headers=forwarded_headers,body=None,)- except Exception:- return _show_page_runtime_unavailable_response()+ except ShowRuntimeUnavailableError as exc:+ return _show_page_runtime_unavailable_response(exc.reason)response_headers = {key: valuefor key, value in proxied.headers.items()@@ -14266,6 +14322,7 @@ async def _show_page_runtime_response(external_prefix: str | None = None,inject_show_config: bool = False,show_authenticated: bool = False,+ runtime_retry_authorized: bool = False,show_config_session_id: str | None = None,include_annotation_bootstrap: bool = True,):@@ -14313,6 +14370,10 @@ async def _show_page_runtime_response(envelope=envelope,headers=forwarded_headers,body=body or None,+ automatic=not (+ runtime_retry_authorized+ and starlette_request.headers.get("X-Avibe-Show-Recovery-Retry") == "1"+ ),**request_options,)proxy_duration_ms = int((time.monotonic() - request_started) * 1000)@@ -14894,12 +14955,14 @@ def redirect_private_show_page_to_canonical_path(session_id):async def serve_private_show_page(session_id, asset_path):from core.show_pages import ShowPageError, ShowPageStore, ensure_show_page_dir+ authorization_context = _request_authorization_context()+ runtime_retry_authorized = _has_runtime_owner_access(authorization_context)store = ShowPageStore()try:try:page = store.require_access(session_id,- user_context=_request_authorization_context(),+ user_context=authorization_context,)except ShowPageError as exc:if exc.code == "resource_access_forbidden":@@ -14930,7 +14993,7 @@ async def serve_private_show_page(session_id, asset_path):# §3.2: /show reads admit every Instance Viewer, but the route forwards# mutation methods straight to Show Runtime — keep Viewers read-only.if request.method not in {"GET", "HEAD"} and not _show_page_mutation_allowed(- _request_authorization_context()+ authorization_context):return _show_page_access_forbidden_response()if asset_path.strip("/") == "__show/me":@@ -14946,6 +15009,11 @@ async def serve_private_show_page(session_id, asset_path):page_dir = ensure_show_page_dir(page.session_id)response = Noneif request.method in {"GET", "HEAD"} or _is_show_api_asset(asset_path):+ from core.show_runtime import (+ ShowRuntimeRequestTimeoutError,+ ShowRuntimeUnavailableError,+ )+try:starlette_request = request._requestresponse = await _show_page_runtime_response(@@ -14954,8 +15022,12 @@ async def serve_private_show_page(session_id, asset_path):starlette_request,inject_show_config=request.method == "GET" and not _is_show_api_asset(asset_path),show_authenticated=can_annotate,+ runtime_retry_authorized=runtime_retry_authorized,)- except Exception as exc:+ except (ShowRuntimeUnavailableError, ShowRuntimeRequestTimeoutError) as exc:+ if isinstance(exc, ShowRuntimeRequestTimeoutError):+ return _show_page_runtime_error_response(asset_path, exc)+ reason, failure_class, recovery_action = _show_page_runtime_failure_evidence(exc)if _is_show_api_asset(asset_path) or _is_show_annotation_asset(asset_path):return _show_page_runtime_error_response(asset_path, exc)response = _show_page_runtime_failure_response(@@ -14963,11 +15035,12 @@ async def serve_private_show_page(session_id, asset_path):page.session_id,asset_path,request._request,+ reason=reason,+ failure_class=failure_class,+ recovery_action=recovery_action,+ retry_authorized=runtime_retry_authorized,)- if response is not None:- logger.debug("Show runtime unavailable; serving fallback Show Page response", exc_info=True)- else:- logger.debug("Show runtime unavailable; serving static Show Page", exc_info=True)+ _log_show_runtime_unavailable(reason, public=False, fallback=response is not None)if response is None:response = _show_page_file_response(page_dir, asset_path)if request.method in {"GET", "HEAD"}:@@ -15441,6 +15514,11 @@ async def serve_public_show_page(share_id, asset_path):page_dir = ensure_show_page_dir(page.session_id)response = Noneif request.method in {"GET", "HEAD"} or _is_show_api_asset(asset_path):+ from core.show_runtime import (+ ShowRuntimeRequestTimeoutError,+ ShowRuntimeUnavailableError,+ )+try:starlette_request = request._requestshow_authenticated = False@@ -15453,10 +15531,14 @@ async def serve_public_show_page(share_id, asset_path):external_prefix=f"/p/{quote(share_id, safe='')}",inject_show_config=request.method == "GET" and not _is_show_api_asset(asset_path),show_authenticated=show_authenticated,+ runtime_retry_authorized=False,show_config_session_id=share_id,include_annotation_bootstrap=not limited_guest,)- except Exception as exc:+ except (ShowRuntimeUnavailableError, ShowRuntimeRequestTimeoutError) as exc:+ if isinstance(exc, ShowRuntimeRequestTimeoutError):+ return _show_page_runtime_error_response(asset_path, exc)+ reason, failure_class, recovery_action = _show_page_runtime_failure_evidence(exc)if _is_show_api_asset(asset_path) or _is_show_annotation_asset(asset_path):return _show_page_runtime_error_response(asset_path, exc)response = _show_page_runtime_failure_response(@@ -15464,11 +15546,12 @@ async def serve_public_show_page(share_id, asset_path):page.session_id,asset_path,request._request,+ reason=reason,+ failure_class=failure_class,+ recovery_action=recovery_action,+ retry_authorized=False,)- if response is not None:- logger.debug("Show runtime unavailable; serving fallback public Show Page response", exc_info=True)- else:- logger.debug("Show runtime unavailable; serving static public Show Page", exc_info=True)+ _log_show_runtime_unavailable(reason, public=True, fallback=response is not None)if response is None:response = _show_page_file_response(page_dir, asset_path)if limited_guest: