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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
perf(local-models): mount panels from a seeded provider id and share one /api/providers request
rubenluetke10-beepba762960bd16
diff --git a/jarvis/ui/web/frontend/src/hooks/useProviders.dedupe.test.tsx b/jarvis/ui/web/frontend/src/hooks/useProviders.dedupe.test.tsxnew file mode 100644index 0000000000..03f8d33a06--- /dev/null+++ b/jarvis/ui/web/frontend/src/hooks/useProviders.dedupe.test.tsx@@ -0,0 +1,77 @@+/**+ * Two `useProviders` instances in one tree share ONE `/api/providers`+ * request; an explicit `refetch()` still asks the server again.+ */+import { act, cleanup, renderHook, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { _resetProvidersCacheForTests, useProviders } from "./useProviders";++function jsonResponse(body: unknown): Response {+ return { ok: true, status: 200, json: async () => body } as Response;+}++beforeEach(() => {+ _resetProvidersCacheForTests();+});++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+});++describe("useProviders request sharing", () => {+ it("two hooks mounted together issue a single fetch", async () => {+ const provider = { id: "ollama", supports_model_pull: true };+ const fetchMock = vi+ .fn()+ .mockResolvedValue(jsonResponse({ providers: [provider] }));+ vi.stubGlobal("fetch", fetchMock);++ const { result } = renderHook(() => ({+ a: useProviders(),+ b: useProviders(),+ }));+ await waitFor(() => expect(result.current.a.loading).toBe(false));+ await waitFor(() => expect(result.current.b.loading).toBe(false));++ expect(fetchMock).toHaveBeenCalledTimes(1);+ expect(result.current.a.providers).toEqual([provider]);+ expect(result.current.b.providers).toEqual([provider]);+ });++ it("one window event fans out to every instance but fetches once", async () => {+ const fetchMock = vi+ .fn()+ .mockResolvedValue(jsonResponse({ providers: [] }));+ vi.stubGlobal("fetch", fetchMock);++ const { result } = renderHook(() => ({+ a: useProviders(),+ b: useProviders(),+ }));+ await waitFor(() => expect(result.current.a.loading).toBe(false));+ expect(fetchMock).toHaveBeenCalledTimes(1);++ await act(async () => {+ window.dispatchEvent(new CustomEvent("jarvis:brain-switched"));+ await Promise.resolve();+ });+ await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));+ });++ it("a remount starts from the last good list", async () => {+ const provider = { id: "ollama" };+ const fetchMock = vi+ .fn()+ .mockResolvedValue(jsonResponse({ providers: [provider] }));+ vi.stubGlobal("fetch", fetchMock);++ const first = renderHook(() => useProviders());+ await waitFor(() => expect(first.result.current.loading).toBe(false));+ first.unmount();++ const second = renderHook(() => useProviders());+ expect(second.result.current.providers).toEqual([provider]);+ });+});diff --git a/jarvis/ui/web/frontend/src/hooks/useProviders.ts b/jarvis/ui/web/frontend/src/hooks/useProviders.tsindex 5dad0aa3f7..0dd4f7f68b 100644--- a/jarvis/ui/web/frontend/src/hooks/useProviders.ts+++ b/jarvis/ui/web/frontend/src/hooks/useProviders.ts@@ -292,45 +292,85 @@ interface UseProvidersOptions {retryDelaysMs?: readonly number[];}+/**+ * One `/api/providers` request shared by every mounted `useProviders`.+ *+ * Several panels of one section mount the hook at once (the section view, the+ * roles panel, the server panel); before this each fired its own request, so+ * one open cost three identical round-trips. Mount-time loads and one window+ * event fan-out now JOIN the request in flight; an explicit `refetch()` still+ * starts a fresh one (server truth after a write must not be an older answer+ * that happened to be pending). `lastGood` is the last list any instance+ * received: a remount on the same page starts from it instead of an empty+ * list, so a tab switch does not blank the consumers for a round-trip.+ */+interface SharedRequest {+ promise: Promise<ProviderDescriptor[]>;+}+let sharedRequest: SharedRequest | null = null;+let lastGood: ProviderDescriptor[] | null = null;+/** Window events already turned into a request — the other instances join. */+const seenEvents = new WeakSet<Event>();++async function fetchProvidersOnce(): Promise<ProviderDescriptor[]> {+ const res = await fetch("/api/providers", { cache: "no-store" });+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ const data: ProvidersResponse = await res.json();+ // A 200 whose body is not the expected shape (a proxy's error page, a+ // partially-written response) must leave an EMPTY list, never+ // `undefined`: every consumer maps or filters this, so one malformed+ // payload would take the whole provider console down with a TypeError+ // instead of showing the honest "no providers" state.+ const list = Array.isArray(data?.providers) ? data.providers : [];+ lastGood = list;+ return list;+}++/** Start a request, or join the one in flight when `join` is set. */+function loadProviders(join: boolean): Promise<ProviderDescriptor[]> {+ if (join && sharedRequest) return sharedRequest.promise;+ const entry: SharedRequest = { promise: fetchProvidersOnce() };+ sharedRequest = entry;+ const clear = () => {+ if (sharedRequest === entry) sharedRequest = null;+ };+ entry.promise.then(clear, clear);+ return entry.promise;+}++/** Test seam: forget the shared request and the last good list. */+export function _resetProvidersCacheForTests(): void {+ sharedRequest = null;+ lastGood = null;+}+/*** Loads /api/providers and re-fetches on relevant WS events. The hook updates* the UI state live whenever a secret is set on the backend or a brain* provider was switched — without the component having to track that itself.*/export function useProviders(options: UseProvidersOptions = {}) {- const [providers, setProviders] = useState<ProviderDescriptor[]>([]);+ const [providers, setProviders] = useState<ProviderDescriptor[]>(+ () => lastGood ?? [],+ );const [loading, setLoading] = useState(true);const [error, setError] = useState<string | null>(null);const requestVersion = useRef(0);- const requestController = useRef<AbortController | null>(null);const retryAttempt = useRef(0);const retryDelays = useRef<readonly number[]>(PROVIDER_RETRY_DELAYS_MS);retryDelays.current = options.retryDelaysMs ?? PROVIDER_RETRY_DELAYS_MS;- const refetch = useCallback(async () => {+ const load = useCallback(async (join: boolean) => {const version = ++requestVersion.current;- requestController.current?.abort();- const controller = new AbortController();- requestController.current = controller;setError(null);try {- const res = await fetch("/api/providers", {- cache: "no-store",- signal: controller.signal,- });- if (!res.ok) throw new Error(`HTTP ${res.status}`);- const data: ProvidersResponse = await res.json();+ const list = await loadProviders(join);if (version === requestVersion.current) {retryAttempt.current = 0;- // A 200 whose body is not the expected shape (a proxy's error page, a- // partially-written response) must leave an EMPTY list, never- // `undefined`: every consumer maps or filters this, so one malformed- // payload would take the whole provider console down with a TypeError- // instead of showing the honest "no providers" state.- setProviders(Array.isArray(data?.providers) ? data.providers : []);+ setProviders(list);}} catch (e) {- if ((e as Error).name !== "AbortError" && version === requestVersion.current) {+ if (version === requestVersion.current) {setError(e instanceof TypeError? PROVIDER_BACKEND_UNREACHABLE@@ -339,10 +379,12 @@ export function useProviders(options: UseProvidersOptions = {}) {}} finally {if (version === requestVersion.current) setLoading(false);- if (requestController.current === controller) requestController.current = null;}}, []);+ /** Fresh server truth — never an answer that was already pending. */+ const refetch = useCallback(() => load(false), [load]);+useEffect(() => {if (error !== PROVIDER_BACKEND_UNREACHABLE || retryDelays.current.length === 0) {return;@@ -375,37 +417,31 @@ export function useProviders(options: UseProvidersOptions = {}) {}, []);useEffect(() => {- void refetch();- const onSecret = () => void refetch();- const onBrain = () => void refetch();- const onTts = () => void refetch();- const onStt = () => void refetch();- const onRealtime = () => void refetch();- const onComputerUse = () => void refetch();- const onDictationPolish = () => void refetch();- window.addEventListener("jarvis:secret-configured", onSecret);- window.addEventListener("jarvis:brain-switched", onBrain);- window.addEventListener("jarvis:tts-switched", onTts);- window.addEventListener("jarvis:stt-switched", onStt);- window.addEventListener("jarvis:realtime-switched", onRealtime);- window.addEventListener("jarvis:computer-use-switched", onComputerUse);- window.addEventListener("jarvis:dictation-polish-switched", onDictationPolish);+ void load(true);+ // One window event reaches every mounted instance; the first one starts+ // the request, the rest join it.+ const onEvent = (e: Event) => {+ const join = seenEvents.has(e);+ seenEvents.add(e);+ void load(join);+ };+ const events = [+ "jarvis:secret-configured",+ "jarvis:brain-switched",+ "jarvis:tts-switched",+ "jarvis:stt-switched",+ "jarvis:realtime-switched",+ "jarvis:computer-use-switched",+ "jarvis:dictation-polish-switched",+ ];+ for (const name of events) window.addEventListener(name, onEvent);return () => {+ // The shared request may still serve another instance: only stop+ // listening for its answer here, never abort it.++requestVersion.current;- requestController.current?.abort();- requestController.current = null;- window.removeEventListener("jarvis:secret-configured", onSecret);- window.removeEventListener("jarvis:brain-switched", onBrain);- window.removeEventListener("jarvis:tts-switched", onTts);- window.removeEventListener("jarvis:stt-switched", onStt);- window.removeEventListener("jarvis:realtime-switched", onRealtime);- window.removeEventListener("jarvis:computer-use-switched", onComputerUse);- window.removeEventListener(- "jarvis:dictation-polish-switched",- onDictationPolish,- );+ for (const name of events) window.removeEventListener(name, onEvent);};- }, [refetch]);+ }, [load]);return { providers, loading, error, refetch, setActiveOptimistic };}diff --git a/jarvis/ui/web/frontend/src/lib/localModelsSeed.test.ts b/jarvis/ui/web/frontend/src/lib/localModelsSeed.test.tsnew file mode 100644index 0000000000..68dce4e722--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/localModelsSeed.test.ts@@ -0,0 +1,31 @@+import { afterEach, describe, expect, it } from "vitest";++import {+ LOCAL_MODELS_SEED_KEY,+ clearLocalModelsSeed,+ readLocalModelsSeed,+ writeLocalModelsSeed,+} from "./localModelsSeed";++afterEach(() => {+ window.localStorage.removeItem(LOCAL_MODELS_SEED_KEY);+});++describe("localModelsSeed", () => {+ it("reads null when nothing is stored", () => {+ expect(readLocalModelsSeed()).toBeNull();+ });++ it("round-trips a provider id and ignores empty writes", () => {+ writeLocalModelsSeed("ollama");+ expect(readLocalModelsSeed()).toBe("ollama");+ writeLocalModelsSeed(" ");+ expect(readLocalModelsSeed()).toBe("ollama");+ });++ it("clears the seed", () => {+ writeLocalModelsSeed("ollama");+ clearLocalModelsSeed();+ expect(readLocalModelsSeed()).toBeNull();+ });+});diff --git a/jarvis/ui/web/frontend/src/lib/localModelsSeed.ts b/jarvis/ui/web/frontend/src/lib/localModelsSeed.tsnew file mode 100644index 0000000000..ae267573a7--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/localModelsSeed.ts@@ -0,0 +1,48 @@+/**+ * Local, synchronous seed for the Local models section: the id of the one+ * provider card that can download models (`supports_model_pull`).+ *+ * The section used to wait for `/api/providers` before it mounted a single+ * panel — 2–3 s of nothing on a cold backend. The pull-capable id barely ever+ * changes, so the last resolved one is mirrored into `localStorage` (same+ * pattern as `assistantNameCache.ts`) and the view mounts its panels from the+ * seed at once while the provider list resolves in the background. When the+ * list arrives and the seeded card turns out NOT to be pull-capable any more,+ * the seed is cleared and the view falls back to the honest "no server" state.+ */++/** localStorage key holding the last pull-capable provider id. */+export const LOCAL_MODELS_SEED_KEY = "jarvis.localModels.pullProvider";++/**+ * Synchronously read the seeded provider id; `null` when none is stored or+ * storage is unavailable (private mode / embedded WebView policies).+ */+export function readLocalModelsSeed(): string | null {+ try {+ const raw = window.localStorage.getItem(LOCAL_MODELS_SEED_KEY);+ const trimmed = raw ? raw.trim() : "";+ return trimmed || null;+ } catch {+ return null;+ }+}++/** Persist the resolved id; empty ids are ignored, blocked storage is a no-op. */+export function writeLocalModelsSeed(providerId: string): void {+ try {+ const trimmed = (providerId || "").trim();+ if (trimmed) window.localStorage.setItem(LOCAL_MODELS_SEED_KEY, trimmed);+ } catch {+ // Storage disabled — non-fatal; the next open simply waits for the list.+ }+}++/** Forget the seed (the card is gone or lost its pull capability). */+export function clearLocalModelsSeed(): void {+ try {+ window.localStorage.removeItem(LOCAL_MODELS_SEED_KEY);+ } catch {+ // Nothing to recover: a seed that cannot be read cannot mislead either.+ }+}