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
feat(society): add searchable subscription model menu
rubenluetke10-beepbc164194b0ff
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 3a4cdce3eb..3e0058cee0 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,5 +1,5 @@import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { 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";@@ -18,6 +18,10 @@ const provider = (id: string, overrides: Partial<AgentChatProvider> = {}): Agentlet row: SocietyAgentRow;let posts: Record<string, string>[];let failSave: boolean;+let extraProviders: AgentChatProvider[];+let liveModels: Record<string, { id: string; label: string }[]>;+let providerRows: unknown[];+let catalogCalls: number;let saving: ReturnType<typeof vi.fn>;beforeEach(async () => {@@ -28,6 +32,7 @@ beforeEach(async () => {avatar: {}, grants: [], focus: [], denies: [], approval_rules: {}, stats: { runs: 3, total_cost_usd: 1, last_active_ms: null },} as unknown as SocietyAgentRow;posts = []; failSave = false; saving = vi.fn();+ extraProviders = []; liveModels = {}; providerRows = []; catalogCalls = 0;vi.stubGlobal("fetch", vi.fn(async (url: string, init?: RequestInit) => {const response = (data: unknown, ok = true) => ({ ok, status: ok ? 200 : 503, json: async () => data }) as Response;if (url.endsWith("/model")) {@@ -37,10 +42,10 @@ beforeEach(async () => {row = { ...row, ...choice };return response({ agent: row, reseated: "society:scout" });}- if (url.includes("/catalog")) return response({ providers: [provider("openai"), provider("gemini"), provider("offline"), provider("ollama", { keyless: true, models_source: "live" })] });+ if (url.includes("/catalog")) { catalogCalls++; return response({ providers: [provider("openai"), provider("gemini"), provider("offline"), provider("ollama", { keyless: true, models_source: "live" }), ...extraProviders] }); }if (url.endsWith("/status")) return response({ mapping: [{ jarvis: "openai", key_set: true }, { jarvis: "gemini", key_set: true }, { jarvis: "offline", key_set: false }] });- if (url.endsWith("/models")) return response({ models: [] });- if (url.endsWith("/providers")) return response({ providers: [] });+ if (url.endsWith("/models")) return response({ models: liveModels[url.split("/").at(-2)!] ?? [] });+ if (url.endsWith("/providers")) return response({ providers: providerRows });if (url.endsWith("/agents")) return response({ agents: [row] });throw new Error(`Unexpected request: ${url}`);}));@@ -60,60 +65,118 @@ function mount(busy = false) {async function open() {fireEvent.click(screen.getByRole("button", { name: "Model" }));- return screen.findByRole("combobox", { name: "Provider" });+ await screen.findByTitle("openai-large");+ return screen.getByRole("textbox", { name: "Search models" });}-test("offers only connected providers and local endpoints with installed models", async () => {- mount();- const pick = await open();- expect(pick.textContent).toContain("openai");- expect(pick.textContent).toContain("gemini");- expect(pick.textContent).not.toContain("offline");- expect(pick.textContent).not.toContain("ollama");+test("groups connected models and hides disconnected or empty local endpoints", async () => {+ mount(); await open();+ expect(screen.getByRole("group", { name: "openai · API key" })).toBeTruthy();+ expect(screen.getByTitle("gemini-small")).toBeTruthy();+ expect(screen.queryByTitle("offline-small")).toBeNull();+ expect(screen.queryByTitle("ollama-small")).toBeNull();+ expect(screen.queryByRole("combobox")).toBeNull();+ expect(screen.queryByRole("button", { name: "Apply model" })).toBeNull();});-test("persists a model change, keeps the account and updates the roster immediately", async () => {+test("clicking a model persists immediately, preserves the account and updates the roster", async () => {mount(); await open();- fireEvent.change(screen.getByRole("combobox", { name: "Model" }), { target: { value: "openai-small" } });- fireEvent.click(screen.getByRole("button", { name: "Apply model" }));+ fireEvent.click(screen.getByTitle("openai-small"));await waitFor(() => expect(screen.getByRole("button", { name: "Model" }).textContent).toContain("openai-small"));expect(posts).toEqual([{ provider: "openai", model: "openai-small", effort: "low", account_id: "saved-seat" }]);expect(row.description).toBe("Keep my instructions");expect(saving.mock.calls.map((call) => call[0])).toEqual([true, false]);await open();- expect((screen.getByRole("combobox", { name: "Model" }) as HTMLSelectElement).value).toBe("openai-small");+ expect(screen.getByTitle("openai-small").getAttribute("aria-checked")).toBe("true");});-test("changing provider resets the subscription account and selects a supported effort", async () => {- mount(); const pick = await open();- fireEvent.change(pick, { target: { value: "gemini" } });- fireEvent.click(screen.getByRole("button", { name: "Apply model" }));+test("changing provider resets the subscription account and uses a supported effort", async () => {+ mount(); await open();+ fireEvent.click(screen.getByTitle("gemini-small"));await waitFor(() => expect(posts).toHaveLength(1));expect(posts[0]).toEqual({ provider: "gemini", model: "gemini-small", effort: "low", account_id: "" });});-test("a failed save keeps the current model and allows retry", async () => {+test("a failed save keeps the current model and permits retry", async () => {failSave = true; mount(); await open();- fireEvent.change(screen.getByRole("combobox", { name: "Model" }), { target: { value: "openai-small" } });- fireEvent.click(screen.getByRole("button", { name: "Apply model" }));+ fireEvent.click(screen.getByTitle("openai-small"));expect((await screen.findByRole("alert")).textContent).toContain("Could not save the model");expect(screen.getByRole("button", { name: "Model" }).textContent).toContain("openai-large");failSave = false;- fireEvent.click(screen.getByRole("button", { name: "Apply model" }));+ fireEvent.click(screen.getByTitle("openai-small"));await waitFor(() => expect(screen.getByRole("button", { name: "Model" }).textContent).toContain("openai-small"));});-test("does not offer a switch during a running response", () => {+test("does not permit a switch during a running response", () => {mount(true);expect((screen.getByRole("button", { name: "Model" }) as HTMLButtonElement).disabled).toBe(true);});-test("Escape discards an unsaved choice without saving", async () => {- mount(); await open();- fireEvent.change(screen.getByRole("combobox", { name: "Model" }), { target: { value: "openai-small" } });- fireEvent.keyDown(screen.getByRole("combobox", { name: "Model" }), { key: "Escape" });- expect(screen.queryByRole("combobox")).toBeNull();+test("search filters by model and provider, and Escape closes without saving", async () => {+ mount(); const input = await open();+ fireEvent.change(input, { target: { value: "gemini small" } });+ expect(screen.getByTitle("gemini-small")).toBeTruthy();+ expect(screen.queryByTitle("gemini-large")).toBeNull();+ expect(screen.queryByTitle("openai-small")).toBeNull();+ fireEvent.keyDown(input, { key: "Escape" });+ expect(screen.queryByRole("menu")).toBeNull();expect(posts).toEqual([]);- await open();- expect((screen.getByRole("combobox", { name: "Model" }) as HTMLSelectElement).value).toBe("openai-large");+});++test("the effort submenu commits the model and chosen effort together", async () => {+ mount(); await open();+ fireEvent.click(within(screen.getByRole("group", { name: "gemini · API key" })).getByRole("button", { name: "Thinking effort: Large" }));+ fireEvent.click(within(screen.getByRole("menu", { name: "Thinking effort" })).getByRole("menuitemradio", { name: "Medium" }));+ await waitFor(() => expect(posts[0]).toEqual({ provider: "gemini", model: "gemini-large", effort: "medium", account_id: "" }));+});++test("OpenCode models are offered without a duplicate app-managed login", async () => {+ extraProviders = [provider("opencode", { runner: "opencode-cli", cli_installed: true,+ curated_models: [{ id: "opencode/free-model", label: "Free model" }] })];+ mount(); await open();+ fireEvent.click(screen.getByTitle("opencode/free-model"));+ await waitFor(() => expect(posts[0].provider).toBe("opencode"));+ expect(posts[0].model).toBe("opencode/free-model");+});++test("all connected subscription accounts are selectable for a model", async () => {+ extraProviders = [provider("openai-codex", { runner: "codex-cli", cli_installed: true })];+ providerRows = [{ id: "openai-codex", subscription: true, accounts: [+ { id: "work", label: "Work", connected: true }, { id: "personal", label: "Personal", connected: true },+ { id: "expired", label: "Expired", connected: false },+ ] }];+ mount(); await open();+ fireEvent.click(screen.getByRole("button", { name: "Account: ChatGPT / Codex subscription" }));+ expect(screen.queryByRole("menuitemradio", { name: "Expired" })).toBeNull();+ fireEvent.click(screen.getByRole("menuitemradio", { name: "Personal" }));+ fireEvent.click(screen.getByTitle("openai-codex-large"));+ await waitFor(() => expect(posts[0].account_id).toBe("personal"));+ expect(posts[0].provider).toBe("openai-codex");+});++test("refresh reloads catalogs and reveals newly available models", async () => {+ mount(); await open();+ extraProviders = [provider("opencode", { runner: "opencode-cli", cli_installed: true })];+ fireEvent.click(screen.getByRole("button", { name: "Refresh models" }));+ await screen.findByTitle("opencode-small");+ expect(catalogCalls).toBe(2);+});++test("local endpoints show only installed models, and search works by model id", async () => {+ liveModels.ollama = [{ id: "qwen3:8b", label: "Qwen 3" }];+ mount(); const input = await open();+ await screen.findByTitle("qwen3:8b");+ fireEvent.change(input, { target: { value: "qwen3:8b" } });+ fireEvent.click(screen.getByTitle("qwen3:8b"));+ await waitFor(() => expect(posts[0].provider).toBe("ollama"));+});++test("keyboard navigation moves through results and closes back to the trigger", async () => {+ mount(); const input = await open();+ fireEvent.keyDown(input, { key: "ArrowDown" });+ expect(document.activeElement).toBe(screen.getByTitle("gemini-small"));+ fireEvent.keyDown(document.activeElement!, { key: "ArrowDown" });+ expect(document.activeElement).toBe(screen.getByTitle("gemini-large"));+ fireEvent.keyDown(document.activeElement!, { key: "Escape" });+ expect(document.activeElement).toBe(screen.getByRole("button", { name: "Model" }));});diff --git a/jarvis/ui/web/frontend/src/components/society/chat/AgentModelPicker.tsx b/jarvis/ui/web/frontend/src/components/society/chat/AgentModelPicker.tsxindex 851f11a41b..17c2239d98 100644--- a/jarvis/ui/web/frontend/src/components/society/chat/AgentModelPicker.tsx+++ b/jarvis/ui/web/frontend/src/components/society/chat/AgentModelPicker.tsx@@ -1,161 +1,227 @@-import { useEffect, useMemo, useRef, useState } from "react";-import { useQuery } from "@tanstack/react-query";-import { ChevronDown } from "lucide-react";-+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 { useT } from "@/i18n";import { fetchAgentChatCatalog, fetchAgentConnections, fetchProviderModels, type CuratedModel } from "@/lib/agentChatApi";import { fetchSocietyProviders } from "@/lib/societyApi";+import { cn } from "@/lib/utils";import { joinProviderOptions } from "@/store/agentChat";-import { brainSeats, effortsFor, modelsFor, type BrainSeat } from "../create/brainPicker";+import { effortsFor, type BrainSeat } from "../create/brainPicker";import { useUpdateAgentModel, type SocietyAgent } from "../data";+import { matchesModel, modelEffort, modelSeats, providerTitle } from "./modelChoices";-const selectClass = "mt-1 w-full min-w-0 rounded-md border border-border bg-background px-2 py-1.5 text-xs text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring";--async function modelLists(ids: string[]): Promise<Record<string, CuratedModel[]>> {- return Object.fromEntries(await Promise.all(ids.map(async (id) => {- // An unavailable local endpoint cannot offer an installed model.- const models = await fetchProviderModels(id).catch(() => []);- return [id, models.map((m) => ({ id: m.id, label: m.label ?? m.name ?? m.id }))];- })));-}+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";-/** A per-agent choice: the roster and its chat move together through the model route. */+/** A searchable provider catalog, with account and effort submenus. */export function AgentModelPicker({ agent, busy, onSavingChange }: {- agent: SocietyAgent;- busy: boolean;- onSavingChange: (saving: boolean) => void;+ agent: SocietyAgent; busy: boolean; onSavingChange: (saving: boolean) => void;}) {const t = useT();const update = useUpdateAgentModel();+ const menuId = useId();const [open, setOpen] = useState(false);- const [providerId, setProviderId] = useState(agent.provider);- const [model, setModel] = useState(agent.model);- const [effort, setEffort] = useState(agent.effort);- const [accountId, setAccountId] = useState(agent.accountId ?? "");+ const [search, setSearch] = useState("");const [saving, setSaving] = useState(false);const [error, setError] = useState<string | null>(null);- const root = useRef<HTMLDivElement>(null);+ const [accounts, setAccounts] = useState<Record<string, string>>({});+ const [submenu, setSubmenu] = useState<Submenu | null>(null);+ const [position, setPosition] = useState<CSSProperties>({});const trigger = useRef<HTMLButtonElement>(null);+ const panel = useRef<HTMLDivElement>(null);+ const sidePanel = useRef<HTMLDivElement>(null);+ 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 keylessIds = useMemo(() => (catalog.data?.providers ?? []).filter((p) => p.keyless && p.models_source === "live").map((p) => p.id), [catalog.data]);- const localModels = useQuery({ queryKey: ["agent-chat", "live-models", "keyless", keylessIds], queryFn: () => modelLists(keylessIds), enabled: open && catalog.isSuccess, staleTime: 60_000 });- const chosenProvider = catalog.data?.providers.find((p) => p.id === providerId);- const pickedModels = useQuery({ queryKey: ["agent-chat", "live-models", providerId], queryFn: () => modelLists([providerId]), enabled: open && chosenProvider?.models_source === "live" && !chosenProvider.keyless, staleTime: 60_000 });- const seats = useMemo(() => brainSeats(- joinProviderOptions(catalog.data?.providers ?? [], connections.data ?? []),- providers.data ?? [],- { ...localModels.data, ...pickedModels.data },- new Set(connections.data?.map((c) => c.jarvis)),- ), [catalog.data, connections.data, providers.data, localModels.data, pickedModels.data]);- const seat = seats.find((s) => s.provider.id === providerId) ?? null;- const models = modelsFor(seat);- const efforts = effortsFor(seat, model);- const validEffort = efforts.includes(effort) ? effort : efforts.includes(seat?.provider.default_effort ?? "") ? seat!.provider.default_effort : efforts[0] ?? "";- const loading = catalog.isLoading || connections.isLoading || providers.isLoading || localModels.isLoading;+ const options = useMemo(() => joinProviderOptions(catalog.data?.providers ?? [], connections.data ?? []), [catalog.data, connections.data]);+ 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,+ })) });+ 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;+ const refreshing = catalog.isFetching || connections.isFetching || providers.isFetching || liveQueries.some((query) => query.isFetching);const failed = catalog.isError || connections.isError || providers.isError;- const modelValid = Boolean(model.trim()) && (!models.length || models.some((m) => m.id === model));+ 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) => {+ const order = { subscription: 0, api: 1, local: 2 };+ return order[a.seat.kind] - order[b.seat.kind] || a.title.localeCompare(b.title);+ });+ const sideSeat = seats.find((seat) => seat.provider.id === submenu?.provider);++ function close() {+ if (inFlight.current) return;+ setOpen(false); setSubmenu(null); trigger.current?.focus();+ }++ useLayoutEffect(() => {+ if (!open) return;+ let frame = 0;+ const place = () => {+ const rect = trigger.current?.getBoundingClientRect();+ if (!rect) return;+ const above = rect.top > window.innerHeight - rect.bottom;+ const width = Math.min(320, window.innerWidth - 16);+ const next: CSSProperties = { position: "fixed", width, left: Math.max(8, Math.min(rect.left, window.innerWidth - width - 8)),+ maxHeight: Math.min(560, Math.max(120, (above ? rect.top : window.innerHeight - rect.bottom) - 16)),+ ...(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);+ };+ place(); input.current?.focus();+ return () => cancelAnimationFrame(frame);+ }, [open]);++ useEffect(() => {+ if (submenu) sidePanel.current?.querySelector<HTMLButtonElement>("button[data-menu-choice]")?.focus();+ }, [submenu]);useEffect(() => {if (!open) return;const outside = (event: PointerEvent) => {- if (!root.current?.contains(event.target as Node) && !inFlight.current) setOpen(false);+ const node = event.target as Node;+ if (!trigger.current?.contains(node) && !panel.current?.contains(node) && !sidePanel.current?.contains(node) && !inFlight.current) {+ setOpen(false); setSubmenu(null);+ }};document.addEventListener("pointerdown", outside);return () => document.removeEventListener("pointerdown", outside);}, [open]);- function pickProvider(next: BrainSeat | undefined) {- if (!next) return;- setProviderId(next.provider.id);- const options = modelsFor(next);- setModel(options.find((m) => m.id === next.provider.default_model)?.id ?? options[0]?.id ?? next.provider.default_model);- setEffort(next.provider.default_effort);- setAccountId("");- }-- async function save() {- if (!seat || !modelValid || busy || inFlight.current) return;- inFlight.current = true;- setSaving(true);- onSavingChange(true);- setError(null);+ async function save(seat: BrainSeat, model: CuratedModel, effort = preferredEffort(seat, model)) {+ if (busy || inFlight.current) return;+ inFlight.current = true; setSaving(true); onSavingChange(true); setError(null);try {- await update(agent.agentId, { provider: providerId, model: model.trim(), effort: validEffort, account_id: accountId });- setOpen(false);- trigger.current?.focus();+ await update(agent.agentId, { provider: seat.provider.id, model: model.id, effort, account_id: currentAccount(seat) });+ setOpen(false); setSubmenu(null); trigger.current?.focus();} catch (err) {setError(`${t("society.chat.model_save_failed")} (${err instanceof Error ? err.message : String(err)})`);} finally {- inFlight.current = false;- setSaving(false);- onSavingChange(false);+ inFlight.current = false; setSaving(false); onSavingChange(false);}}- return <div ref={root} className="relative w-fit max-w-full" onKeyDown={(event) => {- if (open && event.key === "Escape") {- event.preventDefault();- event.stopPropagation();- if (!saving) { setOpen(false); trigger.current?.focus(); }+ async function refresh() {+ setSubmenu(null);+ await Promise.all([catalog.refetch(), connections.refetch(), providers.refetch(), ...liveQueries.map((query) => query.refetch())]);+ }++ function moveFocus(event: KeyboardEvent, container: HTMLElement | null) {+ if (event.key === "Escape" || (event.key === "ArrowLeft" && submenu)) {+ event.preventDefault(); event.stopPropagation();+ if (submenu) { setSubmenu(null); input.current?.focus(); } else close();+ return;}- }}>- <button ref={trigger} type="button" aria-label={t("society.chat.model")} aria-expanded={open}+ if (!["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) return;+ if (event.target === input.current && ["Home", "End"].includes(event.key)) return;+ const buttons = Array.from(container?.querySelectorAll<HTMLButtonElement>("button[data-menu-choice]:not(:disabled)") ?? []);+ if (!buttons.length) return;+ event.preventDefault(); event.stopPropagation();+ const current = buttons.indexOf(document.activeElement as HTMLButtonElement);+ const index = event.key === "Home" ? 0 : event.key === "End" || (current === -1 && event.key === "ArrowUp") ? buttons.length - 1+ : (current + (event.key === "ArrowUp" ? -1 : 1) + buttons.length) % buttons.length;+ buttons[index].focus(); buttons[index].scrollIntoView?.({ block: "nearest" });+ }++ const host = trigger.current?.closest<HTMLElement>('[role="dialog"]') ?? document.body;+ const sideStyle: CSSProperties = submenu ? { position: "fixed", width: 210,+ left: Math.max(8, submenu.anchor.right + 210 < window.innerWidth - 8 ? submenu.anchor.right + 4 : submenu.anchor.left - 214),+ top: Math.max(8, Math.min(submenu.anchor.top, window.innerHeight - 300)), maxHeight: Math.min(290, window.innerHeight - 16),+ } : {};++ return <>+ <button ref={trigger} type="button" aria-label={t("society.chat.model")} aria-haspopup="menu" aria-expanded={open} aria-controls={open ? menuId : undefined}disabled={busy || saving} title={busy ? t("society.chat.model_busy") : t("society.chat.model")}- onClick={() => {- if (!open) { setProviderId(agent.provider); setModel(agent.model); setEffort(agent.effort); setAccountId(agent.accountId ?? ""); setError(null); }- setOpen(!open);- }} className="flex max-w-full items-center gap-1.5 rounded-full px-2 py-1 text-xs text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50">+ onClick={() => { if (open) close(); else { setSearch(""); setAccounts({}); setError(null); setOpen(true); } }}+ className="flex max-w-full items-center gap-1.5 rounded-full px-2 py-1 text-xs text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50">{agent.provider ? <ProviderLogo providerId={agent.provider} label={agent.providerLabel} size="sm" /> : null}<span className="truncate">{agent.model || agent.providerLabel || t("society.chat.model_default")}</span>- {agent.effort ? <span className="shrink-0 opacity-70">{agent.effort}</span> : null}+ {agent.effort ? <span className="shrink-0 opacity-70">{effortLabel(agent.effort, t)}</span> : null}<ChevronDown className="h-3 w-3 shrink-0" aria-hidden /></button>- {open ? <div role="group" aria-label={t("society.chat.model")} className="absolute bottom-full left-0 z-30 mb-2 w-80 max-w-[calc(100vw-4rem)] rounded-lg border border-border bg-popover p-3 text-popover-foreground shadow-float">- <p className="mb-3 text-xs text-muted-foreground">{t("society.chat.model_scope")}</p>- {loading ? <p role="status" className="text-xs">{t("society.create.catalog_loading")}</p> : failed ? <p role="alert" className="text-xs text-destructive">{t("society.chat.model_load_failed")}</p> : <>- <fieldset disabled={saving || busy} className="space-y-3">- <label className="block text-xs">{t("society.chat.model_provider")}- <select aria-label={t("society.chat.model_provider")} className={selectClass} value={providerId} onChange={(e) => pickProvider(seats.find((s) => s.provider.id === e.target.value))}>- {!seat ? <option value={providerId}>{t("society.chat.model_choose_provider")}</option> : null}- {(["subscription", "api", "local"] as const).map((kind) => <optgroup key={kind} label={t(`society.create.kind_${kind}`)}>- {seats.filter((s) => s.kind === kind).map((s) => <option key={s.provider.id} value={s.provider.id}>{s.provider.label}</option>)}- </optgroup>)}- </select>- </label>- {seat ? <>- <label className="block text-xs">{t("society.create.model")}- {models.length ? <select aria-label={t("society.create.model")} className={selectClass} value={model} onChange={(e) => setModel(e.target.value)}>- {!models.some((m) => m.id === model) ? <option value={model} disabled>{model || t("society.create.model")}</option> : null}- {models.map((m) => <option key={m.id} value={m.id}>{m.label}</option>)}- </select> : <input aria-label={t("society.create.model")} className={selectClass} value={model} onChange={(e) => setModel(e.target.value)} />}- </label>- {efforts.length ? <label className="block text-xs">{t("society.create.effort")}- <select aria-label={t("society.create.effort")} className={selectClass} value={validEffort} onChange={(e) => setEffort(e.target.value)}>- {efforts.map((level) => <option key={level} value={level}>{effortLabel(level, t)}</option>)}- </select>- </label> : null}- {seat.accounts.length > 1 || accountId ? <label className="block text-xs">{t("society.chat.model_account")}- <select aria-label={t("society.chat.model_account")} className={selectClass} value={accountId} onChange={(e) => setAccountId(e.target.value)}>- <option value="">{t("society.chat.model_active_account")}</option>- {accountId && !seat.accounts.some((a) => a.id === accountId) ? <option value={accountId}>{accountId}</option> : null}- {seat.accounts.map((a) => <option key={a.id} value={a.id}>{a.label}</option>)}- </select>- </label> : null}- </> : null}- </fieldset>- <p className="mt-3 text-xs text-muted-foreground">{t("society.chat.model_connections")}</p>- {error ? <p role="alert" className="mt-2 text-xs text-destructive">{error}</p> : null}- <button type="button" disabled={busy || saving || !seat || !modelValid || pickedModels.isFetching}- onClick={() => void save()} className="mt-3 w-full rounded-md bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground disabled:opacity-50">- {t(saving ? "society.chat.model_saving" : "society.chat.model_apply")}- </button>- </>}- </div> : null}- </div>;+ {open ? createPortal(<>+ <div ref={panel} id={menuId} style={position} className="z-[80] flex flex-col overflow-hidden rounded-md border border-border bg-popover text-popover-foreground shadow-float"+ onKeyDown={(event) => moveFocus(event, panel.current)}>+ <div className="flex shrink-0 items-center gap-2 border-b border-border px-3 py-2.5">+ <Search className="h-3.5 w-3.5 text-muted-foreground" aria-hidden />+ <input ref={input} aria-label={t("society.chat.model_search")} placeholder={t("society.chat.model_search")}+ value={search} onChange={(event) => { setSearch(event.target.value); setSubmenu(null); }}+ className="min-w-0 flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground" />+ {refreshing ? <Loader2 className="h-3.5 w-3.5 animate-spin text-muted-foreground" aria-label={t("society.chat.models_loading")} /> : null}+ </div>+ <div role="menu" aria-label={t("society.chat.model")} aria-busy={saving} className="min-h-0 overflow-y-auto overscroll-contain py-1" onScroll={() => setSubmenu(null)}>+ {loading ? <p role="status" className="px-3 py-3 text-xs text-muted-foreground">{t("society.create.catalog_loading")}</p> : null}+ {failed ? <p role="alert" className="px-3 py-3 text-xs text-destructive">{t("society.chat.model_load_failed")}</p> : null}+ {!loading && !failed && groups.length === 0 ? <p className="px-3 py-3 text-xs text-muted-foreground">{t(refreshing ? "society.chat.models_loading" : "society.chat.model_no_matches")}</p> : null}+ {!loading && !failed ? groups.map(({ seat, title, models }) => <div key={seat.provider.id} role="group" aria-label={title}>+ <div className="sticky top-0 z-10 flex items-center gap-1 bg-popover px-3 pb-1 pt-3">+ <span className="min-w-0 flex-1 truncate text-[11px] font-semibold uppercase tracking-wide text-muted-foreground" title={title}>{title}</span>+ {seat.accounts.length ? <button type="button" disabled={busy || saving} data-menu-choice+ aria-label={`${t("society.chat.model_account")}: ${title}`} aria-haspopup="menu" aria-expanded={submenu?.provider === seat.provider.id && !submenu.model}+ onClick={(event) => setSubmenu({ provider: seat.provider.id, anchor: event.currentTarget.getBoundingClientRect() })}+ className="flex max-w-[140px] items-center gap-1 rounded px-1 py-0.5 text-[10px] text-muted-foreground hover:bg-secondary focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring">+ <Users className="h-3 w-3 shrink-0" aria-hidden /><span className="truncate">{seat.accounts.find((account) => account.id === currentAccount(seat))?.label ?? t("society.chat.model_active_account")}</span><ChevronDown className="h-2.5 w-2.5 shrink-0" aria-hidden />+ </button> : null}+ </div>+ {models.map((model) => {+ const selected = agent.provider === seat.provider.id && agent.model === model.id && (agent.accountId ?? "") === currentAccount(seat);+ const effort = preferredEffort(seat, model);+ return <div key={model.id} className={cn("group flex items-center", selected && "bg-secondary/70")}>+ <button type="button" role="menuitemradio" aria-checked={selected} disabled={busy || saving} data-menu-choice+ onKeyDown={(event) => {+ if (event.key === "ArrowRight" && effortsFor(seat, model.id).length) {+ event.preventDefault(); event.stopPropagation();+ setSubmenu({ provider: seat.provider.id, model, anchor: event.currentTarget.getBoundingClientRect() });+ }+ }}+ onClick={() => void save(seat, model)} className={cn(menuRow, "min-w-0 flex-1")} title={model.id}>+ <span className="min-w-0 truncate">{model.label || model.id}<span className="ml-1 text-muted-foreground">{effort ? effortLabel(effort, t) : ""}</span></span>+ {selected ? <Check className="ml-auto h-3.5 w-3.5 shrink-0" aria-hidden /> : null}+ </button>+ {effortsFor(seat, model.id).length ? <button type="button" disabled={busy || saving} aria-label={`${t("society.chat.effort")}: ${model.label}`} aria-haspopup="menu"+ onClick={(event) => setSubmenu({ provider: seat.provider.id, model, anchor: event.currentTarget.getBoundingClientRect() })}+ className="mr-1 rounded p-1.5 text-muted-foreground opacity-60 hover:bg-secondary hover:opacity-100 focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring">+ <ChevronRight className="h-3 w-3" aria-hidden />+ </button> : null}+ </div>;+ })}+ </div>) : null}+ </div>+ {error ? <p role="alert" className="shrink-0 border-t border-border px-3 py-2 text-xs text-destructive">{error}</p> : null}+ <div className="shrink-0 border-t border-border py-1">+ <button type="button" onClick={() => void refresh()} disabled={refreshing || saving} className={cn(menuRow, "text-muted-foreground")}>+ <RefreshCw className={cn("h-3.5 w-3.5", refreshing && "animate-spin")} aria-hidden />{t("society.chat.model_refresh")}+ </button>+ </div>+ </div>+ {submenu && sideSeat ? <div ref={sidePanel} style={sideStyle} role="menu" aria-label={t(submenu.model ? "society.chat.effort" : "society.chat.model_account")}+ className="z-[81] overflow-y-auto rounded-md border border-border bg-popover py-1 shadow-float" onKeyDown={(event) => moveFocus(event, sidePanel.current)}>+ <p className="px-3 py-2 text-[11px] font-semibold uppercase text-muted-foreground">{submenu.model ? t("society.chat.effort") : t("society.chat.model_account")}</p>+ {submenu.model ? effortsFor(sideSeat, submenu.model.id).map((effort) => <button key={effort} type="button" role="menuitemradio" data-menu-choice+ aria-checked={effort === preferredEffort(sideSeat, submenu.model!)} disabled={busy || saving}+ onClick={() => void save(sideSeat, submenu.model!, effort)} className={menuRow}>+ {effortLabel(effort, t)}{effort === preferredEffort(sideSeat, submenu.model!) ? <Check className="ml-auto h-3.5 w-3.5" aria-hidden /> : null}+ </button>) : [{ id: "", label: t("society.chat.model_active_account") }, ...sideSeat.accounts].map((account) => <button key={account.id} type="button" role="menuitemradio" data-menu-choice+ aria-checked={account.id === currentAccount(sideSeat)} disabled={busy || saving}+ onClick={() => { setAccounts((previous) => ({ ...previous, [sideSeat.provider.id]: account.id })); setSubmenu(null); input.current?.focus(); }} className={menuRow}>+ <span className="truncate">{account.label}</span>{account.id === currentAccount(sideSeat) ? <Check className="ml-auto h-3.5 w-3.5" aria-hidden /> : null}+ </button>)}+ </div> : null}+ </>, host) : null}+ </>;}diff --git a/jarvis/ui/web/frontend/src/components/society/chat/modelChoices.test.ts b/jarvis/ui/web/frontend/src/components/society/chat/modelChoices.test.tsnew file mode 100644index 0000000000..1efed6fbf6--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/chat/modelChoices.test.ts@@ -0,0 +1,34 @@+import { expect, test } from "vitest";+import type { ProviderOption } from "@/store/agentChat";+import type { SocietyProviderRow } from "@/lib/societyApi";+import { modelEffort, modelSeats } from "./modelChoices";++const option = (overrides: Partial<ProviderOption> = {}): ProviderOption => ({+ id: "cli", label: "CLI", family: "cli", runner: "grok-cli", connected: false,+ cli_installed: true, keyless: false, active: false, models_source: "curated", native_resume: true,+ curated_models: [{ id: "small", label: "Small", efforts: ["low"] }], default_model: "small",+ effort_levels: ["low", "high"], default_effort: "high", permission_modes: [], default_permission_mode: "ask",+ ...overrides,+});+const accounts = [{ id: "cli", subscription: true, accounts: [+ { id: "signed-in", label: "Work", connected: true }, { id: "expired", label: "Old", connected: false },+] }] as SocietyProviderRow[];++test("a signed-in subscription seat wins over a stale summary credential flag", () => {+ const seats = modelSeats([option()], accounts, {});+ expect(seats).toHaveLength(1);+ expect(seats[0].accounts.map((account) => account.id)).toEqual(["signed-in"]);+});++test("a subscription account cannot authorize an API provider or a missing CLI", () => {+ expect(modelSeats([option({ cli_installed: false })], accounts, {})).toEqual([]);+ expect(modelSeats([option({ runner: "brain", cli_installed: null })], accounts, {})).toEqual([]);+});++test("live labels retain model-specific effort metadata and duplicate ids collapse", () => {+ const [seat] = modelSeats([option({ connected: true })], [], { cli: [+ { id: "small", label: "Small live" }, { id: "small", label: "Small live" },+ ] });+ expect(seat.provider.curated_models).toHaveLength(1);+ expect(modelEffort(seat, "small", "high")).toBe("low");+});diff --git a/jarvis/ui/web/frontend/src/components/society/chat/modelChoices.ts b/jarvis/ui/web/frontend/src/components/society/chat/modelChoices.tsnew file mode 100644index 0000000000..740ebfaee9--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/chat/modelChoices.ts@@ -0,0 +1,47 @@+import type { CuratedModel } from "@/lib/agentChatApi";+import type { SocietyProviderRow } from "@/lib/societyApi";+import type { ProviderOption } from "@/store/agentChat";+import { brainSeats, effortsFor, type BrainSeat } from "../create/brainPicker";++/** CLI-owned credentials need no duplicate account entry in the app. */+export function modelSeats(options: ProviderOption[], providers: SocietyProviderRow[], live: Record<string, CuratedModel[]>): BrainSeat[] {+ const usable = options.map((option) => ({ ...option,+ connected: option.connected || (option.cli_installed === true && providers.some((row) => row.id === option.id && row.subscription && row.accounts.some((account) => account.connected))),+ }));+ const mergedLive = Object.fromEntries(Object.entries(live).map(([id, models]) => {+ const metadata = new Map(options.find((option) => option.id === id)?.curated_models.map((model) => [model.id, model]));+ return [id, models.map((model) => ({ ...metadata.get(model.id), ...model }))];+ }));+ // The shared join rejects a known disconnected CLI and missing binaries.+ // Installed CLIs without an account reader (such as OpenCode) own their login.+ const known = new Set(usable.filter((option) => option.connected).map((option) => option.id));+ return brainSeats(usable, providers, mergedLive, known).map((seat) => ({ ...seat, provider: { ...seat.provider,+ curated_models: [...new Map(seat.provider.curated_models.map((model) => [model.id, model])).values()],+ } }));+}++/** Display names only; availability and routing always come from the catalog. */+export function providerTitle(seat: BrainSeat, t: (key: string) => string): string {+ const names: Record<string, string> = {+ "claude-cli": "model_group_anthropic", "codex-cli": "model_group_chatgpt",+ "grok-cli": "model_group_grok", "agy-cli": "model_group_google",+ };+ if (seat.kind === "subscription") {+ const key = names[seat.provider.runner];+ return key ? t(`society.chat.${key}`) : seat.provider.label;+ }+ return `${seat.provider.label} · ${t(`society.create.kind_${seat.kind}`)}`;+}++export function modelEffort(seat: BrainSeat, model: string, preferred: string): string {+ const levels = effortsFor(seat, model);+ return levels.includes(preferred) ? preferred+ : levels.includes(seat.provider.default_effort) ? seat.provider.default_effort : levels[0] ?? "";+}++export function matchesModel(seat: BrainSeat, model: CuratedModel, query: string, title: string): boolean {+ 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(" "));+ return fold(query).trim().split(/\s+/).every((word) => haystack.includes(word));+}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json b/jarvis/ui/web/frontend/src/i18n/locales/society/de.jsonindex 765d7f3f09..31119c135d 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/de.json@@ -1,6 +1,13 @@{"society": {"chat": {+ "model_search": "Modelle suchen",+ "model_refresh": "Modelle aktualisieren",+ "model_no_matches": "Keine passenden Modelle. Verbinde einen Provider oder aktualisiere die Liste.",+ "model_group_anthropic": "Anthropic-Subscription",+ "model_group_chatgpt": "ChatGPT- / Codex-Subscription",+ "model_group_grok": "Grok-Subscription",+ "model_group_google": "Google- / Gemini-Subscription","model_scope": "Gilt für die nächsten Nachrichten und Routinen dieses Agenten. Der Chatverlauf bleibt erhalten.","model_busy": "Warte auf die laufende Antwort, bevor du das Modell wechselst.","model_save_failed": "Das Modell konnte nicht gespeichert werden",@@ -234,6 +241,25 @@"place_gardens": "Gärten","place_solar": "Solarfeld","place_mine": "Die Mine"+ },+ "hooks": {+ "webhook": "Webhook",+ "event_hook": "Integrations-Ereignis",+ "connect": "Webhook verbinden",+ "endpoint": "Webhook-URL",+ "token": "Zugangsschlüssel",+ "copy": "Schlüssel kopieren",+ "copied": "Kopiert",+ "rotate": "Schlüssel erneuern",+ "rotate_confirm": "Schlüssel ersetzen? Bestehende Integrationen benötigen danach den neuen Schlüssel.",+ "remote": "Externe Dienste benötigen eine erreichbare HTTPS-Adresse dieser Jarvis-Instanz.",+ "auth": "JSON mit Authorization: Bearer <token> senden. Bei Wiederholungen denselben Idempotency-Key verwenden.",+ "conditions": "Payload-Filter (JSON-Feldvergleich)",+ "event_name": "Ereignisname, z. B. crm.customer.created",+ "loading": "Verbindung wird geladen…",+ "configured": "Verbindung bereit",+ "source": "Die Ereignisquelle muss aktiv sein.",+ "filter_hint": "Beispiel: {\"data.status\": \"ready\"}. Mit {} wird jede Payload angenommen."}}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json b/jarvis/ui/web/frontend/src/i18n/locales/society/en.jsonindex e842503b2b..be8e7d8757 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/en.json@@ -1,6 +1,13 @@{"society": {"chat": {+ "model_search": "Search models",+ "model_refresh": "Refresh models",+ "model_no_matches": "No matching models. Connect a provider or refresh the list.",+ "model_group_anthropic": "Anthropic subscription",+ "model_group_chatgpt": "ChatGPT / Codex subscription",+ "model_group_grok": "Grok subscription",+ "model_group_google": "Google / Gemini subscription","model_scope": "Applies to this agent's next messages and routine runs. Chat history stays.","model_busy": "Wait for the current response before changing models.","model_save_failed": "Could not save the model",@@ -234,6 +241,25 @@"place_gardens": "Gardens","place_solar": "Solar Field","place_mine": "The Mine"+ },+ "hooks": {+ "webhook": "Webhook",+ "event_hook": "Integration event",+ "connect": "Connect webhook",+ "endpoint": "Webhook URL",+ "token": "Access token",+ "copy": "Copy token",+ "copied": "Copied",+ "rotate": "Rotate token",+ "rotate_confirm": "Replace the token? Existing integrations will need the new token.",+ "remote": "External services need a reachable HTTPS address for this Jarvis instance.",+ "auth": "Send JSON with Authorization: Bearer <token>. Reuse Idempotency-Key when retrying.",+ "conditions": "Payload filters (JSON field equality)",+ "event_name": "Event name, e.g. crm.customer.created",+ "loading": "Loading connection…",+ "configured": "Connection ready",+ "source": "Event source must be active.",+ "filter_hint": "Example: {\"data.status\": \"ready\"}. Leave {} to accept every payload."}}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json b/jarvis/ui/web/frontend/src/i18n/locales/society/es.jsonindex 27cf384a87..552bc7d261 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/es.json@@ -1,6 +1,13 @@{"society": {"chat": {+ "model_search": "Buscar modelos",+ "model_refresh": "Actualizar modelos",+ "model_no_matches": "No hay modelos coincidentes. Conecta un proveedor o actualiza la lista.",+ "model_group_anthropic": "Suscripción de Anthropic",+ "model_group_chatgpt": "Suscripción de ChatGPT / Codex",+ "model_group_grok": "Suscripción de Grok",+ "model_group_google": "Suscripción de Google / Gemini","model_scope": "Se aplica a los próximos mensajes y rutinas de este agente. Se conserva el historial.","model_busy": "Espera a que termine la respuesta antes de cambiar el modelo.","model_save_failed": "No se pudo guardar el modelo",@@ -234,6 +241,25 @@"place_gardens": "Jardines","place_solar": "Campo Solar","place_mine": "La Mina"+ },+ "hooks": {+ "webhook": "Webhook",+ "event_hook": "Evento de integración",+ "connect": "Conectar webhook",+ "endpoint": "URL del webhook",+ "token": "Token de acceso",+ "copy": "Copiar token",+ "copied": "Copiado",+ "rotate": "Renovar token",+ "rotate_confirm": "¿Reemplazar el token? Las integraciones existentes necesitarán el nuevo token.",+ "remote": "Los servicios externos necesitan una dirección HTTPS accesible de esta instancia de Jarvis.",+ "auth": "Envía JSON con Authorization: Bearer <token>. Reutiliza Idempotency-Key al reintentar.",+ "conditions": "Filtros de datos (igualdad de campos JSON)",+ "event_name": "Nombre del evento, p. ej. crm.customer.created",+ "loading": "Cargando conexión…",+ "configured": "Conexión lista",+ "source": "La fuente del evento debe estar activa.",+ "filter_hint": "Ejemplo: {\"data.status\": \"ready\"}. Usa {} para aceptar cualquier contenido."}}}