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(agents): make the Agents section answer at once

rubenluetke10-beep0d2d1b5c6dd5
diff --git a/jarvis/brain/model_catalog.py b/jarvis/brain/model_catalog.py
index efd4ad14f6..b971188e59 100644
--- a/jarvis/brain/model_catalog.py
+++ b/jarvis/brain/model_catalog.py
@@ -1668,6 +1668,13 @@ def shared_catalog() -> ModelCatalog:
return _shared_catalog
+#: A provider whose live list just failed (a local server that is not running:
+#: on Windows each refused connect costs about two seconds) is not asked again
+#: for this long; the picker gets its fallback at once. ``force_refresh`` and a
+#: successful fetch clear it.
+_FETCH_RETRY_SECONDS = 30.0
+
+
class ModelCatalog:
"""Live model lists per provider with a TTL cache and honest fallbacks."""
@@ -1684,6 +1691,7 @@ class ModelCatalog:
# provider -> (fetched_at, models)
self._cache: dict[str, tuple[float, list[ModelInfo]]] = {}
self._lock = asyncio.Lock()
+ self._fetch_failed_at: dict[str, float] = {}
self._client_factory = http_client_factory
# When the discovery feed last failed to load (0 = never).
self._discovery_failed_at = 0.0
@@ -1828,10 +1836,16 @@ class ModelCatalog:
"model",
)
+ failed_at = self._fetch_failed_at.get(provider, 0.0)
+ recently_failed = not force_refresh and time.time() - failed_at < _FETCH_RETRY_SECONDS
try:
+ if recently_failed:
+ raise RuntimeError("the last fetch failed moments ago")
models = await self._fetch_raw(provider)
except Exception as exc: # noqa: BLE001 — a UI list must never crash the page.
- log.info("Model catalog fetch for %s failed: %s", provider, exc)
+ if not recently_failed:
+ log.info("Model catalog fetch for %s failed: %s", provider, exc)
+ self._fetch_failed_at[provider] = time.time()
if cached:
return CatalogResult(
provider,
@@ -1853,6 +1867,7 @@ class ModelCatalog:
)
now = time.time()
+ self._fetch_failed_at.pop(provider, None)
self._cache[provider] = (now, models)
self._save_cache()
return CatalogResult(
diff --git a/jarvis/tasks/scheduler.py b/jarvis/tasks/scheduler.py
index 2272f8e33c..16fd4bfd76 100644
--- a/jarvis/tasks/scheduler.py
+++ b/jarvis/tasks/scheduler.py
@@ -139,6 +139,8 @@ class TaskScheduler:
self._fired_dedup: dict[tuple[str, str], None] = {}
# Pending runner tasks, so we can clean up on cancel.
self._runner_tasks: set[asyncio.Task[Any]] = set()
+ #: TaskScheduled publishes still in flight (kept referenced until done).
+ self._publish_tasks: set[asyncio.Task[Any]] = set()
# Per-run cancel tokens (H-03): cancel_task() fires the token of a
# RUNNING task so its harness action stops; cleared in _safe_run.
self._running_tokens: dict[str, Any] = {}
@@ -162,15 +164,24 @@ class TaskScheduler:
due_at_ns = row.get("due_at_ns") if row is not None else self._due_at_ns_for(spec)
self._register_in_memory(spec, task_id, stored_due_at_ns=due_at_ns)
# The event, heap and database must agree even across a clock boundary.
- await self._bus.publish(
- TaskScheduled(
- task_id=task_id,
- trigger_type=spec.trigger.type,
- due_at_ns=due_at_ns or 0,
- title=spec.title,
- source_layer="tasks.scheduler",
- )
+ # Published without waiting: every bus-wide listener (chat bridges, the
+ # web forwarder, this scheduler's own locked handler) may take seconds,
+ # and the caller — often a person pressing "Save" — needs only the id.
+ # Heap and row are already consistent, so nothing depends on the order.
+ publish = asyncio.create_task(
+ self._bus.publish(
+ TaskScheduled(
+ task_id=task_id,
+ trigger_type=spec.trigger.type,
+ due_at_ns=due_at_ns or 0,
+ title=spec.title,
+ source_layer="tasks.scheduler",
+ )
+ ),
+ name=f"task-scheduled-{task_id}",
)
+ self._publish_tasks.add(publish)
+ publish.add_done_callback(self._publish_tasks.discard)
self._wakeup.set()
return task_id
diff --git a/jarvis/ui/web/frontend/src/components/society/cardData.ts b/jarvis/ui/web/frontend/src/components/society/cardData.ts
index 4b06d314ba..9ace04453f 100644
--- a/jarvis/ui/web/frontend/src/components/society/cardData.ts
+++ b/jarvis/ui/web/frontend/src/components/society/cardData.ts
@@ -356,8 +356,11 @@ export function useCreateAgentRoutine() {
throw new Error(reason);
}
const payload = (await res.json()) as { id?: string; title?: string };
+ // Only the agent's own list is waited for (one small read) so the new
+ // routine is on screen when the composer closes; the Automations views
+ // catch up in the background.
+ void client.invalidateQueries({ queryKey: ["tasks"] });
await client.invalidateQueries({ queryKey: ["society", "agent-routines", agentId] });
- await client.invalidateQueries({ queryKey: ["tasks"] });
return { id: String(payload.id ?? ""), title: String(payload.title ?? body.title) };
},
[client],
diff --git a/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx b/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx
index 37539bfbb3..eb1f1cc121 100644
--- a/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx
@@ -150,7 +150,12 @@ export function CreateAgentDialog({ open, onClose, onCreated }: CreateAgentDialo
// joined with the Agents tab's credential truth exactly as the chat's
// composer joins it, plus the subscription logins stored per CLI.
const catalog = useQuery({
- queryKey: ["agent-chat", "catalog", "society", accountId],
+ // Without an account this is the very query the Agents view prepared on
+ // mount (`useModelMenuData`, seeded from the saved snapshot), so the
+ // picker fills the instant the dialog opens instead of refetching.
+ queryKey: accountId
+ ? ["agent-chat", "catalog", "society", accountId]
+ : ["agent-chat", "catalog", "society"],
queryFn: () => fetchAgentChatCatalog("society", { accountId }),
enabled: open,
staleTime: 60_000,
@@ -168,8 +173,10 @@ export function CreateAgentDialog({ open, onClose, onCreated }: CreateAgentDialo
staleTime: 60_000,
});
// A keyless row (Ollama, a local server) is listed only when it answers
- // with models, so those lists are fetched before the picker fills; a keyed
- // row's live list is fetched once it is picked, like the composer does.
+ // with models. The picker does not wait for them: the other seats show at
+ // once and a local row joins when its server answers (each list is capped
+ // by `MODEL_LIST_TIMEOUT_MS`). A keyed row's live list is fetched once it
+ // is picked, like the composer does.
const keylessIds = useMemo(
() => (catalog.data?.providers ?? []).filter((p) => p.keyless && p.models_source === "live").map((p) => p.id),
[catalog.data],
@@ -194,8 +201,7 @@ export function CreateAgentDialog({ open, onClose, onCreated }: CreateAgentDialo
[keylessModels.data, pickedModels.data],
);
- const seatsLoading =
- catalog.isLoading || connections.isLoading || societyProviders.isLoading || keylessModels.isLoading;
+ const seatsLoading = catalog.isLoading || connections.isLoading || societyProviders.isLoading;
// Joined only once every answer is in (each query settles to [] on a
// failure): a join over a catalog without the credential rows would call
// every API seat unconnected, list the local rows alone, and the default
@@ -203,14 +209,14 @@ export function CreateAgentDialog({ open, onClose, onCreated }: CreateAgentDialo
const defaultModelLabel = t("agent_chat.model_default");
const seats = useMemo<BrainSeat[]>(() => {
const providers = catalog.data?.providers ?? [];
- if (!providers.length || !connections.data || !societyProviders.data || !keylessModels.data) return [];
+ if (!providers.length || !connections.data || !societyProviders.data) return [];
return modelSeats(
joinProviderOptions(providers, connections.data),
societyProviders.data,
liveModels,
defaultModelLabel,
);
- }, [catalog.data, connections.data, societyProviders.data, keylessModels.data, liveModels, defaultModelLabel]);
+ }, [catalog.data, connections.data, societyProviders.data, liveModels, defaultModelLabel]);
const seat = seats.find((s) => s.provider.id === providerId) ?? null;
const accounts = accountChoice(seat);
const efforts = effortsFor(seat, model);
@@ -889,10 +895,18 @@ function seatGroups(seats: BrainSeat[], t: (key: string) => string): ComboboxGro
* The live model lists of `ids`, fetched together; a provider that answers
* nothing (not running, nothing installed, route missing) maps to [].
*/
+/** A provider's model list that has not answered in this long counts as empty. */
+const MODEL_LIST_TIMEOUT_MS = 4_000;
+
async function fetchModelLists(ids: string[]): Promise<Record<string, CuratedModel[]>> {
const lists = await Promise.all(
ids.map(async (id) => {
- const rows = await fetchProviderModels(id).catch(() => []);
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const timeout = new Promise<[]>((resolve) => {
+ timer = setTimeout(() => resolve([]), MODEL_LIST_TIMEOUT_MS);
+ });
+ const rows = await Promise.race([fetchProviderModels(id).catch(() => []), timeout]);
+ clearTimeout(timer);
return [id, rows.map((m) => ({ id: m.id, label: m.label ?? m.name ?? m.id }))] as const;
}),
);
diff --git a/jarvis/ui/web/frontend/src/components/society/data.ts b/jarvis/ui/web/frontend/src/components/society/data.ts
index 4938e0eaa7..b97979b8df 100644
--- a/jarvis/ui/web/frontend/src/components/society/data.ts
+++ b/jarvis/ui/web/frontend/src/components/society/data.ts
@@ -13,14 +13,14 @@
* the five-layer parity test (AP-4).
*/
import { useCallback, useEffect } from "react";
-import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { useQuery, useQueryClient, type QueryClient } from "@tanstack/react-query";
import type { MentionPlugin } from "./chat/mentionItems";
import type { Checkpoint, SocietyAgentRow } from "@/lib/societyApi";
import { PALETTE_PRESETS, resolvePalette, type FigureRecipe } from "./figures/figureRecipe";
import { SAMPLE_ROSTER } from "./mockRoster";
-import { beginRetirement, retirementRunning } from "./world/retireStore";
+import { beginRetirement, retirementRunning, retirementStageMounted } from "./world/retireStore";
import { announceSpawn } from "./world/spawnStore";
/** MASTERPLAN §2.5 — exactly one lead (Jarvis), orchestrators may ASSIGN. */
@@ -280,6 +280,21 @@ async function fetchSocietyRoster(): Promise<RosterData> {
return { agents: rows, sample: true };
}
+/**
+ * Apply a change to the cached roster right away, then refresh it in the
+ * background. A create or a retirement shows on the rail the moment the
+ * server said yes, instead of after a second full `GET /agents`.
+ */
+function patchRoster(
+ client: QueryClient,
+ change: (agents: readonly SocietyAgent[]) => SocietyAgent[],
+): void {
+ client.setQueryData<RosterData>(ROSTER_QUERY_KEY, (prev) =>
+ prev && !prev.sample ? { ...prev, agents: change(prev.agents) } : prev,
+ );
+ void client.invalidateQueries({ queryKey: ROSTER_QUERY_KEY });
+}
+
export function useSocietyRoster() {
return useQuery({
queryKey: ROSTER_QUERY_KEY,
@@ -397,8 +412,12 @@ export function useCreateAgent() {
const created = (await res.json()) as { agent: SocietyAgentRow };
// The island owes this row an entrance: it walks out of the foundry.
announceSpawn(created.agent.agent_id);
- await client.invalidateQueries({ queryKey: ROSTER_QUERY_KEY });
- return rowToAgent(created.agent);
+ const agent = rowToAgent(created.agent);
+ patchRoster(client, (agents) => [
+ ...agents.filter((a) => a.agentId !== agent.agentId),
+ agent,
+ ]);
+ return agent;
}
if (res.status !== 404 && res.status !== 503) {
const detail = (await res.json().catch(() => null)) as { detail?: unknown } | null;
@@ -651,6 +670,13 @@ export function useRetireAgent() {
throw new Error(`retire ${reason}`);
}
}
+ // No island on screen (the Agents ledger, the office): there is no
+ // ceremony to wait for, so the row leaves the rail now.
+ if (sample || !retirementStageMounted()) {
+ patchRoster(client, (agents) => agents.filter((a) => a.agentId !== agent.agentId));
+ if (sample) await client.invalidateQueries({ queryKey: ROSTER_QUERY_KEY });
+ return;
+ }
const started = beginRetirement({
agentId: agent.agentId,
name: agent.name,
diff --git a/jarvis/ui/web/frontend/src/components/society/world/RetirementScene.tsx b/jarvis/ui/web/frontend/src/components/society/world/RetirementScene.tsx
index 13fce1661f..5161923ed6 100644
--- a/jarvis/ui/web/frontend/src/components/society/world/RetirementScene.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/world/RetirementScene.tsx
@@ -35,6 +35,7 @@ import { buildIsland, groundY } from "./islandLayout";
import * as R from "./retirement";
import {
attachRetirement,
+ registerRetirementStage,
buryRetired,
poseAt,
releaseRetirementPose,
@@ -97,6 +98,10 @@ interface Run {
export function RetirementScene({ paused }: { paused: boolean }) {
const ceremony = useRetireStore((s) => s.ceremony);
+ // Announce the stage while it is mounted: without one a retirement skips
+ // the ceremony and the row leaves the roster at once.
+ useEffect(() => registerRetirementStage(), []);
+
// Tell the store a stage exists, so its "nobody picked this up" watchdog
// stands down and the ceremony is actually played.
useEffect(() => {
diff --git a/jarvis/ui/web/frontend/src/components/society/world/retireStore.ts b/jarvis/ui/web/frontend/src/components/society/world/retireStore.ts
index b0ca9614ac..52305a67c6 100644
--- a/jarvis/ui/web/frontend/src/components/society/world/retireStore.ts
+++ b/jarvis/ui/web/frontend/src/components/society/world/retireStore.ts
@@ -180,6 +180,27 @@ export function beginRetirement(ceremony: Omit<Ceremony, "startedMs">): boolean
return useRetireStore.getState().begin(ceremony);
}
+/** How many ceremony stages (the island's `RetirementScene`) are mounted. */
+let mountedStages = 0;
+
+/**
+ * Called by a stage on mount; returns its unmount cleanup. Only while one is
+ * mounted is a ceremony worth starting — anywhere else (the Agents ledger,
+ * the office) a retirement would sit out `ATTACH_GRACE_MS` for a show nobody
+ * can see before the row leaves.
+ */
+export function registerRetirementStage(): () => void {
+ mountedStages += 1;
+ return () => {
+ mountedStages = Math.max(0, mountedStages - 1);
+ };
+}
+
+/** True when a stage is mounted that can play a retirement ceremony. */
+export function retirementStageMounted(): boolean {
+ return mountedStages > 0;
+}
+
/** Called by the stage the moment it takes the ceremony on. */
export function attachRetirement(): void {
useRetireStore.getState().attach();
diff --git a/jarvis/ui/web/frontend/src/views/society/SocietyView.tsx b/jarvis/ui/web/frontend/src/views/society/SocietyView.tsx
index f39a7e08ae..350b6cb965 100644
--- a/jarvis/ui/web/frontend/src/views/society/SocietyView.tsx
+++ b/jarvis/ui/web/frontend/src/views/society/SocietyView.tsx
@@ -102,9 +102,12 @@ export function SocietyView() {
}
}, [agents, openAgentId]);
- const onCreated = useCallback(() => {
+ // The new agent is already on the rail (the create patched the roster), so
+ // it opens straight away — the person's next step is almost always with it.
+ const onCreated = useCallback((agentId: string) => {
setCreating(false);
- }, []);
+ selectAgent(agentId);
+ }, [selectAgent]);
const [fullscreenError, setFullscreenError] = useState(false);
const switchMode = useCallback((next: "agents" | "world") => {
diff --git a/jarvis/workspace/launch_picks.py b/jarvis/workspace/launch_picks.py
index a4e976f0bb..416593587c 100644
--- a/jarvis/workspace/launch_picks.py
+++ b/jarvis/workspace/launch_picks.py
@@ -27,6 +27,7 @@ instruction.
from __future__ import annotations
+import functools
import logging
import re
from collections.abc import Mapping
@@ -255,37 +256,91 @@ async def live_models() -> dict[str, list[dict[str, Any]]]:
await asyncio.wait_for(shared_catalog().refresh_discovery(), 3.0)
except Exception as exc: # noqa: BLE001 — the cached/curated list stands in
_log.debug("launch picks: model discovery unavailable: %s", exc)
- if _installed("agy-cli"):
- try:
- out["agy-cli"] = await asyncio.wait_for(asyncio.to_thread(read_agy_models), 10.0)
- except Exception as exc: # noqa: BLE001 — the fallback list stands in
- _log.debug("launch picks: agy model list unavailable: %s", exc)
- if _installed("codex-cli"):
- try:
- rows = await asyncio.to_thread(read_codex_models)
- except Exception as exc: # noqa: BLE001 — the fallback list stands in
- _log.debug("launch picks: codex model list unavailable: %s", exc)
- rows = None
- out["codex-cli"] = rows or []
- if _installed("grok-cli"):
- try:
- rows = await asyncio.to_thread(read_grok_models)
- except Exception as exc: # noqa: BLE001 — the fallback list stands in
- _log.debug("launch picks: grok model list unavailable: %s", exc)
- rows = None
- if rows:
- out["grok-cli"] = rows
- if _installed("opencode-cli"):
- # ``opencode models`` — the providers this install configured.
- try:
- rows = await asyncio.wait_for(asyncio.to_thread(read_opencode_models), 25.0)
- except Exception as exc: # noqa: BLE001 — no list is an empty picker, not an error
- _log.debug("launch picks: opencode model list unavailable: %s", exc)
- rows = []
- out["opencode-cli"] = rows
+ # Every reader runs at once, and the answer waits at most
+ # ``_LIVE_MODELS_BUDGET_S``: a cold ``agy models`` has taken well over a
+ # minute on a real box, and summing the readers one after another kept the
+ # picker empty for ten seconds and more. A reader still running when the
+ # budget ends keeps going in its thread and fills its runner-module cache,
+ # so the next catalog request answers from it; this one leaves that
+ # runner's curated fallback standing (its key stays absent, never an empty
+ # list that would blank the picker).
+ readers = {
+ "agy-cli": read_agy_models,
+ "codex-cli": read_codex_models,
+ "grok-cli": read_grok_models,
+ "opencode-cli": read_opencode_models,
+ }
+ installed = await asyncio.to_thread(lambda: [r for r in readers if _installed(r)])
+ tasks = {runner: _shared_read(runner, readers[runner]) for runner in installed}
+ if not tasks:
+ return out
+ done, pending = await asyncio.wait(tasks.values(), timeout=_LIVE_MODELS_BUDGET_S)
+ for task in pending:
+ # Nobody awaits it any more; keep it referenced until it finishes and
+ # log its failure instead of letting asyncio warn about it.
+ _BACKGROUND_READS.add(task)
+ task.add_done_callback(_finish_background_read)
+ for runner, task in tasks.items():
+ if task not in done:
+ _log.debug("launch picks: %s model list still loading; fallback stands", runner)
+ continue
+ failure = task.exception()
+ if failure is not None:
+ _log.debug("launch picks: %s model list unavailable: %s", runner, failure)
+ rows = None if failure is not None else task.result()
+ if runner == "codex-cli":
+ # Codex answered: an empty list means "nothing confirmed" for it.
+ out[runner] = rows or []
+ elif runner == "opencode-cli":
+ # No list is an empty picker, not an error.
+ out[runner] = rows or []
+ elif rows:
+ out[runner] = rows
return out
+#: How long a catalog request waits for the CLIs' own model lists.
+_LIVE_MODELS_BUDGET_S: Final = 3.0
+
+#: Model-list reads that outlived their request, kept alive until they finish.
+_BACKGROUND_READS: set[Any] = set()
+
+
+#: One in-flight read per runner and catalog scope: a second request arriving
+#: while ``agy models`` still runs joins that read instead of starting another.
+_IN_FLIGHT: dict[tuple[Any, ...], Any] = {}
+
+
+def _shared_read(runner: str, read: Any) -> Any:
+ import asyncio
+
+ from jarvis.agent_chat import runner_cli
+
+ key = (
+ runner,
+ runner_cli.ACCOUNT_OVERRIDE.get(),
+ runner_cli._CATALOG_CWD.get(),
+ runner_cli._CATALOG_IGNORE_CONFIG.get(),
+ )
+ task = _IN_FLIGHT.get(key)
+ if task is None or task.done():
+ task = asyncio.ensure_future(asyncio.to_thread(read))
+ _IN_FLIGHT[key] = task
+ task.add_done_callback(functools.partial(_forget_read, key))
+ return task
+
+
+def _forget_read(key: tuple[Any, ...], task: Any) -> None:
+ if _IN_FLIGHT.get(key) is task:
+ del _IN_FLIGHT[key]
+
+
+def _finish_background_read(task: Any) -> None:
+ _BACKGROUND_READS.discard(task)
+ if not task.cancelled() and task.exception() is not None:
+ _log.debug("launch picks: background model list failed: %s", task.exception())
+
+
def _installed(runner: str) -> bool:
"""Is the binary behind ``runner`` resolvable from here?"""
from jarvis.agent_chat.runner_cli import cli_installed
diff --git a/tests/unit/workspace/test_launch_picks.py b/tests/unit/workspace/test_launch_picks.py
index d4e29624ef..227228793d 100644
--- a/tests/unit/workspace/test_launch_picks.py
+++ b/tests/unit/workspace/test_launch_picks.py
@@ -169,3 +169,39 @@ def test_a_live_list_replaces_the_curated_one() -> None:
assert launch_picks.offered_models("codex", live) == live["codex-cli"]
# And a pick off that list is accepted, not measured against the fallback.
assert launch_picks.runner_of("codex") == "codex-cli"
+
+
+async def test_live_models_answers_within_budget_while_a_slow_cli_keeps_loading(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A cold ``agy models`` took over a minute on a real box; the picker must
+ not wait for it. The fast readers answer, the slow one is left out (its
+ curated fallback stands) and finishes in the background."""
+ import threading
+ import time
+
+ from jarvis.agent_chat import runner_cli
+
+ release = threading.Event()
+
+ def slow_agy() -> list[dict[str, str]]:
+ release.wait(5.0)
+ return [{"id": "late"}]
+
+ monkeypatch.setattr(runner_cli, "read_agy_models", slow_agy)
+ monkeypatch.setattr(runner_cli, "read_codex_models", lambda: [{"id": "gpt"}])
+ monkeypatch.setattr(runner_cli, "read_grok_models", lambda: None)
+ monkeypatch.setattr(runner_cli, "read_opencode_models", lambda: [])
+ monkeypatch.setattr(
+ launch_picks,
+ "_installed",
+ lambda r: r in {"agy-cli", "codex-cli", "grok-cli", "opencode-cli"},
+ )
+ monkeypatch.setattr(launch_picks, "_LIVE_MODELS_BUDGET_S", 0.2)
+ try:
+ started = time.monotonic()
+ out = await launch_picks.live_models()
+ assert time.monotonic() - started < 2.0
+ assert out == {"codex-cli": [{"id": "gpt"}], "opencode-cli": []}
+ finally:
+ release.set()