Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

perf(desktop): reduce HTTP job stalls and office render load

rubenluetke10-beep52c0cabe11d2
diff --git a/conductor/cli.py b/conductor/cli.py
index 62d2757b86..03cc82ef63 100644
--- a/conductor/cli.py
+++ b/conductor/cli.py
@@ -93,7 +93,7 @@ async def cmd_show(args: argparse.Namespace) -> int:
async def cmd_add(args: argparse.Namespace) -> int:
path = Path(args.yaml_file)
- if not path.exists():
+ if not await asyncio.to_thread(path.exists):
print(f"File not found: {path}", file=sys.stderr)
return 1
@@ -134,31 +134,34 @@ async def cmd_run(args: argparse.Namespace) -> int:
except json.JSONDecodeError as exc:
print(f"--input-json parse error: {exc}", file=sys.stderr)
return 1
- run_id = await runner.trigger(args.id, trigger="manual",
- input_data=input_data)
- print(f"Run started: {run_id}", file=sys.stderr)
+ try:
+ run_id = await runner.trigger(args.id, trigger="manual",
+ input_data=input_data)
+ print(f"Run started: {run_id}", file=sys.stderr)
+
+ # Poll until terminal state.
+ for _ in range(args.timeout * 2):
+ await asyncio.sleep(0.5)
+ run = await store.get_run(run_id)
+ if run and run["state"] in ("completed", "failed", "cancelled"):
+ break
+ else:
+ print("Timeout waiting for terminal state", file=sys.stderr)
+ return 2
- # Poll until terminal state
- for _ in range(args.timeout * 2):
- await asyncio.sleep(0.5)
run = await store.get_run(run_id)
- if run and run["state"] in ("completed", "failed", "cancelled"):
- break
- else:
- print("Timeout waiting for terminal state", file=sys.stderr)
- return 2
-
- run = await store.get_run(run_id)
- if run is None:
- return 2
- if run["state"] == "completed":
- print(run["output"])
- return 0
- print(f"Run failed: {run.get('error') or 'unknown'}",
- file=sys.stderr)
- if run["output"]:
- print(run["output"])
- return 1
+ if run is None:
+ return 2
+ if run["state"] == "completed":
+ print(run["output"])
+ return 0
+ print(f"Run failed: {run.get('error') or 'unknown'}",
+ file=sys.stderr)
+ if run["output"]:
+ print(run["output"])
+ return 1
+ finally:
+ await runner.aclose()
return await _with_store(_run)
diff --git a/conductor/core/runner.py b/conductor/core/runner.py
index f0140c48f3..662a318cee 100644
--- a/conductor/core/runner.py
+++ b/conductor/core/runner.py
@@ -18,9 +18,11 @@ import asyncio
import json
import logging
import time
-from typing import TYPE_CHECKING, Any, Callable
+from collections.abc import Callable
+from typing import TYPE_CHECKING, Any
from ..jobs import HANDLERS
+from ..jobs.http import HttpHandler
from .notify import NEWS_EVENT, classify_run, failures_to_announce
from .schema import JobSpec
@@ -44,6 +46,8 @@ class Runner:
) -> None:
self._store = store
self._on_event = on_event
+ self._http_handler = HttpHandler()
+ self._tasks: set[asyncio.Task[None]] = set()
# Job ids whose current breakage THIS runner announced as "failing".
# A recovery is only news when the breakage was (see ``notify.py``);
# in-memory on purpose — a "working again" about an outage nobody in
@@ -53,6 +57,15 @@ class Runner:
def set_callback(self, on_event: EventCallback) -> None:
self._on_event = on_event
+ async def aclose(self) -> None:
+ """Stop owned runs before closing the HTTP pool and the host's store."""
+ tasks = list(self._tasks)
+ for task in tasks:
+ task.cancel()
+ if tasks:
+ await asyncio.gather(*tasks, return_exceptions=True)
+ await self._http_handler.aclose()
+
# ------------------------------------------------------------------
async def trigger(
@@ -69,10 +82,12 @@ class Runner:
run_id = await self._store.create_run(
job_id, trigger=trigger, input_data=input_data,
)
- asyncio.create_task(
+ task = asyncio.create_task(
self._run(job_row, run_id, trigger, input_data or {}),
name=f"conductor-run-{run_id[:8]}",
)
+ self._tasks.add(task)
+ task.add_done_callback(self._tasks.discard)
return run_id
# ------------------------------------------------------------------
@@ -115,7 +130,7 @@ class Runner:
)
return
- handler = HANDLERS.get(spec.type)
+ handler = self._http_handler if spec.type == "http" else HANDLERS.get(spec.type)
if handler is None:
await self._store.update_run(
run_id, state="failed",
diff --git a/conductor/core/scheduler.py b/conductor/core/scheduler.py
index 6077d3db83..f221f7602b 100644
--- a/conductor/core/scheduler.py
+++ b/conductor/core/scheduler.py
@@ -54,6 +54,7 @@ class Scheduler:
with contextlib.suppress(Exception):
await asyncio.wait_for(self._task, timeout=2.0)
self._task = None
+ await self._runner.aclose()
# ------------------------------------------------------------------
diff --git a/conductor/jobs/http.py b/conductor/jobs/http.py
index 9b34fc9557..3170f2ae66 100644
--- a/conductor/jobs/http.py
+++ b/conductor/jobs/http.py
@@ -1,7 +1,9 @@
-"""HttpHandler — HTTP-Request via httpx, response-body als Run-Output."""
+"""HTTP jobs with a reusable connection pool and off-loop TLS setup."""
from __future__ import annotations
+import asyncio
import time
+from http.cookiejar import CookieJar, DefaultCookiePolicy
from typing import Any
from .base import HandlerResult
@@ -10,7 +12,7 @@ _BODY_CAP = 64 * 1024
def _match_status(status: int, pattern: str) -> bool:
- """``'2xx'`` / ``'200'`` / ``'3xx'`` / exakter Code."""
+ """Match a status family such as ``2xx`` or an exact status code."""
p = pattern.strip().lower()
if p.endswith("xx") and len(p) == 3 and p[0].isdigit():
return (status // 100) == int(p[0])
@@ -20,7 +22,52 @@ def _match_status(status: int, pattern: str) -> bool:
return False
+class _NoStoredCookies(DefaultCookiePolicy):
+ def set_ok(self, cookie: Any, request: Any) -> bool:
+ # Separate jobs may use different credentials against the same host.
+ # Pool sockets, but never carry response cookies into another job.
+ return False
+
+
class HttpHandler:
+ def __init__(self) -> None:
+ self._client: Any | None = None
+ self._lock = asyncio.Lock()
+
+ @staticmethod
+ def _build_client() -> Any:
+ import httpx
+
+ return httpx.AsyncClient(
+ cookies=CookieJar(policy=_NoStoredCookies()),
+ limits=httpx.Limits(
+ max_connections=20, max_keepalive_connections=10,
+ keepalive_expiry=30.0,
+ ),
+ )
+
+ async def _get_client(self) -> Any:
+ async with self._lock:
+ if self._client is None:
+ # Loading trust roots can stall for seconds under memory
+ # pressure. Even the first job must leave the UI loop free.
+ build = asyncio.create_task(asyncio.to_thread(self._build_client))
+ try:
+ self._client = await asyncio.shield(build)
+ except asyncio.CancelledError:
+ # A thread cannot be cancelled. Close what it built before
+ # propagating cancellation, rather than leaking its pool.
+ client = await build
+ await client.aclose()
+ raise
+ return self._client
+
+ async def aclose(self) -> None:
+ async with self._lock:
+ client, self._client = self._client, None
+ if client is not None:
+ await client.aclose()
+
async def execute(
self,
spec: Any,
@@ -30,13 +77,14 @@ class HttpHandler:
start = time.perf_counter()
try:
- async with httpx.AsyncClient(timeout=spec.timeout_s) as client:
- r = await client.request(
- method=spec.method,
- url=spec.url,
- headers=spec.headers or None,
- content=spec.body,
- )
+ client = await self._get_client()
+ r = await client.request(
+ method=spec.method,
+ url=spec.url,
+ headers=spec.headers or None,
+ content=spec.body,
+ timeout=spec.timeout_s,
+ )
except httpx.TimeoutException:
duration_ms = int((time.perf_counter() - start) * 1000)
return HandlerResult(
diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeFrameDriver.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeFrameDriver.tsx
new file mode 100644
index 0000000000..9f9f2520bc
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeFrameDriver.tsx
@@ -0,0 +1,13 @@
+import { useEffect } from "react";
+import { useThree } from "@react-three/fiber";
+import { startOfficeFrameBudget } from "./officeFrameBudget";
+
+/** The narrow IDE companion animates at 30 fps; the full view stays unrestricted. */
+export function OfficeFrameDriver({ enabled }: { enabled: boolean }) {
+ const invalidate = useThree((state) => state.invalidate);
+ useEffect(() => {
+ if (!enabled) return;
+ return startOfficeFrameBudget(invalidate, 30);
+ }, [enabled, invalidate]);
+ return null;
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.tsx
index 05fc7b6c17..c1bfe90b26 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.tsx
@@ -45,6 +45,7 @@ import "./officeFloors.css";
import { OfficeMinimap } from "./OfficeMinimap";
import { OfficeCompass } from "./OfficeCompass";
import { OfficeFullMap } from "./OfficeFullMap";
+import { OfficeFrameDriver } from "./OfficeFrameDriver";
// Only loaded when a host without its own create dialog (the IDE's side panel) spawns an agent.
const CreateAgentDialog = lazy(() => import("../create/CreateAgentDialog").then((m) => ({ default: m.CreateAgentDialog })));
@@ -361,8 +362,9 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpen
<Suspense fallback={<div className="office-fallback" role="status">{t("society.office.loading")}</div>}>
<Canvas shadows="percentage" camera={{ fov: CAMERA_FOV, near: 0.2, far: 800, position: [30, 30, 30] }} dpr={dpr}
gl={{ antialias: true, alpha: true, preserveDrawingBuffer: import.meta.env.DEV }}
- frameloop={!awake ? "never" : "always"}
+ frameloop={!awake ? "never" : compact ? "demand" : "always"}
onPointerMissed={() => select(null)}>
+ <OfficeFrameDriver enabled={awake && compact} />
<OfficeScene floor={floor} occupants={occupants} ready={ready} layout={layout} grid={grid} walkers={walkers} agents={agents} newcomers={newcomers}
awake={awake} reduced={reduced} overview={overview} player={{ look: playerLook(profile), name: playerName }}
selection={selection} nearby={nearby} chats={chats} onOpenScreen={openScreen}
diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeFrameBudget.test.ts b/jarvis/ui/web/frontend/src/components/society/office/officeFrameBudget.test.ts
new file mode 100644
index 0000000000..96fde13b8a
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/office/officeFrameBudget.test.ts
@@ -0,0 +1,46 @@
+import { describe, expect, it } from "vitest";
+import { startOfficeFrameBudget } from "./officeFrameBudget";
+
+function clock() {
+ let pending: FrameRequestCallback | undefined;
+ let count = 0;
+ let nextId = 0;
+ const stop = startOfficeFrameBudget(
+ () => { count += 1; }, 30,
+ (callback) => { pending = callback; return ++nextId; },
+ () => { pending = undefined; },
+ );
+ return {
+ step(now: number) { const callback = pending; pending = undefined; callback?.(now); },
+ get count() { return count; },
+ get pending() { return pending; },
+ stop,
+ };
+}
+
+describe("office side-panel frame budget", () => {
+ it.each([60, 120, 144])("renders 30 frames on a %i Hz display", (hz) => {
+ const timer = clock();
+ for (let frame = 0; frame < hz * 60; frame += 1) timer.step(frame * 1000 / hz);
+ expect(timer.count).toBe(30 * 60);
+ timer.stop();
+ });
+
+ it("does not burst to catch up after the main thread stalls", () => {
+ const timer = clock();
+ timer.step(0);
+ timer.step(10000);
+ timer.step(10001);
+ expect(timer.count).toBe(2);
+ timer.stop();
+ });
+
+ it("stops scheduling when hidden or unmounted, including an in-flight callback", () => {
+ const timer = clock();
+ const inFlight = timer.pending;
+ timer.stop();
+ inFlight?.(100);
+ expect(timer.count).toBe(0);
+ expect(timer.pending).toBeUndefined();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeFrameBudget.ts b/jarvis/ui/web/frontend/src/components/society/office/officeFrameBudget.ts
new file mode 100644
index 0000000000..7a7d102175
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/office/officeFrameBudget.ts
@@ -0,0 +1,29 @@
+/** Keep a secondary 3D view from spending a full render on every display tick. */
+export function startOfficeFrameBudget(
+ invalidate: () => void,
+ fps: number,
+ request: (callback: FrameRequestCallback) => number = requestAnimationFrame,
+ cancel: (handle: number) => void = cancelAnimationFrame,
+): () => void {
+ const interval = 1000 / fps;
+ let last: number | undefined;
+ let stopped = false;
+ let frame: number;
+ const tick: FrameRequestCallback = (now) => {
+ if (stopped) return;
+ if (last === undefined || now - last >= interval - 0.1) {
+ // Retain fractional frame time without trying to repay missed frames
+ // after a stall. At 120/144 Hz the scene still receives at most 30 fps.
+ last = last === undefined
+ ? now
+ : last + Math.max(1, Math.floor((now - last + 0.1) / interval)) * interval;
+ invalidate();
+ }
+ frame = request(tick);
+ };
+ frame = request(tick);
+ return () => {
+ stopped = true;
+ cancel(frame);
+ };
+}
diff --git a/tests/unit/conductor/test_http_pool.py b/tests/unit/conductor/test_http_pool.py
new file mode 100644
index 0000000000..29f289f391
--- /dev/null
+++ b/tests/unit/conductor/test_http_pool.py
@@ -0,0 +1,211 @@
+"""HTTP jobs must not freeze the serving loop or share authentication state."""
+from __future__ import annotations
+
+import asyncio
+import threading
+
+import httpx
+import pytest
+
+from conductor.core.schema import HttpJobSpec
+from conductor.jobs.http import HttpHandler
+
+
+async def test_tls_initialization_yields_and_concurrent_jobs_share_one_pool(monkeypatch):
+ loop_thread = threading.get_ident()
+ entered = threading.Event()
+ release = threading.Event()
+ calls = []
+ built = []
+
+ class Client:
+ def __init__(self, **kwargs):
+ assert threading.get_ident() != loop_thread
+ built.append(self)
+ entered.set()
+ assert release.wait(5)
+
+ async def request(self, **kwargs):
+ calls.append(kwargs)
+ return httpx.Response(200, text="ok")
+
+ async def aclose(self):
+ calls.append("closed")
+
+ monkeypatch.setattr(httpx, "AsyncClient", Client)
+ handler = HttpHandler()
+ jobs = [asyncio.create_task(handler.execute(HttpJobSpec(
+ url="https://example.test", timeout_s=timeout,
+ ), {})) for timeout in (2, 7)]
+ try:
+ assert await asyncio.to_thread(entered.wait, 3)
+ # This callback runs while the trust-root loader is still blocked.
+ heartbeat = asyncio.Event()
+ asyncio.get_running_loop().call_soon(heartbeat.set)
+ await asyncio.wait_for(heartbeat.wait(), 1)
+ assert not any(job.done() for job in jobs)
+ finally:
+ release.set()
+ results = await asyncio.gather(*jobs)
+ assert all(result.success for result in results)
+ assert len(built) == 1
+ assert sorted(call["timeout"] for call in calls) == [2, 7]
+ await handler.aclose()
+ await handler.aclose()
+ assert calls.count("closed") == 1
+
+
+async def test_cancelled_initialization_closes_the_late_client(monkeypatch):
+ entered = threading.Event()
+ release = threading.Event()
+ closed = []
+
+ class Client:
+ def __init__(self, **kwargs):
+ entered.set()
+ assert release.wait(5)
+
+ async def aclose(self):
+ closed.append(True)
+
+ monkeypatch.setattr(httpx, "AsyncClient", Client)
+ handler = HttpHandler()
+ job = asyncio.create_task(handler.execute(HttpJobSpec(url="https://example.test"), {}))
+ try:
+ assert await asyncio.to_thread(entered.wait, 3)
+ job.cancel()
+ await asyncio.sleep(0)
+ finally:
+ release.set()
+ with pytest.raises(asyncio.CancelledError):
+ await job
+ await handler.aclose()
+ assert closed == [True]
+
+
+async def test_pooled_requests_do_not_share_response_cookies_or_headers(monkeypatch):
+ requests = []
+ client_type = httpx.AsyncClient
+
+ def respond(request):
+ requests.append(request)
+ return httpx.Response(200, headers={"set-cookie": "session=private; Path=/"}, text="ok")
+
+ def client(**kwargs):
+ return client_type(transport=httpx.MockTransport(respond), **kwargs)
+
+ monkeypatch.setattr(httpx, "AsyncClient", client)
+ handler = HttpHandler()
+ try:
+ first = await handler.execute(HttpJobSpec(
+ url="https://example.test", headers={"Authorization": "test-only"},
+ ), {})
+ second = await handler.execute(HttpJobSpec(url="https://example.test"), {})
+ assert first.success and second.success
+ assert requests[0].headers["authorization"] == "test-only"
+ assert "authorization" not in requests[1].headers
+ assert "cookie" not in requests[1].headers
+ finally:
+ await handler.aclose()
+
+
+async def test_timeout_keeps_the_pool_usable(monkeypatch):
+ client_type = httpx.AsyncClient
+ attempts = 0
+
+ def respond(request):
+ nonlocal attempts
+ attempts += 1
+ if attempts == 1:
+ raise httpx.ReadTimeout("test timeout")
+ return httpx.Response(200, text="recovered")
+
+ monkeypatch.setattr(httpx, "AsyncClient", lambda **kwargs: client_type(
+ transport=httpx.MockTransport(respond), **kwargs,
+ ))
+ handler = HttpHandler()
+ spec = HttpJobSpec(url="https://example.test", timeout_s=2)
+ try:
+ failed = await handler.execute(spec, {})
+ recovered = await handler.execute(spec, {})
+ assert failed.error == "timeout after 2.0s"
+ assert recovered.success
+ finally:
+ await handler.aclose()
+
+
+async def test_scheduler_stop_cancels_inflight_requests_before_closing_pool(monkeypatch):
+ from conductor.core.runner import Runner
+ from conductor.core.scheduler import Scheduler
+
+ started = asyncio.Event()
+ lifecycle = []
+
+ class Store:
+ async def get_job(self, job_id):
+ return {"id": job_id, "name": "test", "spec_json": HttpJobSpec(
+ url="https://example.test",
+ ).model_dump_json()}
+
+ async def create_run(self, *args, **kwargs):
+ return "run-1"
+
+ async def update_run(self, *args, **kwargs):
+ pass
+
+ class Client:
+ def __init__(self, **kwargs):
+ pass
+
+ async def request(self, **kwargs):
+ started.set()
+ try:
+ await asyncio.Event().wait()
+ finally:
+ lifecycle.append("request ended")
+
+ async def aclose(self):
+ lifecycle.append("pool closed")
+
+ monkeypatch.setattr(httpx, "AsyncClient", Client)
+ store = Store()
+ runner = Runner(store)
+ scheduler = Scheduler(store, runner)
+ await runner.trigger("job-1")
+ try:
+ await asyncio.wait_for(started.wait(), 5)
+ finally:
+ await scheduler.stop()
+ assert lifecycle == ["request ended", "pool closed"]
+ assert not runner._tasks
+
+
+async def test_cli_run_closes_its_pool_before_leaving(tmp_path, monkeypatch):
+ from argparse import Namespace
+
+ from conductor import ConductorStore, Job, ManualSchedule, cli
+
+ path = tmp_path / "jobs.sqlite"
+ store = ConductorStore(path)
+ await store.init()
+ job_id = await store.upsert_job(Job(
+ name="HTTP cleanup", spec=HttpJobSpec(url="https://example.test"),
+ schedule=ManualSchedule(),
+ ))
+ await store.close()
+ closed = []
+
+ class Client:
+ def __init__(self, **kwargs):
+ pass
+
+ async def request(self, **kwargs):
+ return httpx.Response(200, text="ok")
+
+ async def aclose(self):
+ closed.append(True)
+
+ monkeypatch.setattr(httpx, "AsyncClient", Client)
+ monkeypatch.setattr(cli, "_resolve_db_path", lambda: path)
+ assert await cli.cmd_run(Namespace(id=job_id, input_json=None, timeout=10)) == 0
+ assert closed == [True]