Skip to content

armgit / avibe

Public Imported from GitHub
0

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

feat(show): wire runtime session events (#415)

Call Whitef15e783c25d3
diff --git a/core/show_pages.py b/core/show_pages.py
index bf973275f..c41aa878a 100644
--- a/core/show_pages.py
+++ b/core/show_pages.py
@@ -589,9 +589,9 @@ import App from "./App"
type VibeShowRuntimeConfig = {
sessionId?: string
- basePath: string
- eventsPath: string
- streamPath: string
+ basePath?: string
+ eventsPath?: string
+ streamPath?: string
writeToken?: string
}
@@ -605,14 +605,16 @@ function readCookie(name: string): string | undefined {
return item ? decodeURIComponent(item.slice(prefix.length)) : undefined
}
+const injected: VibeShowRuntimeConfig = globalThis.__AVIBE_SHOW__ ?? {}
+
globalThis.__AVIBE_SHOW__ = {
- sessionId: window.location.pathname.match(/\\/show\\/([^/]+)/)?.[1]
+ sessionId: injected.sessionId ?? (window.location.pathname.match(/\\/show\\/([^/]+)/)?.[1]
? decodeURIComponent(window.location.pathname.match(/\\/show\\/([^/]+)/)![1])
- : undefined,
- basePath: window.location.pathname.match(/^(.*\\/(?:show|p)\\/[^/]+\\/)$/)?.[1] || window.location.pathname.replace(/[^/]*$/, ""),
- eventsPath: "__show/events",
- streamPath: "__show/events?stream=1",
- writeToken: readCookie("vibe_show_event_token")
+ : undefined),
+ basePath: injected.basePath ?? (window.location.pathname.match(/^(.*\\/(?:show|p)\\/[^/]+\\/)$/)?.[1] || window.location.pathname.replace(/[^/]*$/, "")),
+ eventsPath: injected.eventsPath ?? "__show/events",
+ streamPath: injected.streamPath ?? "__show/events?stream=1",
+ writeToken: injected.writeToken ?? readCookie("vibe_show_event_token")
}
createRoot(document.getElementById("root")!).render(
diff --git a/core/show_session_events.py b/core/show_session_events.py
index 3ef3191f1..a9a23e048 100644
--- a/core/show_session_events.py
+++ b/core/show_session_events.py
@@ -69,6 +69,7 @@ class ShowSessionEventStore:
self.engine.dispose()
def append(self, session_id: str, payload: dict[str, Any]) -> dict[str, Any]:
+ validate_show_event_payload_session(session_id, payload)
event_type = _validate_event_type(payload.get("type"))
actor = _actor_for_event(event_type)
event_payload = _normalize_event_payload(event_type, payload)
@@ -166,6 +167,41 @@ class ShowSessionEventStore:
}
+def show_event_payload_session_mismatch(session_id: str, payload: dict[str, Any]) -> str | None:
+ for candidate in _show_event_session_id_containers(payload):
+ mismatch = _show_event_container_session_mismatch(session_id, candidate)
+ if mismatch:
+ return mismatch
+ return None
+
+
+def _show_event_session_id_containers(payload: dict[str, Any]) -> list[dict[str, Any]]:
+ candidates = [payload]
+ for key in ("payload", "annotation", "mark"):
+ wrapped = payload.get(key)
+ if isinstance(wrapped, dict):
+ candidates.append(wrapped)
+ return candidates
+
+
+def _show_event_container_session_mismatch(session_id: str, payload: dict[str, Any]) -> str | None:
+ for key in ("sessionId", "session_id"):
+ if key not in payload or payload.get(key) is None:
+ continue
+ value = str(payload.get(key) or "").strip()
+ if value and value != session_id:
+ return value
+ return None
+
+
+def validate_show_event_payload_session(session_id: str, payload: dict[str, Any]) -> None:
+ if show_event_payload_session_mismatch(session_id, payload):
+ raise ShowSessionEventError(
+ "Show event sessionId must match the target session.",
+ code="session_mismatch",
+ )
+
+
def _validate_event_type(raw: Any) -> str:
event_type = str(raw or "").strip()
if event_type not in SUPPORTED_EVENT_TYPES:
diff --git a/docs/plans/show-session-event-pipeline.md b/docs/plans/show-session-event-pipeline.md
new file mode 100644
index 000000000..45c955a30
--- /dev/null
+++ b/docs/plans/show-session-event-pipeline.md
@@ -0,0 +1,66 @@
+# Show Session Event Pipeline Plan
+
+## Summary
+
+Show Runtime can now render interactive pages and the SDK can emit typed
+session events. Vibe Remote already owns the durable event store, transcript
+projection, private/public Show Page routing, and optional dispatch to the
+active agent session.
+
+This slice closes the browser usability gap: a private Show Page should be able
+to use `@avibe/show-sdk` without manually hardcoding the session id, event
+endpoint, stream endpoint, or write token.
+
+## Current State
+
+- `show_session_events` persists typed events and links transcript messages.
+- Private `/show/<session-id>/__show/events` accepts authenticated event POSTs.
+- Private and public Show Pages can list and stream events.
+- `dispatch: true` human intent and annotation events stream an agent turn back
+ through `show.dispatch` events.
+- The static Vibe Remote template reads the write token cookie, but managed
+ runtime pages currently depend on their own generated config and can miss the
+ token.
+
+## Design
+
+Vibe Remote remains the source of truth for session event semantics.
+
+For private Show Page HTML responses, Vibe Remote injects a small
+`globalThis.__AVIBE_SHOW__` bootstrap before the first module script:
+
+```ts
+globalThis.__AVIBE_SHOW__ = {
+ sessionId,
+ basePath,
+ eventsPath: "__show/events",
+ streamPath: "__show/events?stream=1",
+ writeToken
+}
+```
+
+The injection is intentionally limited:
+
+- only private `/show/<session-id>/...` pages receive a write token
+- public `/p/<share-id>/...` pages stay read-only
+- API responses and non-HTML assets are not modified
+- the runtime sidecar still never receives UI cookies or auth headers
+
+The event POST endpoint also treats the URL session id as authoritative. If a
+browser payload includes `sessionId` for a different session, Vibe Remote
+rejects it instead of silently recording a cross-session event.
+
+## Non-Goals
+
+- No screenshot image upload storage in this slice.
+- No new annotation toolbar or overlay UI in Vibe Remote.
+- No public event submission.
+- No extra agent dispatch policy beyond explicit `dispatch: true`.
+
+## Validation
+
+- API tests for private runtime config injection.
+- API tests that runtime-side injected config preserves existing user config.
+- API tests that public Show Pages do not receive write config.
+- API tests for cross-session `sessionId` rejection.
+- Existing event persistence, transcript, SSE, and dispatch tests.
diff --git a/tests/test_show_pages.py b/tests/test_show_pages.py
index c7090331b..92b0c79bf 100644
--- a/tests/test_show_pages.py
+++ b/tests/test_show_pages.py
@@ -229,8 +229,14 @@ def test_show_page_dir_creates_default_index(monkeypatch, tmp_path):
main_tsx = (page_dir / "src" / "main.tsx").read_text(encoding="utf-8")
assert "globalThis.__AVIBE_SHOW__" in main_tsx
assert "declare global" in main_tsx
- assert 'eventsPath: "__show/events"' in main_tsx
- assert 'writeToken: readCookie("vibe_show_event_token")' in main_tsx
+ assert "const injected: VibeShowRuntimeConfig = globalThis.__AVIBE_SHOW__ ?? {}" in main_tsx
+ assert "globalThis.__AVIBE_SHOW__ = {" in main_tsx
+ assert main_tsx.index("const injected: VibeShowRuntimeConfig") < main_tsx.index("globalThis.__AVIBE_SHOW__ = {")
+ assert "sessionId: injected.sessionId ??" in main_tsx
+ assert "basePath: injected.basePath ??" in main_tsx
+ assert 'eventsPath: injected.eventsPath ?? "__show/events"' in main_tsx
+ assert 'streamPath: injected.streamPath ?? "__show/events?stream=1"' in main_tsx
+ assert 'writeToken: injected.writeToken ?? readCookie("vibe_show_event_token")' in main_tsx
assert "Ready to visualize" in (page_dir / "src" / "App.tsx").read_text(encoding="utf-8")
assert (page_dir / "api" / "health.ts").exists()
@@ -779,6 +785,72 @@ def test_show_event_cli_dispatch_fallback_records_and_dispatches(monkeypatch, tm
assert conn.execute(select(show_session_events.c.id)).scalar_one() == payload["event"]["id"]
+def test_show_event_cli_fallback_rejects_mismatched_session_id(monkeypatch, tmp_path, capsys):
+ from sqlalchemy import select
+
+ from storage import messages_service
+ from storage.db import create_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+ from storage.models import agent_sessions, show_session_events
+ from storage.settings_service import upsert_scope
+
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+ _save_config()
+ ensure_sqlite_state()
+
+ engine = create_sqlite_engine()
+ now = messages_service._utc_now_iso()
+ with engine.begin() as conn:
+ scope_id = upsert_scope(conn, platform="avibe", scope_type="project", native_id="proj_show", now=now)
+ conn.execute(
+ agent_sessions.insert().values(
+ id="ses123",
+ scope_id=scope_id,
+ agent_backend="codex",
+ agent_variant="default",
+ session_anchor="anchor_ses123",
+ native_session_id="",
+ status="active",
+ metadata_json="{}",
+ created_at=now,
+ updated_at=now,
+ last_active_at=now,
+ )
+ )
+
+ monkeypatch.setattr(cli.runtime, "read_status", lambda: {"ui_pid": 123})
+
+ def _urlopen(request, timeout):
+ raise cli.urllib.error.HTTPError(request.full_url, 400, "Bad Request", {}, None)
+
+ monkeypatch.setattr(cli.urllib.request, "urlopen", _urlopen)
+
+ args = cli.build_parser().parse_args(
+ [
+ "show",
+ "event",
+ "--session-id",
+ "ses123",
+ "--event-json",
+ json.dumps(
+ {
+ "sessionId": "ses_other",
+ "type": "human.annotation.created",
+ "annotation": {"comment": "Wrong session."},
+ }
+ ),
+ "--json",
+ ]
+ )
+ assert cli.cmd_show(args) == 1
+
+ error_payload = json.loads(capsys.readouterr().err)
+ assert error_payload["code"] == "session_mismatch"
+ with engine.connect() as conn:
+ assert conn.execute(select(show_session_events.c.id)).first() is None
+
+
def test_show_mark_cli_posts_to_configured_ui_host_when_running(monkeypatch, tmp_path):
monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
paths.ensure_data_dirs()
diff --git a/tests/test_show_session_events.py b/tests/test_show_session_events.py
index cb19f7706..c22b6d36e 100644
--- a/tests/test_show_session_events.py
+++ b/tests/test_show_session_events.py
@@ -143,6 +143,62 @@ def test_show_event_store_records_human_annotation_with_anchor_context(isolated_
assert message_row["author"] == "user"
+def test_show_event_store_rejects_mismatched_session_id(isolated_state):
+ _seed_session()
+
+ store = ShowSessionEventStore()
+ try:
+ with pytest.raises(ShowSessionEventError) as exc_info:
+ store.append(
+ "ses_mark",
+ {
+ "sessionId": "ses_other",
+ "type": "human.annotation.created",
+ "annotation": {"comment": "Wrong session."},
+ },
+ )
+ finally:
+ store.close()
+
+ assert exc_info.value.code == "session_mismatch"
+ engine = create_sqlite_engine()
+ with engine.connect() as conn:
+ assert conn.execute(select(show_session_events.c.id)).first() is None
+
+
+ "event_payload",
+ [
+ {
+ "type": "human.annotation.created",
+ "payload": {"sessionId": "ses_other", "comment": "Wrong session."},
+ },
+ {
+ "type": "human.annotation.created",
+ "annotation": {"session_id": "ses_other", "comment": "Wrong session."},
+ },
+ {
+ "type": "assistant.mark.created",
+ "mark": {"sessionId": "ses_other", "target": "summary", "body": "Wrong session."},
+ },
+ ],
+)
+def test_show_event_store_rejects_nested_mismatched_session_id(isolated_state, event_payload):
+ _seed_session()
+
+ store = ShowSessionEventStore()
+ try:
+ with pytest.raises(ShowSessionEventError) as exc_info:
+ store.append("ses_mark", event_payload)
+ finally:
+ store.close()
+
+ assert exc_info.value.code == "session_mismatch"
+ engine = create_sqlite_engine()
+ with engine.connect() as conn:
+ assert conn.execute(select(show_session_events.c.id)).first() is None
+
+
def test_show_event_store_records_element_group_annotation_context(isolated_state):
_seed_session()
diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.py
index af7667874..638a53382 100644
--- a/tests/test_ui_show_pages.py
+++ b/tests/test_ui_show_pages.py
@@ -205,6 +205,139 @@ def test_private_show_page_uses_runtime_when_available(monkeypatch, tmp_path):
assert "x-vibe-csrf-token" not in manager.calls[0][2]
+def test_private_show_page_injects_runtime_event_config(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_show_page("ses123", "private")
+ monkeypatch.setattr("vibe.ui_server.show_event_write_token", lambda session_id: f"token-{session_id}")
+ manager = _FakeShowRuntimeManager(
+ body=b'<!doctype html><html><head></head><body><div id="root"></div><script type="module" src="/src/main.tsx"></script></body></html>',
+ extra_headers={
+ "cache-control": "public, max-age=3600",
+ "etag": '"runtime-etag"',
+ "expires": "Wed, 03 Jun 2026 09:00:00 GMT",
+ "last-modified": "Wed, 03 Jun 2026 08:00:00 GMT",
+ },
+ )
+ set_show_runtime_manager_for_tests(manager)
+ try:
+ response = app.test_client().get("/show/ses123/", base_url="http://127.0.0.1:5123")
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert response.status_code == 200
+ body = response.content.decode("utf-8")
+ assert "globalThis.__AVIBE_SHOW__=Object.assign" in body
+ assert '"sessionId":"ses123"' in body
+ assert '"basePath":"/show/ses123/"' in body
+ assert '"eventsPath":"/show/ses123/__show/events"' in body
+ assert '"streamPath":"/show/ses123/__show/events?stream=1"' in body
+ assert '"writeToken":"token-ses123"' in body
+ assert body.index("globalThis.__AVIBE_SHOW__") < body.index('type="module"')
+ assert "cookie" not in manager.calls[0][2]
+ assert response.headers["cache-control"] == "no-store"
+ assert "etag" not in response.headers
+ assert "expires" not in response.headers
+ assert "last-modified" not in response.headers
+
+
+def test_private_show_page_does_not_inject_runtime_event_config_into_attachment_html(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_show_page("ses123", "private")
+ monkeypatch.setattr("vibe.ui_server.show_event_write_token", lambda session_id: f"token-{session_id}")
+ body = b'<!doctype html><script type="module" src="/src/main.tsx"></script>'
+ manager = _FakeShowRuntimeManager(
+ body=body,
+ extra_headers={
+ "content-type": "text/html; charset=utf-8",
+ "content-disposition": 'attachment; filename="report.html"',
+ },
+ )
+ set_show_runtime_manager_for_tests(manager)
+ try:
+ response = app.test_client().get("/show/ses123/report.html", base_url="http://127.0.0.1:5123")
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert response.status_code == 200
+ assert response.content == body
+ assert "globalThis.__AVIBE_SHOW__" not in response.content.decode("utf-8")
+ assert response.headers["content-disposition"] == 'attachment; filename="report.html"'
+
+
+def test_private_show_page_does_not_inject_runtime_event_config_into_ranged_html(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_show_page("ses123", "private")
+ monkeypatch.setattr("vibe.ui_server.show_event_write_token", lambda session_id: f"token-{session_id}")
+ body = b'<!doctype html><script type="module" src="/src/main.tsx"></script>'
+ manager = _FakeShowRuntimeManager(
+ body=body,
+ status_code=206,
+ extra_headers={
+ "content-type": "text/html; charset=utf-8",
+ "content-range": "bytes 0-63/128",
+ "accept-ranges": "bytes",
+ },
+ )
+ set_show_runtime_manager_for_tests(manager)
+ try:
+ response = app.test_client().get(
+ "/show/ses123/",
+ base_url="http://127.0.0.1:5123",
+ headers={"Range": "bytes=0-63"},
+ )
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert response.status_code == 206
+ assert response.content == body
+ assert "globalThis.__AVIBE_SHOW__" not in response.content.decode("utf-8")
+ assert response.headers["content-range"] == "bytes 0-63/128"
+ assert manager.calls[0][2]["range"] == "bytes=0-63"
+
+
+def test_private_show_page_runtime_config_overrides_existing_client_defaults(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_show_page("ses123", "private")
+ monkeypatch.setattr("vibe.ui_server.show_event_write_token", lambda session_id: f"token-{session_id}")
+ manager = _FakeShowRuntimeManager(
+ body=b'<!doctype html><script>globalThis.__AVIBE_SHOW__={eventsPath:"runtime-only"}</script><script type="module" src="/src/main.tsx"></script>'
+ )
+ set_show_runtime_manager_for_tests(manager)
+ try:
+ response = app.test_client().get("/show/ses123/app/dashboard", base_url="http://127.0.0.1:5123")
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert response.status_code == 200
+ body = response.content.decode("utf-8")
+ assert '"eventsPath":"/show/ses123/__show/events"' in body
+ assert '"writeToken":"token-ses123"' in body
+
+
+def test_public_show_page_does_not_inject_write_runtime_config(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ share_id = _create_show_page("ses123", "public")
+ monkeypatch.setattr("vibe.ui_server.show_event_write_token", lambda session_id: f"token-{session_id}")
+ manager = _FakeShowRuntimeManager(
+ body=b'<!doctype html><html><body><script type="module" src="/src/main.tsx"></script></body></html>'
+ )
+ set_show_runtime_manager_for_tests(manager)
+ try:
+ response = app.test_client().get(f"/p/{share_id}/", base_url="http://127.0.0.1:5123")
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert response.status_code == 200
+ body = response.content.decode("utf-8")
+ assert "globalThis.__AVIBE_SHOW__=Object.assign" not in body
+ assert "token-ses123" not in body
+
+
def test_private_show_page_falls_back_to_static_when_runtime_unavailable(monkeypatch, tmp_path):
monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
_save_config(tmp_path)
@@ -309,6 +442,33 @@ def test_private_show_page_records_show_event(monkeypatch, tmp_path):
assert events_response.get_json()["events"][0]["id"] == payload["event"]["id"]
+def test_private_show_page_rejects_mismatched_event_session_id(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_agent_session("ses123")
+ _create_show_page("ses123", "private")
+ token = "session-write-token"
+ monkeypatch.setattr("vibe.ui_server.show_event_write_token", lambda session_id: token)
+
+ response = app.test_client().post(
+ "/show/ses123/__show/events",
+ base_url="http://127.0.0.1:5123",
+ headers={
+ "Origin": "http://127.0.0.1:5123",
+ "Content-Type": "application/json",
+ "X-Vibe-Show-Token": token,
+ },
+ json={
+ "sessionId": "ses_other",
+ "type": "human.annotation.created",
+ "annotation": {"comment": "Wrong session."},
+ },
+ )
+
+ assert response.status_code == 400
+ assert response.get_json()["code"] == "session_mismatch"
+
+
def test_private_show_page_dispatches_human_show_event(monkeypatch, tmp_path):
monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
_save_config(tmp_path)
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 3c66acf68..f450067cd 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -36,6 +36,7 @@ from core.show_pages import (
show_cli_event_token,
show_event_write_token,
)
+from core.show_session_events import show_event_payload_session_mismatch
from modules.agents.catalog import AGENT_BACKENDS, supports_runtime_refresh
from vibe.runtime import get_ui_dist_path, get_working_dir
from vibe.sentry_integration import init_sentry
@@ -74,6 +75,10 @@ _SHOW_RUNTIME_RESPONSE_HEADER_ALLOWLIST = {
"vary",
"x-sourcemap",
}
+_SHOW_RUNTIME_MODULE_SCRIPT_RE = re.compile(
+ r"<script\b(?=[^>]*\btype\s*=\s*['\"]module['\"])[^>]*>",
+ re.IGNORECASE,
+)
STRUCTURED_LOG_PATTERN = re.compile(r"^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3})\s+-\s+([\w.]+)\s+-\s+(\w+)\s+-\s+(.*)$")
LEVEL_HINT_PATTERN = re.compile(r"\b(DEBUG|INFO|WARNING|ERROR|CRITICAL)\b")
@@ -4402,6 +4407,17 @@ def _show_event_write_authorized(session_id: str) -> bool:
def _show_event_response_from_payload(session_id: str, payload: dict[str, Any]):
+ if show_event_payload_session_mismatch(session_id, payload):
+ return (
+ jsonify(
+ {
+ "ok": False,
+ "code": "session_mismatch",
+ "error": "Show event sessionId must match the URL session.",
+ }
+ ),
+ 400,
+ )
store = _show_session_event_store()
try:
event_payload = store.append(session_id, payload)
@@ -4673,6 +4689,7 @@ async def _show_page_runtime_response(
starlette_request: FastAPIRequest,
*,
external_prefix: str | None = None,
+ inject_private_config: bool = False,
):
from core.show_runtime import get_show_runtime_manager
@@ -4710,7 +4727,96 @@ async def _show_page_runtime_response(
)
response_headers["X-Content-Type-Options"] = "nosniff"
response_headers["Referrer-Policy"] = "no-referrer"
- return FastAPIResponse(content=proxied.content, status_code=proxied.status_code, headers=response_headers)
+ content = proxied.content
+ if _should_inject_show_runtime_config(proxied.status_code, response_headers, inject_private_config=inject_private_config):
+ content = _inject_show_runtime_config(content, session_id)
+ _strip_mutated_show_runtime_headers(response_headers)
+ return FastAPIResponse(content=content, status_code=proxied.status_code, headers=response_headers)
+
+
+def _should_inject_show_runtime_config(
+ status_code: int,
+ headers: dict[str, str],
+ *,
+ inject_private_config: bool,
+) -> bool:
+ if not inject_private_config or status_code != 200:
+ return False
+ if _show_response_is_attachment(_response_header(headers, "content-disposition")):
+ return False
+ return _show_response_is_html(_response_header(headers, "content-type"))
+
+
+def _strip_mutated_show_runtime_headers(headers: dict[str, str]) -> None:
+ for name in ("cache-control", "etag", "expires", "last-modified", "content-length"):
+ _remove_response_header(headers, name)
+ headers["Cache-Control"] = "no-store"
+
+
+def _remove_response_header(headers: dict[str, str], name: str) -> None:
+ normalized = name.lower()
+ for key in list(headers):
+ if key.lower() == normalized:
+ headers.pop(key, None)
+
+
+def _response_header(headers: dict[str, str], name: str) -> str | None:
+ normalized = name.lower()
+ for key, value in headers.items():
+ if key.lower() == normalized:
+ return value
+ return None
+
+
+def _show_response_is_html(content_type: str | None) -> bool:
+ return bool(content_type and "text/html" in content_type.lower())
+
+
+def _show_response_is_attachment(content_disposition: str | None) -> bool:
+ return bool(content_disposition and content_disposition.lstrip().lower().startswith("attachment"))
+
+
+def _show_runtime_config_payload(session_id: str) -> dict[str, str]:
+ session_path = quote(session_id, safe="")
+ events_path = f"/show/{session_path}/__show/events"
+ return {
+ "sessionId": session_id,
+ "basePath": f"/show/{session_path}/",
+ "eventsPath": events_path,
+ "streamPath": f"{events_path}?stream=1",
+ "writeToken": show_event_write_token(session_id),
+ }
+
+
+def _show_runtime_config_script(session_id: str) -> str:
+ payload = json.dumps(_show_runtime_config_payload(session_id), ensure_ascii=False, separators=(",", ":"))
+ payload = payload.replace("<", "\\u003c").replace(">", "\\u003e").replace("&", "\\u0026")
+ return (
+ "<script>"
+ "(function(){"
+ f"var next={payload};"
+ "globalThis.__AVIBE_SHOW__=Object.assign({},globalThis.__AVIBE_SHOW__||{},next);"
+ "}());"
+ "</script>"
+ )
+
+
+def _inject_show_runtime_config(content: bytes, session_id: str) -> bytes:
+ try:
+ html = content.decode("utf-8")
+ except UnicodeDecodeError:
+ return content
+ script = _show_runtime_config_script(session_id)
+ module_match = _SHOW_RUNTIME_MODULE_SCRIPT_RE.search(html)
+ if module_match:
+ html = f"{html[: module_match.start()]}{script}\n {html[module_match.start() :]}"
+ elif "</head>" in html:
+ html = html.replace("</head>", f"{script}\n </head>", 1)
+ elif "</body>" in html:
+ html = html.replace("</body>", f"{script}\n </body>", 1)
+ else:
+ html = f"{script}\n{html}"
+ return html.encode("utf-8")
def _rewrite_show_runtime_location(session_id: str, location: str, *, external_prefix: str | None = None) -> str:
@@ -4796,7 +4902,12 @@ async def serve_private_show_page(session_id, asset_path):
if request.method in {"GET", "HEAD"} or _is_show_api_asset(asset_path):
try:
starlette_request = request._request
- response = await _show_page_runtime_response(page.session_id, asset_path, starlette_request)
+ response = await _show_page_runtime_response(
+ page.session_id,
+ asset_path,
+ starlette_request,
+ inject_private_config=request.method == "GET" and not _is_show_api_asset(asset_path),
+ )
except Exception:
if _is_show_api_asset(asset_path):
return _show_page_runtime_unavailable_response()