Skip to content

armgit / avibe

Public Imported from GitHub
0

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

fix(show-runtime): make Show Page API timeout configurable (#1636)

Call Whitec21aa2741f59
diff --git a/README.md b/README.md
index 5d2e1329e..f08d3ead9 100644
--- a/README.md
+++ b/README.md
@@ -90,6 +90,9 @@ When a picture beats a paragraph, your agent hands you a live web page — a flo
In Chat, click **Visualize** to switch the current session to its Show Page. Hover the button to open the page in a new app window or browser tab. You can also drag the button downward and release to place a new app window at the pointer, or drop it on **Apps** to pin that Show Page to the Dock.
+See [Show Pages](docs/SHOW_PAGES.md) for synchronous API timeout behavior and
+guidance for longer background refreshes.
+
<img src="assets/screenshots/v4/show-page-en.png" alt="Show Page review with anchored comments and Agent replies on the page" />
### 🔐 Vaults — secret values stay out of Vault responses
diff --git a/config/v2_config.py b/config/v2_config.py
index 743033c38..0684fd948 100644
--- a/config/v2_config.py
+++ b/config/v2_config.py
@@ -160,6 +160,7 @@ def _contains_model_hub_credential_material(value: object) -> bool:
return any(pattern.search(rendered) for pattern in _MODEL_HUB_CREDENTIAL_PATTERNS)
DEFAULT_AGENT_IDLE_TIMEOUT_SECONDS = 600
+DEFAULT_SHOW_PAGE_API_TIMEOUT_SECONDS = 90.0
# Harness run staleness sweep (``docs/plans/agent-run-zombie-settlement.md`` §4.4).
# How often the sweep may run at all — it rides the scheduler's existing 2 s tick, so
@@ -2481,6 +2482,10 @@ def memory_config_from_payload(payload: object) -> MemoryConfig:
class RuntimeConfig:
default_cwd: str
log_level: str = "INFO"
+ # Synchronous handlers under /show/*/api and /p/*/api may depend on slower
+ # operational systems. Keep this separate from ordinary Runtime asset
+ # requests, which retain their shorter transport timeout.
+ show_page_api_timeout_seconds: float = DEFAULT_SHOW_PAGE_API_TIMEOUT_SECONDS
# Linux/cgroup v2 best-effort resource governance for aggregate agent
# workload. "auto" enables it only when Avibe can create and write the
# delegated cgroup; unsupported systems silently fall back to legacy spawn.
@@ -2503,6 +2508,17 @@ class RuntimeConfig:
# today's behavior (result only).
harness_prompt_echo: bool = True
+ def __post_init__(self) -> None:
+ self.show_page_api_timeout_seconds = _named_value(
+ "runtime.show_page_api_timeout_seconds",
+ float,
+ self.show_page_api_timeout_seconds,
+ )
+ if self.show_page_api_timeout_seconds <= 0:
+ raise ValueError(
+ "Config 'runtime.show_page_api_timeout_seconds' must be greater than zero"
+ )
+
@dataclass
class OpenCodeConfig:
@@ -4159,6 +4175,7 @@ class V2Config:
"runtime": {
"default_cwd": self.runtime.default_cwd,
"log_level": self.runtime.log_level,
+ "show_page_api_timeout_seconds": self.runtime.show_page_api_timeout_seconds,
"resource_governance": self.runtime.resource_governance,
"harness_run_sweep_interval_seconds": self.runtime.harness_run_sweep_interval_seconds,
"harness_run_orphan_grace_seconds": self.runtime.harness_run_orphan_grace_seconds,
diff --git a/core/show_runtime.py b/core/show_runtime.py
index 217a9f006..881df0296 100644
--- a/core/show_runtime.py
+++ b/core/show_runtime.py
@@ -112,6 +112,7 @@ SHOW_RUNTIME_PROTOCOL_HEADER = "X-Avibe-Show-Protocol"
SHOW_RUNTIME_CONTEXT_HEADER = "X-Avibe-Show-Context"
SHOW_RUNTIME_BASE_HEADER = "x-vibe-show-base"
SHOW_RUNTIME_CONTEXT_KEY_FEATURE = "show-context-key-v1"
+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}
@@ -162,6 +163,10 @@ class ShowRuntimeResult:
reason: str | None = None
+class ShowRuntimeRequestTimeoutError(TimeoutError):
+ """A proxied Runtime request exceeded its total request deadline."""
+
+
@dataclass(frozen=True)
class ShowRuntimeArchive:
platform: str
@@ -318,6 +323,7 @@ class ShowRuntimeManager:
envelope: ShowRuntimeProtocolEnvelope,
headers: dict[str, str] | None = None,
body: bytes | None = None,
+ timeout_seconds: float | None = None,
) -> httpx.Response:
ready = await self.ensure()
if not ready.available or not ready.base_url:
@@ -330,13 +336,31 @@ class ShowRuntimeManager:
}
if session_part := _show_runtime_app_session_part(path):
request_headers[SHOW_RUNTIME_BASE_HEADER] = f"/show/{session_part}/"
- async with httpx.AsyncClient(timeout=httpx.Timeout(30.0, connect=5.0)) as client:
- return await client.request(
+ phase_timeout_seconds = (
+ SHOW_RUNTIME_REQUEST_TIMEOUT_SECONDS
+ if timeout_seconds is None
+ else 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 exc
async def request_global(
self,
diff --git a/docs/SHOW_PAGES.md b/docs/SHOW_PAGES.md
new file mode 100644
index 000000000..5709e0fb2
--- /dev/null
+++ b/docs/SHOW_PAGES.md
@@ -0,0 +1,36 @@
+# Show Pages
+
+## Synchronous API Requests
+
+Show Page API handlers under `/show/<session>/api/` and `/p/<share>/api/` have a
+90-second request timeout by default. A handler that exceeds the deadline returns
+HTTP 504 with this machine-readable body:
+
+```json
+{"error":"show_runtime_request_timeout"}
+```
+
+A Runtime startup, installation, or transport failure remains a different
+condition and returns HTTP 503 with `show_runtime_unavailable`.
+
+Owners can change the synchronous API deadline through the normal V2Config API:
+
+```json
+{
+ "runtime": {
+ "show_page_api_timeout_seconds": 120
+ }
+}
+```
+
+Send this as a partial `POST /api/config` payload using the same CSRF-protected
+settings API as other global configuration. The value must be a finite number
+greater than zero and applies to subsequent Show Page API requests without a
+service restart. Ordinary Show Page assets keep their shorter Runtime transport
+timeout.
+
+Use synchronous handlers only when the work can reliably finish inside the
+configured deadline. Longer operational work should start a background refresh,
+return an accepted response, store a cached snapshot, and let the page poll that
+snapshot. Raising the deadline should not replace a background job for work that
+can take several minutes or survive a browser disconnect.
diff --git a/docs/plans/show-page-api-timeout.md b/docs/plans/show-page-api-timeout.md
new file mode 100644
index 000000000..8d3a40244
--- /dev/null
+++ b/docs/plans/show-page-api-timeout.md
@@ -0,0 +1,53 @@
+# Show Page API Request Timeout
+
+## Background
+
+Show Runtime currently gives every proxied HTTP request the same 30-second
+transport timeout. That is appropriate for page assets, but it turns a healthy,
+slow synchronous Show Page API handler into the same 503 response used when the
+Runtime itself is unavailable.
+
+PR #1634 separately changes the Show Runtime admission-outcome contract in the
+same core and UI proxy files. This change remains based on `origin/master` and
+adds a narrow per-call timeout contract so either merge order can preserve both
+owners without making one PR depend on the other.
+
+## Goal
+
+- Give Show Page API handlers a 90-second default deadline.
+- Expose the deadline as `runtime.show_page_api_timeout_seconds` through the
+ existing V2Config and `GET`/`POST /api/config` contract.
+- Return HTTP 504 with `show_runtime_request_timeout` for an expired handler,
+ while preserving HTTP 503 with `show_runtime_unavailable` for other Runtime
+ failures.
+- Preserve the existing 30-second behavior for ordinary page assets, shared
+ Runtime assets, prewarming, access control, and header filtering.
+
+## Solution
+
+The UI proxy resolves the V2Config value when it forwards a page-authored
+`/api` request and passes it explicitly to `ShowRuntimeManager.request`. An
+omitted timeout preserves the manager's existing 30-second HTTPX phase timeout
+without adding a total deadline, so ordinary assets, prewarming, and Runtime
+protocol paths remain unchanged. Config writes affect subsequent page API
+requests without restarting Avibe.
+
+The Runtime manager wraps the HTTP request in an overall cancellation deadline,
+so a response that keeps streaming small chunks cannot run indefinitely. It
+normalizes both deadline expiry and HTTPX read expiry into a dedicated exception.
+The response boundary maps that exception to 504 only for page-authored `api`
+and `api/*` paths. The broader `__show/*` Runtime protocol space, annotation,
+connection, and other Runtime failures stay on the unavailable path. This keeps
+the machine contract stable without coupling V2Config into the Runtime manager
+or adding an environment-only source of truth.
+
+## Validation
+
+- V2Config default, validation, persistence, projection, and partial-save tests
+- Runtime transport timeout tests for the 30-second default and per-call override
+- Private and public Show Page API proxy tests for the 90-second default,
+ immediate config updates, distinct timeout errors, access behavior, and
+ security-header filtering
+
+Residual manual validation is one real handler that completes after 30 seconds
+and before 90 seconds through both private and public URLs.
diff --git a/tests/test_api_save_config_merge.py b/tests/test_api_save_config_merge.py
index df2409d93..f9dc7c376 100644
--- a/tests/test_api_save_config_merge.py
+++ b/tests/test_api_save_config_merge.py
@@ -15,6 +15,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from config.v2_config import (
_FIELD_SCOPED_RECOVERY_SECTIONS,
AudioAsrConfig,
+ RuntimeConfig,
UiConfig,
V2Config,
VibeCloudRemoteAccessConfig,
@@ -538,6 +539,38 @@ def test_save_config_preserves_harness_runtime_knobs_on_partial_save(monkeypatch
assert payload["runtime"]["harness_run_queued_ttl_seconds"] == 4242
+def test_show_page_api_timeout_defaults_round_trips_and_survives_partial_save(
+ monkeypatch,
+ tmp_path,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+
+ defaulted = V2Config.from_payload(_full_config_payload())
+ assert defaulted.runtime.show_page_api_timeout_seconds == 90.0
+
+ full = _full_config_payload()
+ full["runtime"]["show_page_api_timeout_seconds"] = 135
+ created = api.save_config(full)
+ assert created.runtime.show_page_api_timeout_seconds == 135.0
+
+ updated = api.save_config({"show_duration": False})
+ payload = api.config_to_payload(updated)
+ assert updated.runtime.show_page_api_timeout_seconds == 135.0
+ assert payload["runtime"]["show_page_api_timeout_seconds"] == 135.0
+
+
[email protected]("value", [0, -1, True, float("inf"), float("nan")])
+def test_show_page_api_timeout_rejects_values_that_do_not_name_a_deadline(value):
+ payload = _full_config_payload()
+ payload["runtime"]["show_page_api_timeout_seconds"] = value
+
+ with pytest.raises(
+ ValueError,
+ match="Config 'runtime.show_page_api_timeout_seconds'",
+ ):
+ V2Config.from_payload(payload)
+
+
def test_config_load_defaults_missing_show_pages_prompt_to_enabled():
payload = _full_config_payload()
payload.pop("show_pages_prompt")
@@ -1093,6 +1126,7 @@ def test_full_config_serializers_cover_every_config_field(monkeypatch, tmp_path)
config = api.save_config(_full_config_payload())
ui_field_names = {f.name for f in fields(UiConfig)}
+ runtime_field_names = {f.name for f in fields(RuntimeConfig)}
# ``platform_configs`` is the internal per-platform aggregate; it is emitted
# under each platform's own key, not as a top-level ``platform_configs`` key.
top_level = {f.name for f in fields(V2Config)} - {"platform_configs"}
@@ -1101,6 +1135,9 @@ def test_full_config_serializers_cover_every_config_field(monkeypatch, tmp_path)
def _assert_complete(label: str, payload: dict) -> None:
assert top_level <= set(payload), f"{label} top-level missing: {top_level - set(payload)}"
assert ui_field_names <= set(payload["ui"]), f"{label} ui missing: {ui_field_names - set(payload['ui'])}"
+ assert runtime_field_names <= set(payload["runtime"]), (
+ f"{label} runtime missing: {runtime_field_names - set(payload['runtime'])}"
+ )
assert agents <= set(payload["agents"]), f"{label} agents missing: {agents - set(payload['agents'])}"
assert payload["agents"]["opencode"]["active_turn_timeout_seconds"] == 7200
diff --git a/tests/test_show_runtime_protocol.py b/tests/test_show_runtime_protocol.py
index a8d48095a..ca3539494 100644
--- a/tests/test_show_runtime_protocol.py
+++ b/tests/test_show_runtime_protocol.py
@@ -13,6 +13,7 @@ from core.show_runtime import (
ShowRuntimeContextCapability,
ShowRuntimeManager,
ShowRuntimeProtocolEnvelope,
+ ShowRuntimeRequestTimeoutError,
ShowRuntimeResult,
)
@@ -154,6 +155,180 @@ def test_show_live_015_transient_probe_keeps_shared_request_live_and_retries(
assert all("X-Vibe-Show-Base" not in call[2] for call in requests)
+ ("timeout_seconds", "expected_read_timeout"),
+ [(None, 30.0), (90.0, 90.0)],
+)
+def test_show_runtime_request_accepts_per_call_timeout_without_changing_connect_timeout(
+ monkeypatch,
+ tmp_path,
+ timeout_seconds,
+ expected_read_timeout,
+):
+ manager = _manager(tmp_path)
+ manager._base_url = "http://127.0.0.1:4173"
+ captured_timeouts = []
+ captured_deadlines = []
+ original_wait_for = asyncio.wait_for
+
+ async def ensure():
+ return ShowRuntimeResult(True, manager._base_url)
+
+ async def negotiate(_base_url):
+ return None
+
+ class _AppClient:
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *_args):
+ return None
+
+ async def request(self, _method, _url, *, headers, content):
+ return httpx.Response(200, content=b"ready")
+
+ def client_factory(*, timeout):
+ captured_timeouts.append(timeout)
+ return _AppClient()
+
+ async def wait_for(awaitable, *, timeout):
+ captured_deadlines.append(timeout)
+ return await original_wait_for(awaitable, timeout=timeout)
+
+ monkeypatch.setattr(manager, "ensure", ensure)
+ monkeypatch.setattr(manager, "_negotiate_context_key_capability", negotiate)
+ monkeypatch.setattr(show_runtime.httpx, "AsyncClient", client_factory)
+ monkeypatch.setattr(show_runtime.asyncio, "wait_for", wait_for)
+ envelope = ShowRuntimeProtocolEnvelope(ShowRuntimeContext.PRIVATE)
+
+ kwargs = {} if timeout_seconds is None else {"timeout_seconds": timeout_seconds}
+ asyncio.run(manager.request("GET", "/sessions/ses/app/api/slow", envelope=envelope, **kwargs))
+
+ assert len(captured_timeouts) == 1
+ assert captured_timeouts[0].connect == 5.0
+ assert captured_timeouts[0].read == expected_read_timeout
+ assert captured_timeouts[0].write == expected_read_timeout
+ assert captured_timeouts[0].pool == expected_read_timeout
+ assert captured_deadlines == ([] if timeout_seconds is None else [timeout_seconds])
+
+
+def test_show_runtime_default_read_timeout_is_not_converted(monkeypatch, tmp_path):
+ manager = _manager(tmp_path)
+ manager._base_url = "http://127.0.0.1:4173"
+ read_timeout = httpx.ReadTimeout(
+ "Runtime response stalled",
+ request=httpx.Request("GET", manager._base_url),
+ )
+
+ async def ensure():
+ return ShowRuntimeResult(True, manager._base_url)
+
+ async def negotiate(_base_url):
+ return None
+
+ class _AppClient:
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *_args):
+ return None
+
+ async def request(self, _method, _url, *, headers, content):
+ raise read_timeout
+
+ async def unexpected_wait_for(*_args, **_kwargs):
+ raise AssertionError("default Runtime requests must not use a total deadline")
+
+ monkeypatch.setattr(manager, "ensure", ensure)
+ monkeypatch.setattr(manager, "_negotiate_context_key_capability", negotiate)
+ monkeypatch.setattr(show_runtime.httpx, "AsyncClient", lambda **_kwargs: _AppClient())
+ monkeypatch.setattr(show_runtime.asyncio, "wait_for", unexpected_wait_for)
+ envelope = ShowRuntimeProtocolEnvelope(ShowRuntimeContext.PRIVATE)
+
+ with pytest.raises(httpx.ReadTimeout) as raised:
+ asyncio.run(manager.request("GET", "/sessions/ses/app/src/main.tsx", envelope=envelope))
+
+ assert raised.value is read_timeout
+
+
+def test_show_runtime_explicit_read_timeout_is_converted(monkeypatch, tmp_path):
+ manager = _manager(tmp_path)
+ manager._base_url = "http://127.0.0.1:4173"
+ read_timeout = httpx.ReadTimeout(
+ "API response stalled",
+ request=httpx.Request("GET", manager._base_url),
+ )
+
+ async def ensure():
+ return ShowRuntimeResult(True, manager._base_url)
+
+ async def negotiate(_base_url):
+ return None
+
+ class _AppClient:
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *_args):
+ return None
+
+ async def request(self, _method, _url, *, headers, content):
+ raise read_timeout
+
+ monkeypatch.setattr(manager, "ensure", ensure)
+ monkeypatch.setattr(manager, "_negotiate_context_key_capability", negotiate)
+ monkeypatch.setattr(show_runtime.httpx, "AsyncClient", lambda **_kwargs: _AppClient())
+ envelope = ShowRuntimeProtocolEnvelope(ShowRuntimeContext.PRIVATE)
+
+ with pytest.raises(ShowRuntimeRequestTimeoutError) as raised:
+ asyncio.run(
+ manager.request(
+ "GET",
+ "/sessions/ses/app/api/slow",
+ envelope=envelope,
+ timeout_seconds=90,
+ )
+ )
+
+ assert raised.value.__cause__ is read_timeout
+
+
+def 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():
+ return ShowRuntimeResult(True, manager._base_url)
+
+ async def negotiate(_base_url):
+ return None
+
+ class _AppClient:
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *_args):
+ return None
+
+ async def request(self, _method, _url, *, headers, content):
+ await asyncio.Event().wait()
+
+ monkeypatch.setattr(manager, "ensure", ensure)
+ monkeypatch.setattr(manager, "_negotiate_context_key_capability", negotiate)
+ monkeypatch.setattr(show_runtime.httpx, "AsyncClient", lambda **_kwargs: _AppClient())
+ envelope = ShowRuntimeProtocolEnvelope(ShowRuntimeContext.PRIVATE)
+
+ with pytest.raises(ShowRuntimeRequestTimeoutError, match="exceeded 0.01 seconds"):
+ asyncio.run(
+ manager.request(
+ "GET",
+ "/sessions/ses/app/api/slow",
+ envelope=envelope,
+ timeout_seconds=0.01,
+ )
+ )
+
+
def test_show_live_014_capability_cache_resets_with_process_base_and_manager_lifetime(
monkeypatch,
tmp_path,
diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.py
index 575611f17..c9a5c913b 100644
--- a/tests/test_ui_server_fastapi.py
+++ b/tests/test_ui_server_fastapi.py
@@ -1786,6 +1786,29 @@ def test_config_get_on_fresh_install_returns_default_needing_setup(monkeypatch,
assert not paths.get_config_path().exists(), "GET must not persist a config file"
+def test_show_page_api_timeout_round_trips_through_config_routes(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ from vibe import api
+
+ api.save_config(_full_config_payload())
+ client = app.test_client()
+
+ initial = client.get("/api/config")
+ updated = client.post(
+ "/api/config",
+ json={"runtime": {"show_page_api_timeout_seconds": 12.5}},
+ headers=csrf_headers(client),
+ )
+ fetched = client.get("/api/config")
+
+ assert initial.status_code == 200
+ assert initial.get_json()["runtime"]["show_page_api_timeout_seconds"] == 90.0
+ assert updated.status_code == 200
+ assert updated.get_json()["runtime"]["show_page_api_timeout_seconds"] == 12.5
+ assert fetched.status_code == 200
+ assert fetched.get_json()["runtime"]["show_page_api_timeout_seconds"] == 12.5
+
+
def test_first_config_post_starts_remote_access_monitoring(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
monkeypatch.setattr(ui_server, "_UI_RUNTIME_ACTIVE", True)
diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.py
index 220d344ba..5d67fc0e2 100644
--- a/tests/test_ui_show_pages.py
+++ b/tests/test_ui_show_pages.py
@@ -16,6 +16,7 @@ from pathlib import Path
from types import SimpleNamespace
from unittest.mock import patch
+import httpx
import pytest
from starlette.websockets import WebSocketDisconnect
@@ -35,6 +36,7 @@ from core.show_pages import (
from core.show_runtime import (
ShowRuntimeContext,
ShowRuntimeManager,
+ ShowRuntimeRequestTimeoutError,
ShowRuntimeWebSocketTarget,
_runtime_download_error,
_runtime_platform_tag,
@@ -88,6 +90,7 @@ class _FakeShowRuntimeManager:
*,
body: bytes = b"Runtime Show Page",
fail: bool = False,
+ error: Exception | None = None,
status_code: int = 200,
extra_headers: dict[str, str] | None = None,
headers_by_path: dict[str, dict[str, str]] | None = None,
@@ -96,6 +99,7 @@ class _FakeShowRuntimeManager:
):
self.body = body
self.fail = fail
+ self.error = error
self.status_code = status_code
self.extra_headers = extra_headers or {}
self.headers_by_path = headers_by_path or {}
@@ -106,10 +110,21 @@ class _FakeShowRuntimeManager:
self.websocket_headers = []
self.stopped = False
- async def request(self, method, path, *, envelope, headers=None, body=None):
+ async def request(
+ self,
+ method,
+ path,
+ *,
+ envelope,
+ headers=None,
+ body=None,
+ timeout_seconds=None,
+ ):
import httpx
- self.calls.append((method, path, envelope.headers(headers), body))
+ self.calls.append((method, path, envelope.headers(headers), body, timeout_seconds))
+ if self.error is not None:
+ raise self.error
if self.fail:
raise RuntimeError("runtime unavailable")
headers = {
@@ -2635,6 +2650,36 @@ def test_show_annotation_bootstrap_asset_proxies_to_runtime(monkeypatch, tmp_pat
assert manager.calls[0][1] == "/sessions/ses123/app/__show/annotation.js"
[email protected]("surface", ["private", "public"])
[email protected]("runtime_path", ["__show/annotation.js", "__show/runtime-probe"])
+def test_show_protocol_timeout_remains_runtime_unavailable(
+ monkeypatch,
+ tmp_path,
+ surface,
+ runtime_path,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ if surface == "private":
+ _create_show_page("ses123", "private")
+ path = f"/show/ses123/{runtime_path}"
+ 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")
+ )
+ set_show_runtime_manager_for_tests(manager)
+ try:
+ response = app.test_client().get(path, base_url="http://127.0.0.1:5123")
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert response.status_code == 503
+ assert response.get_json() == {"error": "show_runtime_unavailable"}
+ assert manager.calls[0][4] is None
+
+
def test_private_show_page_does_not_inject_runtime_event_config_into_attachment_html(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
_save_config(tmp_path)
@@ -3536,6 +3581,83 @@ def test_private_show_page_proxies_runtime_api_methods(monkeypatch, tmp_path):
assert manager.calls[0][2]["X-Avibe-Show-Context"] == "private"
assert "cookie" not in manager.calls[0][2]
assert manager.calls[0][3] == b'{"ping":true}'
+ assert manager.calls[0][4] == 90.0
+ assert response.headers["x-content-type-options"] == "nosniff"
+ assert "x-runtime-private-header" not in response.headers
+ assert "__Host-vibe_remote_session=attacker" not in response.headers.get("set-cookie", "")
+
+
+def test_private_show_page_api_uses_live_v2_config_timeout(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ config.runtime.show_page_api_timeout_seconds = 12.5
+ config.save()
+ _create_show_page("ses123", "private")
+ manager = _FakeShowRuntimeManager(body=b'{"ok":true}')
+ set_show_runtime_manager_for_tests(manager)
+ try:
+ response = app.test_client().get(
+ "/show/ses123/api/slow",
+ base_url="http://127.0.0.1:5123",
+ )
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert response.status_code == 200
+ assert manager.calls[0][4] == 12.5
+
+
[email protected]("public", [False, True])
+def test_show_page_api_timeout_is_distinct_from_runtime_unavailable(
+ monkeypatch,
+ tmp_path,
+ public,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ share_id = _create_show_page("ses123", "public" if public else "private")
+ timeout = ShowRuntimeRequestTimeoutError("Show Runtime request exceeded 90 seconds")
+ manager = _FakeShowRuntimeManager(error=timeout)
+ set_show_runtime_manager_for_tests(manager)
+ try:
+ if public:
+ response = app.test_client().get(
+ f"/p/{share_id}/api/slow",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ )
+ else:
+ response = app.test_client().get(
+ "/show/ses123/api/slow",
+ base_url="http://127.0.0.1:5123",
+ )
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert response.status_code == 504
+ assert response.get_json() == {"error": "show_runtime_request_timeout"}
+
+
+def test_show_page_api_connect_timeout_remains_runtime_unavailable(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)
+ set_show_runtime_manager_for_tests(manager)
+ try:
+ response = app.test_client().get(
+ "/show/ses123/api/slow",
+ base_url="http://127.0.0.1:5123",
+ )
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert response.status_code == 503
+ assert response.get_json() == {"error": "show_runtime_unavailable"}
def test_private_show_page_records_show_event(monkeypatch, tmp_path):
@@ -8212,6 +8334,10 @@ def test_public_show_page_proxies_runtime_api_methods(monkeypatch, tmp_path):
assert manager.calls[0][2]["X-Avibe-Show-Context"] == "shared"
assert "cookie" not in manager.calls[0][2]
assert manager.calls[0][3] == b'{"ping":true}'
+ assert manager.calls[0][4] == 90.0
+ assert response.headers["x-content-type-options"] == "nosniff"
+ assert "x-runtime-private-header" not in response.headers
+ assert "__Host-vibe_remote_session=attacker" not in response.headers.get("set-cookie", "")
def test_public_show_page_api_mutation_rejects_cross_origin(monkeypatch, tmp_path):
diff --git a/vibe/api.py b/vibe/api.py
index ebb213124..09d9bf231 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -1331,6 +1331,7 @@ def config_to_payload(
"runtime": {
"default_cwd": config.runtime.default_cwd,
"log_level": config.runtime.log_level,
+ "show_page_api_timeout_seconds": config.runtime.show_page_api_timeout_seconds,
"resource_governance": config.runtime.resource_governance,
# The config-only Harness knobs have no UI, but this payload IS the
# deep-merge base every ``/api/config`` save builds on: a key omitted here
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index b3648b206..a8bea3c74 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -12899,17 +12899,39 @@ def _show_page_runtime_unavailable_response():
return jsonify({"error": "show_runtime_unavailable"}), 503
+def _show_page_runtime_timeout_response():
+ return jsonify({"error": "show_runtime_request_timeout"}), 504
+
+
+def _is_show_page_api_handler_path(asset_path: str) -> bool:
+ relative = (asset_path or "").strip("/")
+ return relative == "api" or relative.startswith("api/")
+
+
def _is_show_api_asset(asset_path: str) -> bool:
relative = (asset_path or "").strip("/")
+ if _is_show_page_api_handler_path(asset_path):
+ return True
if relative == "__show/annotation.js":
return False
- return relative == "api" or relative.startswith("api/") or relative == "__show" or relative.startswith("__show/")
+ return relative == "__show" or relative.startswith("__show/")
def _is_show_annotation_asset(asset_path: str) -> bool:
return (asset_path or "").strip("/") == "__show/annotation.js"
+def _show_page_runtime_error_response(asset_path: str, exc: Exception):
+ from core.show_runtime import ShowRuntimeRequestTimeoutError
+
+ if _is_show_page_api_handler_path(asset_path) and isinstance(
+ exc,
+ ShowRuntimeRequestTimeoutError,
+ ):
+ return _show_page_runtime_timeout_response()
+ return _show_page_runtime_unavailable_response()
+
+
def _is_show_page_entry_asset(asset_path: str) -> bool:
relative = (asset_path or "").strip("/")
return relative in {"", "index.html"}
@@ -14279,12 +14301,19 @@ async def _show_page_runtime_response(
body = await starlette_request.body()
request_started = time.monotonic()
manager = get_show_runtime_manager()
+ request_options: dict[str, float] = {}
+ if _is_show_page_api_handler_path(asset_path):
+ from core.services import settings as settings_service
+
+ config = await asyncio.to_thread(settings_service.load_config_or_default)
+ request_options["timeout_seconds"] = config.runtime.show_page_api_timeout_seconds
proxied = await manager.request(
starlette_request.method,
runtime_path,
envelope=envelope,
headers=forwarded_headers,
body=body or None,
+ **request_options,
)
proxy_duration_ms = int((time.monotonic() - request_started) * 1000)
if (
@@ -14926,9 +14955,9 @@ async def serve_private_show_page(session_id, asset_path):
inject_show_config=request.method == "GET" and not _is_show_api_asset(asset_path),
show_authenticated=can_annotate,
)
- except Exception:
+ except Exception as exc:
if _is_show_api_asset(asset_path) or _is_show_annotation_asset(asset_path):
- return _show_page_runtime_unavailable_response()
+ return _show_page_runtime_error_response(asset_path, exc)
response = _show_page_runtime_failure_response(
page_dir,
page.session_id,
@@ -15427,9 +15456,9 @@ async def serve_public_show_page(share_id, asset_path):
show_config_session_id=share_id,
include_annotation_bootstrap=not limited_guest,
)
- except Exception:
+ except Exception as exc:
if _is_show_api_asset(asset_path) or _is_show_annotation_asset(asset_path):
- return _show_page_runtime_unavailable_response()
+ return _show_page_runtime_error_response(asset_path, exc)
response = _show_page_runtime_failure_response(
page_dir,
page.session_id,