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
perf(ui-server): cache and gzip static assets (#757)
Call Whitec628f953df13
diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.pyindex 5406e2f0a..0fe0ff1fe 100644--- a/tests/test_ui_server_fastapi.py+++ b/tests/test_ui_server_fastapi.py@@ -1,7 +1,16 @@+import gzip+import pytestfrom storage.importer import ensure_sqlite_state-from vibe.ui_compat import CompatApp, normalize_response, route_path_to_fastapi, run_maybe_async, request+from vibe.ui_compat import (+ TEST_REMOTE_ADDR_HEADER,+ CompatApp,+ normalize_response,+ route_path_to_fastapi,+ run_maybe_async,+ request,+)from starlette.websockets import WebSocketDisconnectfrom vibe import ui_server@@ -555,6 +564,7 @@ def test_config_restart_fallback_schedules_when_in_flight_finishes_after_marker(def test_static_ui_assets_use_cache_headers(monkeypatch, tmp_path):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))ui_dist = tmp_path / "dist"assets_dir = ui_dist / "assets"assets_dir.mkdir(parents=True)@@ -580,6 +590,131 @@ def test_static_ui_assets_use_cache_headers(monkeypatch, tmp_path):assert spa_response.headers["Cache-Control"] == "no-store, private"+def test_static_ui_asset_omits_csrf_cookie(monkeypatch, tmp_path):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))+ ui_dist = tmp_path / "dist"+ assets_dir = ui_dist / "assets"+ assets_dir.mkdir(parents=True)+ (assets_dir / "index-abc123.js").write_text("console.log('ok')", encoding="utf-8")++ monkeypatch.setattr(ui_server, "get_ui_dist_path", lambda: ui_dist)++ response = app.test_client().get("/assets/index-abc123.js")++ assert response.status_code == 200+ assert response.headers["Cache-Control"] == "public, max-age=31536000, immutable"+ assert not any(header.startswith("vibe_csrf_token=") for header in response.headers.getlist("Set-Cookie"))+++def test_static_ui_documents_keep_csrf_cookie(monkeypatch, tmp_path):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))+ ui_dist = tmp_path / "dist"+ ui_dist.mkdir(parents=True)+ (ui_dist / "index.html").write_text("<html>app</html>", encoding="utf-8")++ monkeypatch.setattr(ui_server, "get_ui_dist_path", lambda: ui_dist)++ index_response = app.test_client().get("/")+ spa_response = app.test_client().get("/workbench/session-1")++ assert index_response.status_code == 200+ assert any(header.startswith("vibe_csrf_token=") for header in index_response.headers.getlist("Set-Cookie"))+ assert spa_response.status_code == 200+ assert any(header.startswith("vibe_csrf_token=") for header in spa_response.headers.getlist("Set-Cookie"))+++def test_static_ui_asset_gzip_uses_shared_response_rules(monkeypatch, tmp_path):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))+ ui_dist = tmp_path / "dist"+ assets_dir = ui_dist / "assets"+ assets_dir.mkdir(parents=True)+ original = b"console.log('edge cache');\n" * 200+ (assets_dir / "index-abc123.js").write_bytes(original)++ monkeypatch.setattr(ui_server, "get_ui_dist_path", lambda: ui_dist)++ client = app.test_client()+ identity_response = client.get("/assets/index-abc123.js", headers={"Accept-Encoding": ""})+ assert identity_response.status_code == 200+ assert identity_response.content == original+ assert "Content-Encoding" not in identity_response.headers+ assert "Accept-Encoding" in identity_response.headers["Vary"]+ assert identity_response.headers["Accept-Ranges"] == "bytes"+ assert identity_response.headers["ETag"]+ assert identity_response.headers["Last-Modified"]++ gzip_disabled_response = client.get("/assets/index-abc123.js", headers={"Accept-Encoding": "br, gzip;q=0"})+ assert gzip_disabled_response.status_code == 200+ assert gzip_disabled_response.content == original+ assert "Content-Encoding" not in gzip_disabled_response.headers+ assert "Accept-Encoding" in gzip_disabled_response.headers["Vary"]++ with client._client.stream(+ "GET",+ "http://127.0.0.1/assets/index-abc123.js",+ headers={+ "Accept-Encoding": "gzip",+ TEST_REMOTE_ADDR_HEADER: "127.0.0.1",+ },+ ) as gzip_response:+ compressed = b"".join(gzip_response.iter_raw())++ assert gzip_response.status_code == 200+ assert gzip_response.headers["Content-Encoding"] == "gzip"+ assert "Accept-Encoding" in gzip_response.headers["Vary"]+ assert gzip.decompress(compressed) == original+++def test_static_ui_asset_range_request_keeps_file_response_semantics(monkeypatch, tmp_path):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))+ ui_dist = tmp_path / "dist"+ assets_dir = ui_dist / "assets"+ assets_dir.mkdir(parents=True)+ original = b"0123456789abcdef"+ (assets_dir / "index-abc123.js").write_bytes(original)++ monkeypatch.setattr(ui_server, "get_ui_dist_path", lambda: ui_dist)++ response = app.test_client().get(+ "/assets/index-abc123.js",+ headers={+ "Accept-Encoding": "gzip",+ "Range": "bytes=0-9",+ },+ )++ assert response.status_code == 206+ assert response.content == b"0123456789"+ assert response.headers["Content-Range"] == f"bytes 0-9/{len(original)}"+ assert response.headers["Accept-Ranges"] == "bytes"+ assert "Content-Encoding" not in response.headers+++def test_static_ui_asset_gzip_skips_small_and_binary_files(monkeypatch, tmp_path):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))+ ui_dist = tmp_path / "dist"+ assets_dir = ui_dist / "assets"+ assets_dir.mkdir(parents=True)+ small_js = b"console.log('small')"+ png = b"\x89PNG\r\n\x1a\n" + (b"\x00" * 2048)+ (assets_dir / "small-abc123.js").write_bytes(small_js)+ (assets_dir / "logo-abc123.png").write_bytes(png)++ monkeypatch.setattr(ui_server, "get_ui_dist_path", lambda: ui_dist)++ client = app.test_client()+ small_response = client.get("/assets/small-abc123.js", headers={"Accept-Encoding": "gzip"})+ binary_response = client.get("/assets/logo-abc123.png", headers={"Accept-Encoding": "gzip"})++ assert small_response.status_code == 200+ assert small_response.content == small_js+ assert "Content-Encoding" not in small_response.headers+ assert binary_response.status_code == 200+ assert binary_response.content == png+ assert "Content-Encoding" not in binary_response.headers+ assert "Vary" not in binary_response.headers++def test_run_maybe_async_offloads_sync_handlers_without_losing_context():import asyncioimport threadingdiff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.pyindex 4ce9dba18..45ec6ed23 100644--- a/tests/test_ui_show_pages.py+++ b/tests/test_ui_show_pages.py@@ -2637,6 +2637,33 @@ def test_show_runtime_vendor_asset_proxy_is_immutable(monkeypatch, tmp_path):)+def test_show_runtime_vendor_asset_proxy_honors_gzip_q0(monkeypatch, tmp_path):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ _save_config(tmp_path)+ body = b"export const React = {};\n" * 200+ manager = _FakeShowRuntimeManager(+ body=body,+ extra_headers={+ "content-type": "text/javascript; charset=utf-8",+ "cache-control": "public, max-age=31536000, immutable",+ },+ )+ set_show_runtime_manager_for_tests(manager)+ try:+ response = app.test_client().get(+ "/_show-runtime/vendor/abc123/react.js",+ base_url="http://127.0.0.1:5123",+ headers={"Accept-Encoding": "br, gzip;q=0"},+ )+ finally:+ set_show_runtime_manager_for_tests(None)++ assert response.status_code == 200+ assert response.content == body+ assert "content-encoding" not in response.headers+ assert "Accept-Encoding" in response.headers["vary"]++def test_show_runtime_vendor_asset_proxy_forwards_query_and_is_public(monkeypatch, tmp_path):# No remote login configured here: the vendor namespace is referenced by the# anonymous public `/p/<share>/` surface via the runtime's import map, so it must bediff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex f0c0bc0c9..5f9b4b53c 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -343,7 +343,7 @@ def _is_show_api_mutation() -> bool:def _ensure_csrf_cookie(response: Response) -> Response:- if _is_current_show_runtime_immutable_asset_request():+ if _is_current_immutable_static_asset_request():return responseif response.headers.getlist("Set-Cookie"):for cookie_header in response.headers.getlist("Set-Cookie"):@@ -1873,7 +1873,7 @@ def renew_remote_access_cookie(response: Response) -> Response:# Logout handler explicitly clears the session cookie; never re-issue it.if getattr(g, "remote_session_logout", False):return response- if _is_current_show_runtime_immutable_asset_request():+ if _is_current_immutable_static_asset_request():return responserenew = getattr(g, "remote_session_renew", None)if not renew:@@ -7379,7 +7379,7 @@ async def show_runtime_vendor_asset(vendor_path: str):_remove_response_header(response_headers, "cache-control")_remove_response_header(response_headers, "set-cookie")response_headers["Cache-Control"] = _SHOW_RUNTIME_IMMUTABLE_CACHE_CONTROL- content = _compress_show_runtime_response(proxied.content, response_headers, request._request)+ content = _compress_response_content(proxied.content, response_headers, request._request)return FastAPIResponse(content=content, status_code=proxied.status_code, headers=response_headers)@@ -7554,7 +7554,7 @@ async def _show_page_runtime_response(# and base path); never let it be cached. App modules and per-session deps keep# the runtime's own cache headers (Vite marks optimized deps immutable)._mark_show_runtime_document_no_store(response_headers)- content = _compress_show_runtime_response(content, response_headers, starlette_request)+ content = _compress_response_content(content, response_headers, starlette_request)return FastAPIResponse(content=content, status_code=proxied.status_code, headers=response_headers)@@ -7577,26 +7577,51 @@ def _mark_show_runtime_document_no_store(headers: dict[str, str]) -> None:headers["Cache-Control"] = "no-store"-def _compress_show_runtime_response(content: bytes, headers: dict[str, str], starlette_request: FastAPIRequest) -> bytes:+def _compress_response_content(content: bytes, headers: dict[str, str], starlette_request: FastAPIRequest) -> bytes:if len(content) < _SHOW_RUNTIME_COMPRESSIBLE_MIN_BYTES:return contentif _response_header(headers, "content-encoding"):return content- if "gzip" not in (starlette_request.headers.get("accept-encoding") or "").lower():- return contentcontent_type = _response_header(headers, "content-type") or ""if not _show_response_is_compressible(content_type):return content+ _set_response_header(headers, "Vary", _append_vary_header(_response_header(headers, "vary"), "Accept-Encoding"))+ if not _accept_encoding_allows_gzip(starlette_request.headers.get("accept-encoding")):+ return contentcompressed = gzip.compress(content, compresslevel=6)if len(compressed) >= len(content):return content_remove_response_header(headers, "content-length")_remove_response_header(headers, "etag")- headers["Content-Encoding"] = "gzip"- headers["Vary"] = _append_vary_header(_response_header(headers, "vary"), "Accept-Encoding")+ _set_response_header(headers, "Content-Encoding", "gzip")return compressed+def _accept_encoding_allows_gzip(accept_encoding: str | None) -> bool:+ if not accept_encoding:+ return False+ for item in accept_encoding.split(","):+ parts = [part.strip() for part in item.split(";") if part.strip()]+ if not parts or parts[0].lower() != "gzip":+ continue+ q = 1.0+ for param in parts[1:]:+ name, separator, value = param.partition("=")+ if separator and name.strip().lower() == "q":+ try:+ q = float(value.strip())+ except ValueError:+ q = 0.0+ break+ return q > 0+ return False+++def _set_response_header(headers: dict[str, str], name: str, value: str) -> None:+ _remove_response_header(headers, name)+ headers[name] = value++def _append_vary_header(existing: str | None, value: str) -> str:values = [item.strip() for item in (existing or "").split(",") if item.strip()]if not any(item.lower() == value.lower() for item in values):@@ -7730,11 +7755,15 @@ def _is_current_show_runtime_immutable_asset_request() -> bool:return _is_show_runtime_immutable_asset_path(parts[2])+def _is_current_immutable_static_asset_request() -> bool:+ return (request.path or "").startswith("/assets/") or _is_current_show_runtime_immutable_asset_request()++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)+ del headers[key]def _response_header(headers: dict[str, str], name: str) -> str | None:@@ -7980,6 +8009,22 @@ async def serve_public_show_page(share_id, asset_path):store.close()+def _ui_static_file_response(resolved_path: Path, *, content_type: str, cache_control: str) -> Response:+ response = send_file(resolved_path, mimetype=content_type)+ response.headers["Cache-Control"] = cache_control+ if hasattr(response, "set_stat_headers"):+ response.set_stat_headers(resolved_path.stat())+ if request.method != "GET" or request.headers.get("range"):+ return response+ headers = response.headers+ content = resolved_path.read_bytes()+ compressed = _compress_response_content(content, headers, request._request)+ if compressed is content:+ return response+ _remove_response_header(headers, "accept-ranges")+ return Response(content=compressed, headers=headers)++@app.route("/", defaults={"path": ""})@app.route("/<path:path>")def serve_static(path):@@ -8001,22 +8046,27 @@ def serve_static(path):if resolved_path.exists() and resolved_path.is_file():mime_type, _ = mimetypes.guess_type(str(resolved_path))- response = send_file(resolved_path, mimetype=mime_type or "application/octet-stream")if path.startswith("assets/"):- response.headers["Cache-Control"] = "public, max-age=31536000, immutable"+ cache_control = "public, max-age=31536000, immutable"elif resolved_path.name == "index.html":- response.headers["Cache-Control"] = "no-store, private"+ cache_control = "no-store, private"else:- response.headers["Cache-Control"] = "public, max-age=3600"- return response+ cache_control = "public, max-age=3600"+ return _ui_static_file_response(+ resolved_path,+ content_type=mime_type or "application/octet-stream",+ cache_control=cache_control,+ )# SPA fallback: serve index.html for routes without file extensionif "." not in path:index_path = ui_dist / "index.html"if index_path.exists():- response = send_file(index_path, mimetype="text/html")- response.headers["Cache-Control"] = "no-store, private"- return response+ return _ui_static_file_response(+ index_path,+ content_type="text/html",+ cache_control="no-store, private",+ )return jsonify({"error": "not_found"}), 404