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(society): persist model menu data and eliminate idle work

rubenluetke10-beep70c944d47e2a
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.tsx
index 22dff359cb..ec6183c91d 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
@@ -10,6 +10,7 @@ import { AgentModelPicker } from "./AgentModelPicker";
import type { SocietyAgentRow } from "@/lib/societyApi";
import { AgentChatStoreProvider } from "@/components/agentchat/AgentChatStoreContext";
import { createAgentChatStore, type AgentChatStoreHook } from "@/store/agentChat";
+import { clearModelMenuSnapshot, MODEL_MENU_SNAPSHOT_KEY, writeModelMenuSnapshot } from "./modelMenuSnapshot";
const provider = (id: string, overrides: Partial<AgentChatProvider> = {}): AgentChatProvider => ({
id, label: id, family: id, runner: "brain", models_source: "curated",
@@ -31,6 +32,7 @@ let connectionsGate: Promise<void> | undefined;
let accountsGate: Promise<void> | undefined;
beforeEach(async () => {
+ clearModelMenuSnapshot();
await loadLocaleChunk("society");
row = {
agent_id: "scout", name: "Scout", title: "Research", description: "Keep my instructions",
@@ -62,6 +64,51 @@ beforeEach(async () => {
});
afterEach(() => { cleanup(); vi.unstubAllGlobals(); });
+test("a first open after page reload needs no request when a snapshot is available", async () => {
+ writeModelMenuSnapshot({ version: 1, savedAt: Date.now(),
+ catalog: { providers: [provider("openai")], default_cwd: "", shell: "" },
+ connections: [{ jarvis: "openai", key_set: true, is_active_brain: false }], providers: [], live: {},
+ });
+ const serialized = localStorage.getItem(MODEL_MENU_SNAPSHOT_KEY)!;
+ clearModelMenuSnapshot();
+ localStorage.setItem(MODEL_MENU_SNAPSHOT_KEY, serialized);
+ mount();
+ fireEvent.click(screen.getByRole("button", { name: "Model" }));
+ expect(screen.getByTitle("openai-small")).toBeTruthy();
+ expect(screen.queryByText("Loading the provider catalog…")).toBeNull();
+ expect(catalogCalls).toBe(0);
+});
+
+test("an idle open menu schedules no animation loop and batches layout changes", async () => {
+ const frames: FrameRequestCallback[] = [];
+ const requestFrame = vi.fn((callback: FrameRequestCallback) => { frames.push(callback); return frames.length; });
+ vi.stubGlobal("requestAnimationFrame", requestFrame);
+ vi.stubGlobal("cancelAnimationFrame", vi.fn());
+ mount(); await open();
+ expect(requestFrame).not.toHaveBeenCalled();
+ fireEvent.resize(window);
+ fireEvent.resize(window);
+ expect(requestFrame).toHaveBeenCalledTimes(1);
+ act(() => frames[0](0));
+ expect(requestFrame).toHaveBeenCalledTimes(1);
+});
+
+test("freshly disconnected credentials supersede a display snapshot", async () => {
+ writeModelMenuSnapshot({ version: 1, savedAt: Date.now(),
+ catalog: { providers: [provider("openai")], default_cwd: "", shell: "" },
+ connections: [{ jarvis: "openai", key_set: true, is_active_brain: false }], providers: [], live: {},
+ });
+ const store = createAgentChatStore("society");
+ mount(false, false, store);
+ fireEvent.click(screen.getByRole("button", { name: "Model" }));
+ expect(screen.getByTitle("openai-small")).toBeTruthy();
+ act(() => store.setState({
+ catalog: { providers: [provider("openai")], default_cwd: "", shell: "" },
+ connections: [{ jarvis: "openai", key_set: false, api_key_set: false, is_active_brain: false }],
+ }));
+ await waitFor(() => expect(screen.queryByTitle("openai-small")).toBeNull());
+});
+
function mount(busy = false, inDialog = false, store?: AgentChatStoreHook) {
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const initial: SocietyAgent = { ...SAMPLE_ROSTER[1], ...rowToAgent(row) };
diff --git a/jarvis/ui/web/frontend/src/components/society/chat/AgentModelPicker.tsx b/jarvis/ui/web/frontend/src/components/society/chat/AgentModelPicker.tsx
index 7e4e475f0d..73a7ab9c84 100644
--- a/jarvis/ui/web/frontend/src/components/society/chat/AgentModelPicker.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/chat/AgentModelPicker.tsx
@@ -1,19 +1,18 @@
import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type KeyboardEvent } from "react";
import { createPortal } from "react-dom";
-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";
+import type { CuratedModel } from "@/lib/agentChatApi";
import { cn } from "@/lib/utils";
-import { joinProviderOptions } from "@/store/agentChat";
import { effortsFor, type BrainSeat } from "../create/brainPicker";
import { useUpdateAgentModel, type SocietyAgent } from "../data";
import { collapsibleModels, matchesModel, modelEffort, modelGroupOrder, modelSeats, providerTitle, visibleModels } from "./modelChoices";
+import { useModelMenuData } from "./useModelMenuData";
+
type Submenu = { provider: string; model?: CuratedModel; anchor: DOMRect };
const menuRow = "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[13px] text-popover-foreground hover:bg-secondary focus-visible:bg-secondary focus-visible:outline-none disabled:opacity-45";
@@ -40,34 +39,19 @@ export function AgentModelPicker({ agent, busy, onSavingChange }: {
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 && 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);
- // 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 = (!availableCatalog && catalog.isError) || (!availableConnections && connections.isError);
+ const { options, providers, live, loading, refreshing, failed, refresh: refreshData } = useModelMenuData(chatCatalog, chatConnections);
+ const seats = useMemo(() => modelSeats(options, providers ?? [], live), [options, providers, live]);
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),
- models: seat.provider.curated_models.filter((model) => matchesModel(seat, model, search, providerTitle(seat, t))),
- })).filter((group) => group.models.length > 0).sort((a, b) => {
- return modelGroupOrder(a.seat) - modelGroupOrder(b.seat) || a.title.localeCompare(b.title);
- });
+ // useT returns a new function each render; memoize by its actual labels.
+ const titleKey = JSON.stringify(seats.map((seat) => providerTitle(seat, t)));
+ const groups = useMemo(() => {
+ const titles = JSON.parse(titleKey) as string[];
+ return seats.map((seat, index) => ({ seat, title: titles[index],
+ models: seat.provider.curated_models.filter((model) => matchesModel(seat, model, search, titles[index])),
+ })).filter((group) => group.models.length > 0).sort((a, b) =>
+ modelGroupOrder(a.seat) - modelGroupOrder(b.seat) || a.title.localeCompare(b.title));
+ }, [seats, search, titleKey]);
const sideSeat = seats.find((seat) => seat.provider.id === submenu?.provider);
function close() {
@@ -100,11 +84,29 @@ export function AgentModelPicker({ agent, busy, onSavingChange }: {
...(above ? { bottom: window.innerHeight - rect.top + 6 } : { top: rect.bottom + 6 }),
};
setPosition((previous) => previous.left === next.left && previous.top === next.top && previous.bottom === next.bottom && previous.width === next.width && previous.maxHeight === next.maxHeight ? previous : next);
- // Dialog content can settle after the menu opens without a window resize.
- frame = requestAnimationFrame(place);
+
+ };
+ const schedule = () => {
+ if (frame) return;
+ frame = requestAnimationFrame(() => { frame = 0; place(); });
};
+ const scroll = (event: Event) => {
+ if (!panel.current?.contains(event.target as Node)) schedule();
+ };
+ const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(schedule);
+ // Resizing the composer or its ancestors can move an unchanged trigger.
+ for (let node: HTMLElement | null = trigger.current; node; node = node.parentElement) observer?.observe(node);
place(); input.current?.focus();
- return () => cancelAnimationFrame(frame);
+ window.addEventListener("resize", schedule);
+ window.addEventListener("scroll", scroll, { capture: true, passive: true });
+ const dialog = trigger.current?.closest('[role="dialog"]');
+ dialog?.addEventListener("animationend", schedule);
+ return () => {
+ cancelAnimationFrame(frame); observer?.disconnect();
+ window.removeEventListener("resize", schedule);
+ window.removeEventListener("scroll", scroll, true);
+ dialog?.removeEventListener("animationend", schedule);
+ };
}, [open]);
useEffect(() => {
@@ -138,7 +140,7 @@ export function AgentModelPicker({ agent, busy, onSavingChange }: {
async function refresh() {
setSubmenu(null);
- await Promise.all([catalog.refetch(), connections.refetch(), providers.refetch(), ...liveQueries.map((query) => query.refetch())]);
+ await refreshData();
}
function moveFocus(event: KeyboardEvent, container: HTMLElement | null) {
diff --git a/jarvis/ui/web/frontend/src/components/society/chat/modelChoices.ts b/jarvis/ui/web/frontend/src/components/society/chat/modelChoices.ts
index 91e45c9ac6..d5cdfc704e 100644
--- a/jarvis/ui/web/frontend/src/components/society/chat/modelChoices.ts
+++ b/jarvis/ui/web/frontend/src/components/society/chat/modelChoices.ts
@@ -63,6 +63,7 @@ export function modelEffort(seat: BrainSeat, model: string, preferred: string):
}
export function matchesModel(seat: BrainSeat, model: CuratedModel, query: string, title: string): boolean {
+ if (!query.trim()) return true;
const fold = (value: string) => value.toLocaleLowerCase().normalize("NFD").replace(/\p{Diacritic}/gu, "").replace(/[-_./]/g, " ");
const haystack = fold([title, seat.provider.id, seat.provider.label, model.id, model.label,
...seat.accounts.map((account) => `${account.label} ${account.email ?? ""}`)].join(" "));
diff --git a/jarvis/ui/web/frontend/src/components/society/chat/modelMenuSnapshot.test.ts b/jarvis/ui/web/frontend/src/components/society/chat/modelMenuSnapshot.test.ts
new file mode 100644
index 0000000000..e23cf742a7
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/chat/modelMenuSnapshot.test.ts
@@ -0,0 +1,64 @@
+import { afterEach, beforeEach, expect, test, vi } from "vitest";
+import { clearModelMenuSnapshot, MODEL_MENU_SNAPSHOT_KEY, readModelMenuSnapshot, writeModelMenuSnapshot, type ModelMenuSnapshot } from "./modelMenuSnapshot";
+
+const snapshot = (): ModelMenuSnapshot => ({
+ version: 1, savedAt: Date.now(),
+ catalog: { default_cwd: "private/workspace", shell: "private/shell", providers: [{
+ id: "example", label: "Example", family: "example", runner: "brain", models_source: "curated",
+ curated_models: [{ id: "small", label: "Small", efforts: ["low"] }], default_model: "small",
+ keyless: false, native_resume: false, effort_levels: ["low"], default_effort: "low",
+ permission_modes: [], default_permission_mode: "ask", cli_installed: null,
+ }] },
+ connections: [{ jarvis: "example", key_set: true, api_key_set: true, is_active_brain: false }],
+ providers: [{ id: "example", label: "Example", family: "example", runner: "brain", subscription: false,
+ keyless: false, platform: null, accounts: [{ id: "work", label: "Work", connected: true, mode: "subscription",
+ message: "private diagnostic", email: "[email protected]", tier: null, warning: null }] }],
+ live: { example: [{ id: "live-small", label: "Live small" }] },
+});
+
+beforeEach(clearModelMenuSnapshot);
+afterEach(() => { vi.restoreAllMocks(); clearModelMenuSnapshot(); });
+
+test("reload retains models and selections without emails, paths or unknown fields", () => {
+ const source = snapshot();
+ Object.assign(source, { token: "must-not-be-saved" });
+ writeModelMenuSnapshot(source);
+ const raw = localStorage.getItem(MODEL_MENU_SNAPSHOT_KEY)!;
+ expect(raw).not.toContain("private");
+ expect(raw).not.toContain("must-not-be-saved");
+ clearModelMenuSnapshot();
+ localStorage.setItem(MODEL_MENU_SNAPSHOT_KEY, raw);
+ const restored = readModelMenuSnapshot()!;
+ expect(restored.catalog.providers[0].curated_models[0].id).toBe("small");
+ expect(restored.live.example[0].id).toBe("live-small");
+ expect(restored.providers[0].accounts[0].id).toBe("work");
+});
+
+test.each(["not-json", '{"version":0}', JSON.stringify({ ...snapshot(), connections: [{ jarvis: "example", key_set: "yes" }] })])("corrupt or incompatible cache falls back to discovery", (raw) => {
+ localStorage.setItem(MODEL_MENU_SNAPSHOT_KEY, raw);
+ expect(readModelMenuSnapshot()).toBeNull();
+});
+
+test("unavailable storage still retains an in-memory snapshot", () => {
+ vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => { throw new Error("storage disabled"); });
+ writeModelMenuSnapshot(snapshot());
+ expect(readModelMenuSnapshot()?.catalog.providers[0].id).toBe("example");
+});
+
+test("shared observers do not serialize and write the same data twice", () => {
+ const write = vi.spyOn(Storage.prototype, "setItem");
+ const source = snapshot();
+ writeModelMenuSnapshot(source);
+ writeModelMenuSnapshot({ ...source, live: { ...source.live } });
+ expect(write).toHaveBeenCalledTimes(1);
+});
+
+test("fresh connection metadata does not make an old live model list fresh", () => {
+ const source = snapshot();
+ source.liveUpdatedAt = { example: Date.now() - 11 * 60_000 };
+ writeModelMenuSnapshot(source);
+ const raw = localStorage.getItem(MODEL_MENU_SNAPSHOT_KEY)!;
+ clearModelMenuSnapshot();
+ localStorage.setItem(MODEL_MENU_SNAPSHOT_KEY, raw);
+ expect(readModelMenuSnapshot()?.liveUpdatedAt?.example).toBe(source.liveUpdatedAt.example);
+});
diff --git a/jarvis/ui/web/frontend/src/components/society/chat/modelMenuSnapshot.ts b/jarvis/ui/web/frontend/src/components/society/chat/modelMenuSnapshot.ts
new file mode 100644
index 0000000000..780475e0dc
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/chat/modelMenuSnapshot.ts
@@ -0,0 +1,91 @@
+/** Display-only cache. Authentication and model changes remain server-owned. */
+import { z } from "zod";
+import type { AgentChatCatalog, AgentConnectionRow, CuratedModel } from "@/lib/agentChatApi";
+import type { SocietyProviderRow } from "@/lib/societyApi";
+
+export const MODEL_MENU_SNAPSHOT_KEY = "jarvis.society.model-menu.v1";
+const MAX_BYTES = 2_000_000;
+const text = z.string().max(1024);
+const model = z.object({ id: text, label: text, efforts: z.array(text).optional(), note: text.optional() });
+const snapshotSchema = z.object({
+ version: z.literal(1), savedAt: z.number().finite().positive(),
+ catalog: z.object({
+ default_cwd: z.unknown().transform(() => ""), shell: z.unknown().transform(() => ""),
+ providers: z.array(z.object({
+ id: text, label: text, family: text, runner: text,
+ models_source: z.enum(["live", "curated"]), curated_models: z.array(model).max(20_000),
+ default_model: text, keyless: z.boolean(), native_resume: z.boolean(),
+ effort_levels: z.array(text), default_effort: text,
+ permission_modes: z.array(z.object({ id: text, label: text, description: text })),
+ default_permission_mode: text, cli_installed: z.boolean().nullable(), agent: text.optional(),
+ })).max(100),
+ }),
+ connections: z.array(z.object({
+ jarvis: text, label: text.optional(), key_set: z.boolean(), api_key_set: z.boolean().optional(),
+ oauth_connected: z.boolean().optional(), is_active_brain: z.boolean().default(false), keyless: z.boolean().optional(),
+ })).max(100),
+ providers: z.array(z.object({
+ id: text, label: text, family: text, runner: text, subscription: z.boolean(), keyless: z.boolean(),
+ platform: text.nullable(), accounts: z.array(z.object({
+ id: text, label: text, connected: z.boolean(), mode: text,
+ message: z.unknown().transform(() => ""), email: z.unknown().transform(() => null),
+ tier: z.unknown().transform(() => null), warning: z.unknown().transform(() => null),
+ })).max(100),
+ })).max(100),
+ live: z.record(z.array(model).max(20_000)),
+ liveUpdatedAt: z.record(z.number().finite().nonnegative()).default({}),
+});
+
+export interface ModelMenuSnapshot {
+ version: 1;
+ savedAt: number;
+ catalog: AgentChatCatalog;
+ connections: AgentConnectionRow[];
+ providers: SocietyProviderRow[];
+ live: Record<string, CuratedModel[]>;
+ liveUpdatedAt?: Record<string, number>;
+}
+
+let memory: ModelMenuSnapshot | null | undefined;
+let lastSource: ModelMenuSnapshot | undefined;
+
+export function readModelMenuSnapshot(): ModelMenuSnapshot | null {
+ if (memory !== undefined) return memory;
+ memory = null;
+ try {
+ const raw = localStorage.getItem(MODEL_MENU_SNAPSHOT_KEY);
+ if (!raw || raw.length > MAX_BYTES) return null;
+ const result = snapshotSchema.safeParse(JSON.parse(raw));
+ if (result.success && result.data.savedAt <= Date.now() + 60_000) memory = result.data;
+ } catch {
+ // Optional display cache: blocked storage or invalid JSON uses live discovery.
+ }
+ return memory;
+}
+
+export function writeModelMenuSnapshot(snapshot: ModelMenuSnapshot): void {
+ if (lastSource?.catalog === snapshot.catalog && lastSource.connections === snapshot.connections
+ && lastSource.providers === snapshot.providers && lastSource.savedAt === snapshot.savedAt
+ && Object.keys(lastSource.live).length === Object.keys(snapshot.live).length
+ && Object.keys(snapshot.live).every((id) => lastSource!.live[id] === snapshot.live[id]
+ && lastSource!.liveUpdatedAt?.[id] === snapshot.liveUpdatedAt?.[id])) return;
+ // Strip unknown fields, emails, paths and diagnostic messages before storage.
+ const result = snapshotSchema.safeParse(snapshot);
+ if (!result.success) return;
+ lastSource = snapshot;
+ memory = result.data;
+ try {
+ const raw = JSON.stringify(result.data);
+ if (raw.length <= MAX_BYTES) localStorage.setItem(MODEL_MENU_SNAPSHOT_KEY, raw);
+ } catch {
+ // Private mode / full storage: the in-memory snapshot still works.
+ }
+}
+
+export function clearModelMenuSnapshot(): void {
+ memory = undefined;
+ lastSource = undefined;
+ try { localStorage.removeItem(MODEL_MENU_SNAPSHOT_KEY); } catch {
+ // Storage can be disabled; clearing memory is sufficient in that case.
+ }
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/chat/useModelMenuData.ts b/jarvis/ui/web/frontend/src/components/society/chat/useModelMenuData.ts
new file mode 100644
index 0000000000..67572e125b
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/chat/useModelMenuData.ts
@@ -0,0 +1,67 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useQueries, useQuery, useQueryClient } from "@tanstack/react-query";
+import type { UseQueryResult } from "@tanstack/react-query";
+import { fetchAgentChatCatalog, fetchAgentConnections, fetchProviderModels, type AgentChatCatalog, type AgentConnectionRow, type CuratedModel } from "@/lib/agentChatApi";
+import { fetchSocietyProviders } from "@/lib/societyApi";
+import { joinProviderOptions } from "@/store/agentChat";
+import { readModelMenuSnapshot, writeModelMenuSnapshot } from "./modelMenuSnapshot";
+
+const EMPTY_CONNECTIONS: AgentConnectionRow[] = [];
+const QUERY_POLICY = { staleTime: 60_000, gcTime: 30 * 60_000, refetchOnWindowFocus: false };
+
+/** Prepare once at the Agents view; the card reuses the same query instances. */
+export function useModelMenuData(chatCatalog: AgentChatCatalog | null = null, chatConnections = EMPTY_CONNECTIONS) {
+ const client = useQueryClient();
+ const previousChatCatalog = useRef(chatCatalog);
+ const [saved] = useState(readModelMenuSnapshot);
+ const catalog = useQuery({ queryKey: ["agent-chat", "catalog", "society"], queryFn: () => fetchAgentChatCatalog("society"),
+ initialData: saved?.catalog, initialDataUpdatedAt: saved?.savedAt, placeholderData: chatCatalog ?? undefined, ...QUERY_POLICY });
+ const connections = useQuery({ queryKey: ["agent-chat", "connections"], queryFn: fetchAgentConnections,
+ initialData: saved?.connections, initialDataUpdatedAt: saved?.savedAt, placeholderData: chatCatalog ? chatConnections : undefined, ...QUERY_POLICY });
+ const providers = useQuery({ queryKey: ["society", "providers"], queryFn: fetchSocietyProviders,
+ initialData: saved?.providers, initialDataUpdatedAt: saved?.savedAt, ...QUERY_POLICY });
+ const availableCatalog = catalog.data ?? chatCatalog;
+ const availableConnections = connections.data ?? (chatCatalog ? chatConnections : undefined);
+ const options = useMemo(() => joinProviderOptions(availableCatalog?.providers ?? [], availableConnections ?? []), [availableCatalog, availableConnections]);
+ const liveProviders = useMemo(() => options.filter((option) => option.connected && option.models_source === "live"), [options]);
+ const combine = useCallback((queries: UseQueryResult<CuratedModel[], Error>[]) => ({
+ live: Object.fromEntries(queries.flatMap((query, index) => query.data ? [[liveProviders[index].id, query.data]] : [])) as Record<string, CuratedModel[]>,
+ updatedAt: Object.fromEntries(queries.map((query, index) => [liveProviders[index].id, query.dataUpdatedAt])),
+ fetching: queries.some((query) => query.isFetching),
+ refresh: () => Promise.all(queries.map((query) => query.refetch())),
+ }), [liveProviders]);
+ const models = 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 })),
+ initialData: saved?.live[provider.id], initialDataUpdatedAt: saved?.liveUpdatedAt?.[provider.id] ?? saved?.savedAt,
+ enabled: Boolean(availableConnections), ...QUERY_POLICY, staleTime: 10 * 60_000, retry: false,
+ })), combine });
+
+ useEffect(() => {
+ if (chatCatalog && previousChatCatalog.current !== chatCatalog) {
+ // A fresh chat-store load after a key/account change supersedes the
+ // display snapshot, including providers that have just disconnected.
+ client.setQueryData(["agent-chat", "catalog", "society"], chatCatalog);
+ client.setQueryData(["agent-chat", "connections"], chatConnections);
+ }
+ previousChatCatalog.current = chatCatalog;
+ }, [client, chatCatalog, chatConnections]);
+
+ useEffect(() => {
+ if (!availableCatalog || !availableConnections || !providers.data) return;
+ // Coalesce independently arriving lists; never stringify during the click.
+ const timer = window.setTimeout(() => writeModelMenuSnapshot({
+ version: 1, savedAt: Math.min(catalog.dataUpdatedAt || Date.now(), connections.dataUpdatedAt || Date.now(), providers.dataUpdatedAt || Date.now()),
+ catalog: availableCatalog, connections: availableConnections, providers: providers.data!, live: models.live, liveUpdatedAt: models.updatedAt,
+ }), 100);
+ return () => window.clearTimeout(timer);
+ }, [availableCatalog, availableConnections, providers.data, models.live, models.updatedAt, catalog.dataUpdatedAt, connections.dataUpdatedAt, providers.dataUpdatedAt]);
+
+ return {
+ options, live: models.live, providers: providers.data,
+ loading: !availableCatalog || !availableConnections,
+ refreshing: catalog.isFetching || connections.isFetching || providers.isFetching || models.fetching,
+ failed: (!availableCatalog && catalog.isError) || (!availableConnections && connections.isError),
+ refresh: () => Promise.all([catalog.refetch(), connections.refetch(), providers.refetch(), models.refresh()]),
+ };
+}
diff --git a/jarvis/ui/web/frontend/src/store/agentChat.test.ts b/jarvis/ui/web/frontend/src/store/agentChat.test.ts
index 7a3cf68d8f..54c27a3114 100644
--- a/jarvis/ui/web/frontend/src/store/agentChat.test.ts
+++ b/jarvis/ui/web/frontend/src/store/agentChat.test.ts
@@ -318,3 +318,12 @@ describe("agent-chat store session switch", () => {
expect(store.getState().timeline.items[0]).toMatchObject({ text: "gmail-inbox" });
});
});
+
+
+it("opening a society catalog never runs paid provider health probes", async () => {
+ const calls = stubFetch([]);
+ await createAgentChatStore("society").getState().loadCatalog();
+ expect(calls.some((call) => call.url.includes("provider-health"))).toBe(false);
+ await createAgentChatStore("jarvis").getState().loadCatalog();
+ expect(calls.some((call) => call.url.includes("provider-health"))).toBe(true);
+});
diff --git a/jarvis/ui/web/frontend/src/store/agentChat.ts b/jarvis/ui/web/frontend/src/store/agentChat.ts
index 1a236367b6..aa8d948e2e 100644
--- a/jarvis/ui/web/frontend/src/store/agentChat.ts
+++ b/jarvis/ui/web/frontend/src/store/agentChat.ts
@@ -430,7 +430,9 @@ export function createAgentChatStore(surface: AgentChatSurface) {
// Deliberately not awaited: the sweep makes one real request per
// provider and can take seconds. The composer paints from the
// catalog now and the dots appear when the answers arrive.
- void get().loadHealth();
+ // The society picker has no health dots. Opening its card must not
+ // send model test requests to every configured provider.
+ if (surface !== "society") void get().loadHealth();
// Settle the draft: an empty or unknown provider becomes the active
// sub-agent (else the first connected one); blank picks take the
// provider's defaults.
diff --git a/jarvis/ui/web/frontend/src/views/society/SocietyView.tsx b/jarvis/ui/web/frontend/src/views/society/SocietyView.tsx
index 63f6c34e30..d3db40a367 100644
--- a/jarvis/ui/web/frontend/src/views/society/SocietyView.tsx
+++ b/jarvis/ui/web/frontend/src/views/society/SocietyView.tsx
@@ -20,12 +20,14 @@ import { CreateAgentDialog } from "@/components/society/create/CreateAgentDialog
import type { PlaceId } from "@/components/society/world/islandLayout";
import { useSocietyRoster } from "@/components/society/data";
import { RosterRail } from "@/components/society/roster/RosterRail";
+import { useModelMenuData } from "@/components/society/chat/useModelMenuData";
const JarvisAgentsBoard = lazy(() =>
import("@/views/JarvisAgentsView").then((m) => ({ default: m.JarvisAgentsView })),
);
export function SocietyView() {
+ useModelMenuData();
const t = useT();
const roster = useSocietyRoster();
const agents = useMemo(() => roster.data?.agents ?? [], [roster.data]);