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(ui): offload compat sync handlers

cyh3c72739f558a
diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.py
index 0d300ac35..9658514fd 100644
--- a/tests/test_ui_server_fastapi.py
+++ b/tests/test_ui_server_fastapi.py
@@ -1,5 +1,6 @@
import pytest
+from vibe.ui_compat import CompatApp, run_maybe_async, request
from starlette.websockets import WebSocketDisconnect
from vibe.ui_server import app
@@ -30,3 +31,33 @@ def test_fastapi_schema_routes_are_not_exposed():
docs_response = client.get("/docs")
assert b"swagger-ui" not in docs_response.content.lower()
assert client.get("/openapi.json").status_code != 200
+
+
+def test_run_maybe_async_offloads_sync_handlers_without_losing_context():
+ import asyncio
+ import threading
+ import time
+
+ loop_thread_id = threading.get_ident()
+
+ def blocking_handler():
+ assert threading.get_ident() != loop_thread_id
+ time.sleep(0.05)
+ return request.path
+
+ async def ticker():
+ await asyncio.sleep(0.01)
+ return "tick"
+
+ async def exercise():
+ return await asyncio.gather(
+ run_maybe_async(blocking_handler),
+ ticker(),
+ )
+
+ compat_app = CompatApp()
+ with compat_app.test_request_context("/threadpool-check"):
+ result, tick = asyncio.run(exercise())
+
+ assert result == "/threadpool-check"
+ assert tick == "tick"
diff --git a/vibe/ui_compat.py b/vibe/ui_compat.py
index 49e6e6c5a..f26d38606 100644
--- a/vibe/ui_compat.py
+++ b/vibe/ui_compat.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import contextlib
+import functools
import inspect
import json
import re
@@ -13,6 +14,7 @@ from urllib.parse import urlsplit
from fastapi import FastAPI, Request as FastAPIRequest
from fastapi.responses import FileResponse, JSONResponse, RedirectResponse, Response as StarletteResponse
from fastapi.testclient import TestClient
+from starlette.concurrency import run_in_threadpool
from starlette.datastructures import Headers, QueryParams, URL
@@ -187,8 +189,19 @@ def normalize_response(value: Any) -> Response:
)
+def _is_async_callable(obj: Any) -> bool:
+ while isinstance(obj, functools.partial):
+ obj = obj.func
+ return inspect.iscoroutinefunction(obj) or (
+ callable(obj) and inspect.iscoroutinefunction(obj.__call__)
+ )
+
+
async def run_maybe_async(func: Callable[..., Any], *args: Any, **kwargs: Any) -> Any:
- result = func(*args, **kwargs)
+ if _is_async_callable(func):
+ result = await func(*args, **kwargs)
+ else:
+ result = await run_in_threadpool(func, *args, **kwargs)
if inspect.isawaitable(result):
return await result
return result