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(society): open model picker from already loaded chat catalog
rubenluetke10-beepa719e3ec7855
diff --git a/jarvis/ui/web/frontend/src/components/society/chat/AgentModelPicker.test.tsx b/jarvis/ui/web/frontend/src/components/society/chat/AgentModelPicker.test.tsxindex 8b4aeb84ba..22dff359cb 100644--- a/jarvis/ui/web/frontend/src/components/society/chat/AgentModelPicker.test.tsx+++ b/jarvis/ui/web/frontend/src/components/society/chat/AgentModelPicker.test.tsx@@ -1,13 +1,15 @@import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import * as Dialog from "@radix-ui/react-dialog";-import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";+import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";import { afterEach, beforeEach, expect, test, vi } from "vitest";import { loadLocaleChunk } from "@/i18n";-import type { AgentChatProvider } from "@/lib/agentChatApi";+import type { AgentChatProvider, AgentConnectionRow } from "@/lib/agentChatApi";import { SAMPLE_ROSTER } from "../mockRoster";import { rowToAgent, useSocietyAgent, type SocietyAgent } from "../data";import { AgentModelPicker } from "./AgentModelPicker";import type { SocietyAgentRow } from "@/lib/societyApi";+import { AgentChatStoreProvider } from "@/components/agentchat/AgentChatStoreContext";+import { createAgentChatStore, type AgentChatStoreHook } from "@/store/agentChat";const provider = (id: string, overrides: Partial<AgentChatProvider> = {}): AgentChatProvider => ({id, label: id, family: id, runner: "brain", models_source: "curated",@@ -24,6 +26,9 @@ let liveModels: Record<string, { id: string; label: string }[]>;let providerRows: unknown[];let catalogCalls: number;let saving: ReturnType<typeof vi.fn>;+let catalogGate: Promise<void> | undefined;+let connectionsGate: Promise<void> | undefined;+let accountsGate: Promise<void> | undefined;beforeEach(async () => {await loadLocaleChunk("society");@@ -34,7 +39,11 @@ beforeEach(async () => {} as unknown as SocietyAgentRow;posts = []; failSave = false; saving = vi.fn();extraProviders = []; liveModels = {}; providerRows = []; catalogCalls = 0;+ catalogGate = undefined; connectionsGate = undefined; accountsGate = undefined;vi.stubGlobal("fetch", vi.fn(async (url: string, init?: RequestInit) => {+ if (url.includes("/catalog")) await catalogGate;+ if (url.endsWith("/status")) await connectionsGate;+ if (url.endsWith("/providers")) await accountsGate;const response = (data: unknown, ok = true) => ({ ok, status: ok ? 200 : 503, json: async () => data }) as Response;if (url.endsWith("/model")) {const choice = JSON.parse(String(init?.body));@@ -53,19 +62,61 @@ beforeEach(async () => {});afterEach(() => { cleanup(); vi.unstubAllGlobals(); });-function mount(busy = false, inDialog = false) {+function mount(busy = false, inDialog = false, store?: AgentChatStoreHook) {const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });const initial: SocietyAgent = { ...SAMPLE_ROSTER[1], ...rowToAgent(row) };client.setQueryData(["society", "roster"], { agents: [initial], sample: false });function Subject() {const { agent } = useSocietyAgent("scout");- return <AgentModelPicker agent={agent ?? initial} busy={busy} onSavingChange={saving} />;+ const picker = <AgentModelPicker agent={agent ?? initial} busy={busy} onSavingChange={saving} />;+ return store ? <AgentChatStoreProvider store={store}>{picker}</AgentChatStoreProvider> : picker;}return render(<QueryClientProvider client={client}>{inDialog ? <Dialog.Root defaultOpen><Dialog.Content><Dialog.Title>Agent</Dialog.Title><Dialog.Description>Model controls</Dialog.Description><Subject /></Dialog.Content></Dialog.Root> : <Subject />}</QueryClientProvider>);}+test("already loaded chat models are immediately selectable while every refresh is stalled", async () => {+ let release!: () => void;+ catalogGate = connectionsGate = accountsGate = new Promise<void>((resolve) => { release = resolve; });+ const store = createAgentChatStore("society");+ store.setState({+ catalog: { providers: [provider("openai")], default_cwd: "", shell: "" },+ connections: [{ jarvis: "openai", key_set: true }] as AgentConnectionRow[],+ });+ try {+ mount(false, false, store);+ fireEvent.click(screen.getByRole("button", { name: "Model" }));+ // Synchronous: no await, no timers and none of the requests has resolved.+ expect(screen.getByTitle("openai-small")).toBeTruthy();+ expect(screen.queryByText("Loading the provider catalog…")).toBeNull();+ fireEvent.click(screen.getByTitle("openai-small"));+ await waitFor(() => expect(posts[0].model).toBe("openai-small"));+ } finally {+ await act(async () => { release(); await catalogGate; });+ }+});++test("a cold menu renders models without waiting for subscription account discovery", async () => {+ let release!: () => void;+ accountsGate = new Promise<void>((resolve) => { release = resolve; });+ try {+ mount(); await open();+ expect(screen.getByTitle("gemini-small")).toBeTruthy();+ expect(screen.queryByText("Loading the provider catalog…")).toBeNull();+ } finally {+ await act(async () => { release(); await accountsGate; });+ }+});++test("catalog loading starts when the card mounts, before the picker is clicked", async () => {+ mount();+ await waitFor(() => expect(catalogCalls).toBe(1));+ expect(screen.queryByRole("menu")).toBeNull();+ await open();+ expect(catalogCalls).toBe(1);+});+async function open() {fireEvent.click(screen.getByRole("button", { name: "Model" }));await screen.findByTitle("openai-large");diff --git a/jarvis/ui/web/frontend/src/components/society/chat/AgentModelPicker.tsx b/jarvis/ui/web/frontend/src/components/society/chat/AgentModelPicker.tsxindex d711ff0beb..7e4e475f0d 100644--- a/jarvis/ui/web/frontend/src/components/society/chat/AgentModelPicker.tsx+++ b/jarvis/ui/web/frontend/src/components/society/chat/AgentModelPicker.tsx@@ -4,6 +4,7 @@ import { useQueries, useQuery } from "@tanstack/react-query";import { Check, ChevronDown, ChevronRight, Loader2, RefreshCw, Search, Users } from "lucide-react";import { ProviderLogo } from "@/components/providers/ProviderLogo";import { effortLabel } from "@/components/agentchat/AgentComposer";+import { useAgentChat } from "@/components/agentchat/AgentChatStoreContext";import { useT } from "@/i18n";import { fetchAgentChatCatalog, fetchAgentConnections, fetchProviderModels, type CuratedModel } from "@/lib/agentChatApi";import { fetchSocietyProviders } from "@/lib/societyApi";@@ -37,22 +38,29 @@ export function AgentModelPicker({ agent, busy, onSavingChange }: {const input = useRef<HTMLInputElement>(null);const inFlight = useRef(false);- const catalog = useQuery({ queryKey: ["agent-chat", "catalog", "society"], queryFn: () => fetchAgentChatCatalog("society"), enabled: open, staleTime: 60_000 });- const connections = useQuery({ queryKey: ["agent-chat", "connections"], queryFn: fetchAgentConnections, enabled: open, staleTime: 60_000 });- const providers = useQuery({ queryKey: ["society", "providers"], queryFn: fetchSocietyProviders, enabled: open, staleTime: 60_000 });- const options = useMemo(() => joinProviderOptions(catalog.data?.providers ?? [], connections.data ?? []), [catalog.data, connections.data]);+ const chatCatalog = useAgentChat((state) => state.surface === "society" ? state.catalog : null);+ const chatConnections = useAgentChat((state) => state.connections);+ // Start with the card, not its first click. The chat store has usually already+ // loaded these same facts; a slow refresh must not replace them with a spinner.+ const catalog = useQuery({ queryKey: ["agent-chat", "catalog", "society"], queryFn: () => fetchAgentChatCatalog("society"), placeholderData: chatCatalog ?? undefined, staleTime: 60_000 });+ const connections = useQuery({ queryKey: ["agent-chat", "connections"], queryFn: fetchAgentConnections, placeholderData: chatCatalog ? chatConnections : undefined, staleTime: 60_000 });+ const providers = useQuery({ queryKey: ["society", "providers"], queryFn: fetchSocietyProviders, staleTime: 60_000 });+ const availableCatalog = catalog.data ?? chatCatalog;+ const availableConnections = connections.data ?? (chatCatalog ? chatConnections : undefined);+ const options = useMemo(() => joinProviderOptions(availableCatalog?.providers ?? [], availableConnections ?? []), [availableCatalog, availableConnections]);const liveProviders = options.filter((option) => option.connected && option.models_source === "live");const liveQueries = useQueries({ queries: liveProviders.map((provider) => ({queryKey: ["society", "model-menu", "live", provider.id],queryFn: async (): Promise<CuratedModel[]> => (await fetchProviderModels(provider.id)).map((model) => ({ id: model.id, label: model.label ?? model.name ?? model.id })),- enabled: open && connections.isSuccess, staleTime: 60_000, retry: false,+ enabled: open && Boolean(availableConnections), staleTime: 60_000, retry: false,})) });const live: Record<string, CuratedModel[]> = {};liveProviders.forEach((provider, index) => { if (liveQueries[index].data) live[provider.id] = liveQueries[index].data!; });const seats = modelSeats(options, providers.data ?? [], live);- const loading = catalog.isLoading || connections.isLoading || providers.isLoading;+ // Subscription accounts enrich the menu independently of its model rows.+ const loading = !availableCatalog || !availableConnections;const refreshing = catalog.isFetching || connections.isFetching || providers.isFetching || liveQueries.some((query) => query.isFetching);- const failed = catalog.isError || connections.isError || providers.isError;+ const failed = (!availableCatalog && catalog.isError) || (!availableConnections && connections.isError);const currentAccount = (seat: BrainSeat) => accounts[seat.provider.id] ?? (agent.provider === seat.provider.id ? agent.accountId ?? "" : "");const preferredEffort = (seat: BrainSeat, model: CuratedModel) => modelEffort(seat, model.id, seat.provider.id === agent.provider ? agent.effort : seat.provider.default_effort);const groups = seats.map((seat) => ({ seat, title: providerTitle(seat, t),diff --git a/jarvis/ui/web/frontend/src/lib/agentChatApi.ts b/jarvis/ui/web/frontend/src/lib/agentChatApi.tsindex 30e602f5fb..8589d2c5f9 100644--- a/jarvis/ui/web/frontend/src/lib/agentChatApi.ts+++ b/jarvis/ui/web/frontend/src/lib/agentChatApi.ts@@ -184,9 +184,19 @@ async function json<T>(res: Response, what: string): Promise<T> {return (await res.json()) as T;}-export async function fetchAgentChatCatalog(surface?: AgentChatSurface): Promise<AgentChatCatalog> {+// A chat and its picker mount together. Share their in-flight reads without+// caching completed requests: explicit refreshes must still reach the server.+const catalogRequests = new Map<string, Promise<AgentChatCatalog>>();++export function fetchAgentChatCatalog(surface?: AgentChatSurface): Promise<AgentChatCatalog> {const query = surface ? `?surface=${encodeURIComponent(surface)}` : "";- return json(await fetch(`/api/agent-chat/catalog${query}`), "catalog-failed");+ const pending = catalogRequests.get(query);+ if (pending) return pending;+ const request = fetch(`/api/agent-chat/catalog${query}`)+ .then((response) => json<AgentChatCatalog>(response, "catalog-failed"))+ .finally(() => catalogRequests.delete(query));+ catalogRequests.set(query, request);+ return request;}export interface TypeaheadRow {@@ -243,12 +253,15 @@ export async function fetchProviderHealth(return Array.isArray(data.providers) ? data.providers : [];}-export async function fetchAgentConnections(): Promise<AgentConnectionRow[]> {- const data = await json<{ mapping?: AgentConnectionRow[] }>(- await fetch("/api/jarvis-agent/status"),- "status-failed",- );- return Array.isArray(data.mapping) ? data.mapping : [];+let connectionRequest: Promise<AgentConnectionRow[]> | null = null;++export function fetchAgentConnections(): Promise<AgentConnectionRow[]> {+ if (connectionRequest) return connectionRequest;+ connectionRequest = fetch("/api/jarvis-agent/status")+ .then((response) => json<{ mapping?: AgentConnectionRow[] }>(response, "status-failed"))+ .then((data) => Array.isArray(data.mapping) ? data.mapping : [])+ .finally(() => { connectionRequest = null; });+ return connectionRequest;}export interface LiveModel {diff --git a/jarvis/ui/web/frontend/src/lib/agentChatCatalogRequests.test.ts b/jarvis/ui/web/frontend/src/lib/agentChatCatalogRequests.test.tsnew file mode 100644index 0000000000..c95932434f--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/agentChatCatalogRequests.test.ts@@ -0,0 +1,45 @@+import { afterEach, expect, test, vi } from "vitest";+import { fetchAgentChatCatalog, fetchAgentConnections } from "./agentChatApi";++afterEach(() => vi.unstubAllGlobals());++test("concurrent catalog readers share a request, but surfaces and later refreshes remain separate", async () => {+ let release!: (response: Response) => void;+ const pending = new Promise<Response>((resolve) => { release = resolve; });+ const request = vi.fn(() => pending);+ vi.stubGlobal("fetch", request);+ const first = fetchAgentChatCatalog("society");+ const second = fetchAgentChatCatalog("society");+ const other = fetchAgentChatCatalog("jarvis");+ expect(first).toBe(second);+ expect(request).toHaveBeenCalledTimes(2);+ // The response stub permits each distinct surface to read its own body.+ release({ ok: true, json: async () => ({ providers: [] }) } as Response);+ await Promise.all([first, second, other]);+ await fetchAgentChatCatalog("society");+ expect(request).toHaveBeenCalledTimes(3);+});++test("concurrent credential-status readers share the in-flight request", async () => {+ const request = vi.fn(async () => ({ ok: true, json: async () => ({ mapping: [] }) }) as Response);+ vi.stubGlobal("fetch", request);+ const first = fetchAgentConnections();+ const second = fetchAgentConnections();+ expect(first).toBe(second);+ await Promise.all([first, second]);+ expect(request).toHaveBeenCalledTimes(1);+ await fetchAgentConnections();+ expect(request).toHaveBeenCalledTimes(2);+});++test("a rejected discovery request is released so a later retry can succeed", async () => {+ const request = vi.fn().mockRejectedValueOnce(new Error("offline"))+ .mockResolvedValue({ ok: true, json: async () => ({ providers: [] }) });+ vi.stubGlobal("fetch", request);+ const first = fetchAgentChatCatalog("society");+ const second = fetchAgentChatCatalog("society");+ const results = await Promise.allSettled([first, second]);+ expect(results.map((result) => result.status)).toEqual(["rejected", "rejected"]);+ await expect(fetchAgentChatCatalog("society")).resolves.toEqual({ providers: [] });+ expect(request).toHaveBeenCalledTimes(2);+});