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(ultrawiki): pick slot models from a list, not a text box
Ruben Lütkeee34817f0770
diff --git a/jarvis/ui/web/frontend/src/components/BrainModelSelector.tsx b/jarvis/ui/web/frontend/src/components/BrainModelSelector.tsxindex f4bb9af714..013b7ff93c 100644--- a/jarvis/ui/web/frontend/src/components/BrainModelSelector.tsx+++ b/jarvis/ui/web/frontend/src/components/BrainModelSelector.tsx@@ -16,6 +16,7 @@ import {type BrainModel,type BrainModelProbe,type BrainModelSaveResult,+ type BrainModelsResult,type ProviderTestStatus,} from "@/hooks/useProviders";import { useEventStore } from "@/store/events";@@ -111,6 +112,7 @@ export function BrainModelSelector({placeholder,controlled,visionOnly,+ loadModels,}: {providerId: string;currentModel?: string;@@ -161,6 +163,14 @@ export function BrainModelSelector({* default — the main brain picker shows everything.*/visionOnly?: boolean;+ /**+ * Override where the list comes from. The UltraWiki capability slots pass+ * their own fetcher (`GET /api/ultrawiki/models/{slot}`) so they get THIS+ * picker — searchable, refreshable, with the custom-id escape hatch — rather+ * than a look-alike that would drift from it. Defaults to the per-provider+ * brain catalog, so every existing call site is unchanged.+ */+ loadModels?: (refresh: boolean) => Promise<BrainModelsResult>;}) {const t = useT();const pushToast = useEventStore((s) => s.pushToast);@@ -170,6 +180,10 @@ export function BrainModelSelector({const [filter, setFilter] = useState<ModelFilter>("all");const [models, setModels] = useState<BrainModel[]>([]);const [source, setSource] = useState<"live" | "cache" | "static" | "curated" | null>(null);+ // Why the list is the fallback one ("no Gemini API key saved yet") — shown+ // verbatim, because "these five are all there is" and "we couldn't ask" look+ // identical in a dropdown and mean very different things.+ const [sourceNote, setSourceNote] = useState("");const [selects, setSelects] = useState<"model" | "voice">("model");const [loading, setLoading] = useState(false);const [saving, setSaving] = useState(false);@@ -179,9 +193,12 @@ export function BrainModelSelector({async function load(refresh = false) {setLoading(true);try {- const res = await getBrainProviderModels(providerId, refresh);+ const res = loadModels+ ? await loadModels(refresh)+ : await getBrainProviderModels(providerId, refresh);setModels(Array.isArray(res.models) ? res.models : []);setSource(res.source);+ setSourceNote(typeof res.reason === "string" ? res.reason : "");setSelects(res.selects === "voice" ? "voice" : "model");// Uncontrolled: adopt the catalog's current selection as the pinned value.// Controlled (CU picker): the parent owns the pinned value (cu_model) —@@ -565,6 +582,9 @@ export function BrainModelSelector({{t("apikeys_model.source_static")}</span>)}+ {sourceNote && (+ <span className="text-[11px] text-muted-foreground">{sourceNote}</span>+ )}{probe && <ProbeChip probe={probe} />}</div></div>diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/SlotsPanel.test.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/SlotsPanel.test.tsxindex 9f2e22cab7..9028e04c76 100644--- a/jarvis/ui/web/frontend/src/components/ultrawiki/SlotsPanel.test.tsx+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/SlotsPanel.test.tsx@@ -190,6 +190,25 @@ function installFetchMock(overrides: Record<string, () => Response> = {}) {json: async () => CATALOG,} as Response;}+ if (url.startsWith("/api/ultrawiki/models/")) {+ return {+ ok: true,+ status: 200,+ statusText: "OK",+ json: async () => ({+ provider: "ollama",+ current_model: "bge-m3",+ models: [+ { id: "bge-m3", label: "bge-m3 — multilingual" },+ { id: "nomic-embed-text", label: "nomic-embed-text" },+ ],+ source: "live",+ fetched_at: 0,+ selects: "model",+ reason: "",+ }),+ } as Response;+ }if (url.startsWith("/api/ultrawiki/settings")) {putBodies.push(JSON.parse(String(init?.body ?? "{}")));return {@@ -290,6 +309,30 @@ describe("SlotsPanel", () => {expect(links.length).toBeGreaterThan(0);});+ it("picks the model from a list instead of asking the user to type it", async () => {+ // A free-text model box is how "gemini-embedding-01" becomes a 404 on the+ // first real embed and a silently paused pipeline. The slot uses the same+ // searchable picker as every other provider surface in the app.+ renderWithClient(<SlotsPanel status={STATUS} onChanged={() => {}} />);+ fireEvent.click(await screen.findByRole("button", { name: "Model" }));+ // The provider's own catalog, not a hardcoded guess. The id shows twice+ // per row (label + monospace id column), so match all of them.+ expect((await screen.findAllByText("nomic-embed-text")).length).toBeGreaterThan(0);+ expect(screen.getAllByText(/bge-m3/).length).toBeGreaterThan(0);+ });++ it("saves the model straight from the list, with no separate Save step", async () => {+ renderWithClient(<SlotsPanel status={STATUS} onChanged={() => {}} />);+ fireEvent.click(await screen.findByRole("button", { name: /model/i }));+ const row = (await screen.findAllByText("nomic-embed-text"))[0];+ fireEvent.click(row.closest("button") as HTMLElement);+ await waitFor(() => expect(putBodies).toHaveLength(1));+ expect(putBodies[0]).toEqual({+ embedding_provider: "ollama",+ embedding_model: "nomic-embed-text",+ });+ });+it("treats automatic distillation and rerank-off as real choices", async () => {renderWithClient(<SlotsPanel status={STATUS} onChanged={() => {}} />);const auto = await screen.findByTestId("ultrawiki-card-distill-auto");diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/SlotsPanel.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/SlotsPanel.tsxindex 7c7d24a862..752ae4345b 100644--- a/jarvis/ui/web/frontend/src/components/ultrawiki/SlotsPanel.tsx+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/SlotsPanel.tsx@@ -3,14 +3,20 @@* distillation, rerank) rendered as provider CARDS, in the same visual and* behavioural language as the API-Keys view.*- * What changed and why (2026-07-25): the previous version showed a dropdown- * per slot and, for anything needing a credential, the sentence "add it in the- * API-Keys view". That view has no field for these slots, so Voyage, Mistral,- * Cohere and every Postgres store were listed but impossible to connect from- * inside the app — the exact out-of-app setup step the in-app-recoverable- * mandate forbids (§3, AP-23). Every provider now carries its credential- * widget on its own card, using the SAME `ApiKeyForm` component the API-Keys- * view uses, so the two screens cannot drift apart.+ * Two rounds of "this is not the API-Keys section, it just looks vaguely like+ * it" got it here:+ *+ * 1. The slots used to be dropdowns whose credential hint pointed at the+ * API-Keys view — which has no field for `voyage_api_key`,+ * `mistral_api_key`, `cohere_api_key` or `ultrawiki_db_url`. Every provider+ * now carries its credential widget on its own card, and that widget IS the+ * shared `ApiKeyForm`, so the two screens cannot drift apart.+ * 2. The model was then a free-text box while every other provider surface in+ * the app has a searchable picker. It is now the SAME picker+ * (`BrainModelSelector`), fed by `GET /api/ultrawiki/models/{slot}` — live+ * from the provider where one is listed, curated where none is, and its+ * custom-id row still reaches a model no catalog knows yet. Picking saves;+ * there is no separate Save button to forget.** Slot rules that are deliberate, not incidental:*@@ -38,6 +44,7 @@ import {Loader2,} from "lucide-react";+import { BrainModelSelector } from "@/components/BrainModelSelector";import { Button } from "@/components/ui/button";import { cn } from "@/lib/utils";import { useT } from "@/i18n";@@ -49,11 +56,12 @@ import {} from "@/views/settings/SettingsBlock";import { SupabaseConnect } from "@/components/ultrawiki/SupabaseConnect";import {- StateChip,+ SlotActiveControl,UltraProviderCard,} from "@/components/ultrawiki/UltraProviderCard";import {fetchUltraWikiCatalog,+ fetchUltraWikiSlotModels,reembedGateOf,testUltraWikiSlot,updateUltraWikiSettings,@@ -181,6 +189,51 @@ interface SectionProps {refresh: () => void;}+/**+ * The shared model picker — literally the API-Keys one, pointed at this slot.+ *+ * `onSave` returns the picker's expected result shape; UltraWiki runs no+ * 1-token probe on a model pin (the slot's own Test button does a real call),+ * so `probe` is null and the picker simply shows the saved state.+ */+function SlotModelPicker({+ slot,+ providerId,+ currentModel,+ recommendedModel,+ onSave,+}: {+ slot: UltraWikiSlotName;+ providerId: string;+ currentModel: string;+ recommendedModel?: string | null;+ onSave: (model: string) => Promise<void>;+}): JSX.Element {+ return (+ <BrainModelSelector+ providerId={providerId}+ currentModel={currentModel}+ recommendedModel={recommendedModel ?? null}+ controlled+ loadModels={(refresh) =>+ fetchUltraWikiSlotModels(slot, providerId, refresh)+ }+ onSave={async (model) => {+ await onSave(model);+ return {+ ok: true,+ provider: providerId,+ model,+ persisted: true,+ applied_live: true,+ restart_required: false,+ probe: null,+ };+ }}+ />+ );+}+// ---------------------------------------------------------------------------// Storage// ---------------------------------------------------------------------------@@ -252,9 +305,7 @@ function EmbeddingSection({}: SectionProps): JSX.Element {const t = useT();const rows = catalog.slots.embedding ?? [];- const [model, setModel] = useState<string | null>(null);const [endpoint, setEndpoint] = useState<string | null>(null);- const modelValue = model ?? catalog.models.embedding;const endpointValue = endpoint ?? catalog.ollama_endpoint;return (@@ -284,50 +335,45 @@ function EmbeddingSection({>{row.selected && (<div className="space-y-3">- <SettingsField label={t("ultrawiki.slots.model_label")}>- <input- type="text"- value={modelValue}- onChange={(e) => setModel(e.target.value)}- placeholder={row.default_model}- className={settingsInputCls}- data-testid="ultrawiki-embedding-model-input"- />- </SettingsField>- {row.supports_base_url && (- <SettingsField label={t("ultrawiki.slots.server_url_label")}>- <input- type="url"- value={endpointValue}- onChange={(e) => setEndpoint(e.target.value)}- placeholder={row.default_base_url ?? ""}- className={settingsInputCls}- data-testid="ultrawiki-ollama-endpoint-input"- />- </SettingsField>- )}- <Button- size="sm"- disabled={pending}- onClick={() =>- void apply({+ <SlotModelPicker+ slot="embedding"+ providerId={row.id}+ currentModel={catalog.models.embedding}+ recommendedModel={row.default_model}+ onSave={(model) =>+ apply({embedding_provider: row.id,- embedding_model: modelValue,- ...(row.supports_base_url- ? { ollama_endpoint: endpointValue }- : {}),+ embedding_model: model,})}- data-testid="ultrawiki-embedding-apply"- >- {pending && (- <Loader2- className="mr-1 h-3.5 w-3.5 animate-spin"- aria-hidden- />- )}- {t("ultrawiki.slots.save_model")}- </Button>+ />+ {row.supports_base_url && (+ <div className="space-y-2">+ <SettingsField+ label={t("ultrawiki.slots.server_url_label")}+ >+ <input+ type="url"+ value={endpointValue}+ onChange={(e) => setEndpoint(e.target.value)}+ placeholder={row.default_base_url ?? ""}+ className={settingsInputCls}+ data-testid="ultrawiki-ollama-endpoint-input"+ />+ </SettingsField>+ <Button+ size="sm"+ variant="secondary"+ disabled={pending || endpointValue === catalog.ollama_endpoint}+ onClick={() =>+ void apply({ ollama_endpoint: endpointValue })+ }+ data-testid="ultrawiki-ollama-endpoint-apply"+ >+ {t("ultrawiki.slots.save_server_url")}+ </Button>+ </div>+ )}</div>)}</UltraProviderCard>@@ -354,8 +400,6 @@ function DistillSection({}: SectionProps): JSX.Element {const t = useT();const rows = catalog.slots.distill ?? [];- const [model, setModel] = useState<string | null>(null);- const modelValue = model ?? catalog.models.distill;const automatic = !catalog.selected.distill;return (@@ -369,6 +413,7 @@ function DistillSection({<SlotProvenance slot="distill" via={status.slots.distill?.via} /><CardGrid><SlotDefaultCard+ slot="distill"selected={automatic}busy={pending}title={t("ultrawiki.slots.distill_auto")}@@ -385,34 +430,15 @@ function DistillSection({onCredentialChanged={refresh}>{row.selected && (- <div className="space-y-2">- <SettingsField label={t("ultrawiki.slots.model_label")}>- <input- type="text"- value={modelValue}- onChange={(e) => setModel(e.target.value)}- placeholder={- row.default_model ||- t("ultrawiki.slots.model_cheap_default")- }- className={settingsInputCls}- data-testid="ultrawiki-distill-model-input"- />- </SettingsField>- <Button- size="sm"- disabled={pending}- onClick={() =>- void apply({- distill_provider: row.id,- distill_model: modelValue,- })- }- data-testid="ultrawiki-distill-apply"- >- {t("ultrawiki.slots.save_model")}- </Button>- </div>+ <SlotModelPicker+ slot="distill"+ providerId={row.id}+ currentModel={catalog.models.distill}+ recommendedModel={row.default_model}+ onSave={(model) =>+ apply({ distill_provider: row.id, distill_model: model })+ }+ />)}</UltraProviderCard>))}@@ -436,11 +462,10 @@ function RerankSection({const t = useT();const rows = catalog.slots.rerank ?? [];const off = !catalog.selected.rerank;- const [rerankModel, setRerankModel] = useState<string | null>(null);const [floor, setFloor] = useState<string | null>(null);- const rerankModelValue = rerankModel ?? status.slots.rerank?.model ?? "";- const floorValue =- floor ?? String(status.slots.rerank?.ranking?.rerank_min_score ?? 4);+ const rerankModel = status.slots.rerank?.model ?? "";+ const savedFloor = String(status.slots.rerank?.ranking?.rerank_min_score ?? 4);+ const floorValue = floor ?? savedFloor;return (<SettingsBlock@@ -453,6 +478,7 @@ function RerankSection({<SlotProvenance slot="rerank" via={status.slots.rerank?.via} /><CardGrid><SlotDefaultCard+ slot="rerank"selected={off}busy={pending}title={t("ultrawiki.slots.rerank_off")}@@ -472,37 +498,20 @@ function RerankSection({rerank_provider: row.id,// The vendor cross-encoders pin their own model; only the// chat-graded backend takes one from the user.- rerank_model: row.id === "llm" ? rerankModelValue : "",+ rerank_model: row.id === "llm" ? rerankModel : "",})}onCredentialChanged={refresh}>{row.selected && row.id === "llm" && (- <div className="space-y-2">- <SettingsField label={t("ultrawiki.slots.model_label")}>- <input- type="text"- value={rerankModelValue}- onChange={(e) => setRerankModel(e.target.value)}- placeholder={t("ultrawiki.slots.rerank_model_placeholder")}- className={settingsInputCls}- data-testid="ultrawiki-rerank-model-input"- />- </SettingsField>- <Button- size="sm"- disabled={pending}- onClick={() =>- void apply({- rerank_provider: row.id,- rerank_model: rerankModelValue,- })- }- data-testid="ultrawiki-rerank-apply"- >- {t("ultrawiki.slots.save_model")}- </Button>- </div>+ <SlotModelPicker+ slot="rerank"+ providerId={row.id}+ currentModel={rerankModel}+ onSave={(model) =>+ apply({ rerank_provider: row.id, rerank_model: model })+ }+ />)}</UltraProviderCard>))}@@ -529,7 +538,8 @@ function RerankSection({</p><Buttonsize="sm"- disabled={pending}+ variant="secondary"+ disabled={pending || floorValue === savedFloor}onClick={() => void apply({ rerank_min_score: Number(floorValue) })}data-testid="ultrawiki-rerank-floor-apply">@@ -546,6 +556,8 @@ function RerankSection({// ---------------------------------------------------------------------------function CardGrid({ children }: { children: React.ReactNode }): JSX.Element {+ // items-stretch (the grid default) plus h-full on the cards: a provider with+ // six lines of help text and one with three still produce a level row.return <div className="grid gap-3 lg:grid-cols-2">{children}</div>;}@@ -583,6 +595,7 @@ function SlotProvenance({* with the plain fusion order.*/function SlotDefaultCard({+ slot,selected,busy,title,@@ -590,6 +603,7 @@ function SlotDefaultCard({onSelect,testId,}: {+ slot: UltraWikiSlotName;selected: boolean;busy: boolean;title: string;@@ -597,7 +611,6 @@ function SlotDefaultCard({onSelect: () => void;testId: string;}): JSX.Element {- const t = useT();return (<divonClick={() => {@@ -606,33 +619,22 @@ function SlotDefaultCard({data-testid={testId}data-selected={selected ? "true" : "false"}className={cn(- "card-outline space-y-3 p-4 transition-colors",+ "card-outline flex h-full flex-col gap-3 p-4 transition-colors",selected? "border-primary bg-primary/[0.06] ring-1 ring-primary/30": "cursor-pointer hover:border-primary/40 hover:bg-primary/[0.02]",)}><div className="flex items-start justify-between gap-3">- <div className="min-w-0 flex-1">- <div className="flex flex-wrap items-center gap-2">- <span className="font-display text-sm font-semibold tracking-tight">- {title}- </span>- {selected && (- <StateChip tone="active">- {t("ultrawiki.card.chip_in_use")}- </StateChip>- )}- </div>- </div>- <Button- size="sm"- variant={selected ? "secondary" : "outline"}- disabled={selected || busy}- onClick={onSelect}- >- {t(selected ? "ultrawiki.card.in_use" : "ultrawiki.card.use")}- </Button>+ <span className="font-display text-sm font-semibold tracking-tight">+ {title}+ </span>+ <SlotActiveControl+ slot={slot}+ selected={selected}+ busy={busy}+ onSelect={onSelect}+ /></div><p className="text-[11px] leading-relaxed text-muted-foreground">{body}</p></div>diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/UltraProviderCard.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/UltraProviderCard.tsxindex aebd2fb34a..038cbb57cb 100644--- a/jarvis/ui/web/frontend/src/components/ultrawiki/UltraProviderCard.tsx+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/UltraProviderCard.tsx@@ -1,24 +1,25 @@/*** One provider card inside an UltraWiki capability slot.*- * Deliberately the same visual language as the API-Keys view's `ProviderCard`- * (`card-outline`, the primary ring on the active card, the state chip, the- * `ApiKeyForm` credential widget, a footer separated from the body): the two- * screens do the same job — pick a provider, give it a credential, verify it —- * so they must not look like two different products.+ * Deliberately the same card as the API-Keys view's `ProviderCard`, down to+ * the details that make it read as one product: `card-outline`, the primary+ * ring on the active card, the state chip, a radio "Set active" control on the+ * right (NOT a second button repeating what the chip already says), the shared+ * `ApiKeyForm` credential widget, and a footer separated from the body.*- * The credential widget is literally `ApiKeyForm`, not a copy of it. That is- * the point of this rewrite: the old settings cards had no credential input at- * all and told the user to go to the API-Keys view, which has no field for- * these slots either. Sharing the component means the entry, the reveal- * toggle, the shared-key delete warning and the "get your key" link behave- * identically here and there, forever.+ * Sharing `ApiKeyForm` rather than copying it is the point: the entry, the+ * reveal toggle, the shared-key delete warning and the "get your key" link+ * behave identically here and in the API-Keys view, forever.+ *+ * Cards sit in a grid, so each one stretches to the row height and pins its+ * credential block to the bottom — otherwise a provider with three lines of+ * help text and one with six produce the ragged, unfinished look that reads as+ * "generated" rather than designed.*/import type { ReactNode } from "react";import { Sparkles } from "lucide-react";import { ApiKeyForm } from "@/components/ApiKeyForm";-import { Button } from "@/components/ui/button";import { cn } from "@/lib/utils";import { useT } from "@/i18n";import type { UltraWikiCatalogRow } from "@/lib/ultrawikiApi";@@ -49,6 +50,50 @@ export function StateChip({);}+/**+ * The radio "Set active" control, identical in shape and wording to the one on+ * the API-Keys cards. A radio, not a button: it says "one of these is chosen"+ * at a glance, which a row of identical buttons never does.+ */+export function SlotActiveControl({+ slot,+ selected,+ busy,+ onSelect,+ title,+ testId,+}: {+ slot: string;+ selected: boolean;+ busy: boolean;+ onSelect: () => void;+ title?: string;+ testId?: string;+}): JSX.Element {+ const t = useT();+ return (+ <label+ onClick={(e) => e.stopPropagation()}+ className={cn(+ "inline-flex shrink-0 cursor-pointer select-none items-center gap-1.5 text-xs",+ selected ? "font-medium text-primary" : "text-muted-foreground hover:text-foreground",+ )}+ title={title}+ >+ <input+ type="radio"+ name={`ultrawiki-slot-${slot}`}+ checked={selected}+ onChange={() => onSelect()}+ disabled={busy}+ data-testid={testId}+ className="accent-primary"+ />+ {t(selected ? "ultrawiki.card.in_use" : "ultrawiki.card.use")}+ </label>+ );+}+export function UltraProviderCard({row,busy,@@ -63,13 +108,14 @@ export function UltraProviderCard({onSelect: () => void;/** A credential was saved or deleted — refetch the catalog. */onCredentialChanged: () => void;- /** Slot-specific body (model input, connect wizard, server URL). */+ /** Slot-specific body (model picker, connect wizard, server URL). */children?: ReactNode;- /** Slot-specific footer under the separator (a test result, a hint). */+ /** Slot-specific footer under the separator. */footer?: ReactNode;}): JSX.Element {const t = useT();const keyless = row.auth_mode === "none";+ const managed = row.auth_mode === "managed_link";// A card click selects, EXCEPT on an interactive child — clicking into the// password box or the trash icon must never also flip the provider. Same@@ -100,7 +146,7 @@ export function UltraProviderCard({data-testid={`ultrawiki-card-${row.slot}-${row.id}`}data-selected={row.selected ? "true" : "false"}className={cn(- "card-outline space-y-3 p-4 transition-colors",+ "card-outline flex h-full flex-col gap-3 p-4 transition-colors",row.selected? "border-primary bg-primary/[0.06] ring-1 ring-primary/30": "cursor-pointer hover:border-primary/40 hover:bg-primary/[0.02]",@@ -112,7 +158,15 @@ export function UltraProviderCard({<span className="font-display text-sm font-semibold tracking-tight">{row.label}</span>- <CardStatusChip row={row} />+ {/* The chip carries only what the radio does NOT already say. */}+ {!row.selected && row.ready && (+ <StateChip tone="ready">{t("ultrawiki.card.chip_ready")}</StateChip>+ )}+ {!row.selected && !row.ready && (+ <StateChip tone="neutral">+ {t("ultrawiki.card.chip_needs_setup")}+ </StateChip>+ )}{row.recommended && (<span className="inline-flex items-center gap-1 rounded-full border border-primary/40 bg-primary/10 px-2 py-0.5 text-[10px] font-medium text-primary"><Sparkles aria-hidden="true" className="h-2.5 w-2.5" />@@ -134,17 +188,24 @@ export function UltraProviderCard({<span>{t(`ultrawiki.card.auth_${row.auth_mode}`)}</span></p></div>- <Button- size="sm"- variant={row.selected ? "secondary" : "outline"}- disabled={row.selected || busy}- onClick={onSelect}- data-testid={`ultrawiki-use-${row.slot}-${row.id}`}- >- {t(row.selected ? "ultrawiki.card.in_use" : "ultrawiki.card.use")}- </Button>+ <SlotActiveControl+ slot={row.slot}+ selected={row.selected}+ busy={busy}+ onSelect={onSelect}+ testId={`ultrawiki-use-${row.slot}-${row.id}`}+ title={+ row.selected+ ? t("ultrawiki.card.in_use_tooltip")+ : t("ultrawiki.card.click_to_use")+ }+ /></div>+ <p className="text-[11px] leading-relaxed text-muted-foreground">+ {row.credential_help}+ </p>+{/* The honest reason line. Amber, not red: a provider without a key isnot broken, it is simply not set up — and for every slot but theembedding one, Jarvis keeps working without it. */}@@ -157,42 +218,30 @@ export function UltraProviderCard({</p>)}- {/* A managed_link provider owns its own multi-step flow (Supabase: browser- login → project pick → password), so the card shows the explanation- and hands the credential UI to `children`. Rendering the default key- boxes here as well would ask for two secrets the user should never- type by hand. */}- {keyless || row.auth_mode === "managed_link" ? (- <p className="text-[11px] leading-relaxed text-muted-foreground">- {row.credential_help}- </p>- ) : (- row.secret_keys.map((secretKey) => (- <ApiKeyForm- key={secretKey}- secretKey={secretKey}- dashboardUrl={row.dashboard_url}- configured={Boolean(row.secrets_set[secretKey])}- sharedWith={row.secret_shared_with[secretKey] ?? []}- credentialHelp={row.credential_help}- onChanged={onCredentialChanged}- />- ))- )}-{children}- {footer && (- <div className="border-t border-border/60 pt-2.5">{footer}</div>- )}+ {/* Credentials sit at the bottom of every card, so a row of cards lines+ its input boxes up instead of scattering them by help-text length.+ A managed_link provider owns its own multi-step flow through+ `children` and gets no default key boxes — asking for two secrets the+ user should never type by hand. */}+ <div className="mt-auto space-y-2 pt-1">+ {!keyless &&+ !managed &&+ row.secret_keys.map((secretKey) => (+ <ApiKeyForm+ key={secretKey}+ secretKey={secretKey}+ dashboardUrl={row.dashboard_url}+ configured={Boolean(row.secrets_set[secretKey])}+ sharedWith={row.secret_shared_with[secretKey] ?? []}+ onChanged={onCredentialChanged}+ />+ ))}+ {footer && (+ <div className="border-t border-border/60 pt-2.5">{footer}</div>+ )}+ </div></div>);}--/** In use → active; usable → ready; otherwise "needs setup". */-function CardStatusChip({ row }: { row: UltraWikiCatalogRow }): JSX.Element {- const t = useT();- if (row.selected) return <StateChip tone="active">{t("ultrawiki.card.chip_in_use")}</StateChip>;- if (row.ready) return <StateChip tone="ready">{t("ultrawiki.card.chip_ready")}</StateChip>;- return <StateChip tone="neutral">{t("ultrawiki.card.chip_needs_setup")}</StateChip>;-}diff --git a/jarvis/ui/web/frontend/src/hooks/useProviders.ts b/jarvis/ui/web/frontend/src/hooks/useProviders.tsindex 5e3c22b886..ec38178904 100644--- a/jarvis/ui/web/frontend/src/hooks/useProviders.ts+++ b/jarvis/ui/web/frontend/src/hooks/useProviders.ts@@ -821,6 +821,12 @@ export interface BrainModelsResult {fetched_at: number;// What the picker writes: "model" (brain/stt/cartesia) or "voice" (most TTS).selects?: "model" | "voice";+ /**+ * Why a `curated` list is being shown instead of the provider's own ("no+ * Gemini API key saved yet"). Optional: only the UltraWiki slot catalog+ * fills it in today. Shown verbatim under the picker.+ */+ reason?: string;}/** Lists the available models for a brain provider for the picker dropdown. */diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex b2de0c3151..186c1a3141 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -2816,7 +2816,6 @@"in_use": "In Benutzung: {0}","embedding_title": "Embedding-Modell","embedding_desc": "Wandelt Text in Vektoren für die semantische Suche um. Ein Wechsel bettet alles neu ein.",- "model_label": "Modell","distill_title": "Destillations-Modell","distill_desc": "Fasst aufgenommene Elemente im Hintergrund zusammen. Gilt nur für neue Arbeit.","distill_auto": "Automatisch — erster bereiter Chat-Anbieter",@@ -2842,13 +2841,12 @@"via": "Über: {0}","loading": "Anbieterliste wird geladen…","catalog_unavailable": "Die Anbieterliste konnte nicht geladen werden. Die App startet möglicherweise noch — versuche es gleich noch einmal.",- "save_model": "Modell speichern","server_url_label": "Server-URL","storage_restart_hint": "Eine Änderung am Speicher greift beim nächsten Start von Jarvis. Es wird nichts gelöscht, und bis dahin antwortet der bisherige Speicher weiter.","embedding_lock_hint": "Dieser Slot hat absichtlich keinen automatischen Ersatz: Anbieter und Modell zusammen legen den Vektorraum deines gesamten Gedächtnisses fest, deshalb wechselt Jarvis ihn nie unbemerkt.","distill_auto_desc": "Nutzt den Chat-Anbieter, für den du bereits gültige Zugangsdaten hast, und geht zum nächsten weiter, wenn dieser gedrosselt ist oder kein Guthaben mehr hat. Die sichere Voreinstellung.","rerank_off_desc": "Die Suche funktioniert trotzdem: Die Treffer behalten die Reihenfolge, auf die sich Stichwort- und Bedeutungssuche geeinigt haben. Schalte einen Reranker ein, wenn präzise Fragen schärfere Antworten brauchen.",- "model_cheap_default": "Standard der Kette (schnelles, günstiges Modell)"+ "save_server_url": "Server-URL speichern"},"wizard": {"title": "Ultra-Modus einschalten",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex e9924c86e7..beb77a056e 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -2817,7 +2817,6 @@"in_use": "In use: {0}","embedding_title": "Embedding model","embedding_desc": "Turns text into vectors for semantic search. Changing it re-embeds everything.",- "model_label": "Model","distill_title": "Distillation model","distill_desc": "Summarizes ingested items in the background. Applies to new work only.","distill_auto": "Automatic — first ready chat provider",@@ -2843,13 +2842,12 @@"via": "Via: {0}","loading": "Loading the provider list…","catalog_unavailable": "The provider list could not be loaded. The app may still be starting — try again in a moment.",- "save_model": "Save model","server_url_label": "Server URL","storage_restart_hint": "A storage change takes effect the next time Jarvis starts. Nothing is deleted, and the current store keeps answering until then.","embedding_lock_hint": "This slot has no automatic fallback on purpose: the provider and model together define the vector space of your whole memory, so Jarvis never switches it silently.","distill_auto_desc": "Uses whichever chat provider you already have a working credential for, and moves on to the next one if it is rate limited or out of credit. The safe default.","rerank_off_desc": "Search still works: results keep the order the keyword and semantic legs agreed on. Turn a reranker on for sharper answers to precise questions.",- "model_cheap_default": "Chain default (a cheap fast model)"+ "save_server_url": "Save server URL"},"wizard": {"title": "Turn on Ultra mode",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex f425e21a14..912b7ad6f2 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -2816,7 +2816,6 @@"in_use": "En uso: {0}","embedding_title": "Modelo de embeddings","embedding_desc": "Convierte el texto en vectores para la búsqueda semántica. Cambiarlo vuelve a incrustar todo.",- "model_label": "Modelo","distill_title": "Modelo de destilación","distill_desc": "Resume los elementos ingeridos en segundo plano. Solo aplica al trabajo nuevo.","distill_auto": "Automático — primer proveedor de chat listo",@@ -2842,13 +2841,12 @@"via": "Mediante: {0}","loading": "Cargando la lista de proveedores…","catalog_unavailable": "No se pudo cargar la lista de proveedores. Puede que la aplicación aún esté arrancando: inténtalo de nuevo en un momento.",- "save_model": "Guardar modelo","server_url_label": "URL del servidor","storage_restart_hint": "Un cambio de almacenamiento surte efecto la próxima vez que arranque Jarvis. No se borra nada y, hasta entonces, el almacén actual sigue respondiendo.","embedding_lock_hint": "Esta ranura no tiene alternativa automática a propósito: el proveedor y el modelo juntos definen el espacio vectorial de toda tu memoria, así que Jarvis nunca lo cambia en silencio.","distill_auto_desc": "Usa el proveedor de chat para el que ya tengas una credencial válida y pasa al siguiente si está limitado o sin saldo. La opción segura por defecto.","rerank_off_desc": "La búsqueda sigue funcionando: los resultados mantienen el orden en el que coincidieron la búsqueda por palabras clave y la semántica. Activa un reranker para respuestas más precisas.",- "model_cheap_default": "Valor por defecto de la cadena (modelo rápido y barato)"+ "save_server_url": "Guardar URL del servidor"},"wizard": {"title": "Activar el modo Ultra",diff --git a/jarvis/ui/web/frontend/src/lib/ultrawikiApi.ts b/jarvis/ui/web/frontend/src/lib/ultrawikiApi.tsindex 56fbacb2bf..79601d99fc 100644--- a/jarvis/ui/web/frontend/src/lib/ultrawikiApi.ts+++ b/jarvis/ui/web/frontend/src/lib/ultrawikiApi.ts@@ -329,6 +329,21 @@ export interface UltraWikiCatalog {ollama_endpoint: string;}+/**+ * Mirrors `GET /api/ultrawiki/models/{slot}` — deliberately the same shape as+ * `BrainModelsResult` so the shared picker consumes it unchanged.+ */+export interface UltraWikiSlotModels {+ provider: string;+ current_model: string;+ models: { id: string; label: string }[];+ source: "live" | "cache" | "static" | "curated";+ fetched_at: number;+ selects?: "model" | "voice";+ /** Why a curated list is shown ("no Gemini API key saved yet"). */+ reason?: string;+}+export interface SupabaseProject {ref: string;name: string;@@ -481,6 +496,25 @@ export function fetchUltraWikiCatalog(): Promise<UltraWikiCatalog> {return request<UltraWikiCatalog>("/api/ultrawiki/catalog");}+/**+ * The selectable models for one slot's provider, in the exact shape the+ * API-Keys model picker consumes — so the slots get THAT picker (searchable,+ * refreshable, custom ids allowed) instead of a free-text box.+ */+export function fetchUltraWikiSlotModels(+ slot: UltraWikiSlotName,+ provider: string,+ refresh = false,+): Promise<UltraWikiSlotModels> {+ const params = new URLSearchParams();+ if (provider) params.set("provider", provider);+ if (refresh) params.set("refresh", "true");+ const query = params.toString();+ return request<UltraWikiSlotModels>(+ `/api/ultrawiki/models/${encodeURIComponent(slot)}${query ? `?${query}` : ""}`,+ );+}+export function fetchSupabaseProjects(): Promise<SupabaseProjectsResponse> {return request<SupabaseProjectsResponse>("/api/ultrawiki/storage/supabase/projects",diff --git a/jarvis/ui/web/ultrawiki_routes.py b/jarvis/ui/web/ultrawiki_routes.pyindex c77ed89817..1c9150dbc5 100644--- a/jarvis/ui/web/ultrawiki_routes.py+++ b/jarvis/ui/web/ultrawiki_routes.py@@ -495,6 +495,122 @@ async def get_catalog(request: Request) -> dict[str, Any]:}[email protected]("/models/{slot}", summary="Selectable models for one UltraWiki slot")+async def list_slot_models(+ slot: str,+ request: Request,+ provider: str = Query(default="", description="Defaults to the slot's provider"),+ refresh: bool = Query(default=False),+) -> dict[str, Any]:+ """The model catalog for a slot's provider, shaped like the brain picker's.++ Same payload as ``GET /api/providers/{id}/models`` so the settings cards+ reuse the API-Keys model picker verbatim instead of a look-alike — a+ free-text box was how a one-character typo ("gemini-embedding-01") became a+ silently paused embed stage.++ Embedding models come from :mod:`jarvis.ultrawiki.embedding_models`+ (live where the provider lists them, curated otherwise); distillation and+ the chat-graded reranker are ordinary chat providers and go through the+ shared brain catalog. ``source`` stays honest either way, and the picker's+ custom-id row still reaches a model no catalog knows yet.+ """+ cfg = _config(request)+ uw = _uw_cfg(request)+ if slot not in ("embedding", "distill", "rerank"):+ raise HTTPException(+ status_code=404,+ detail="unknown slot — one of: embedding, distill, rerank",+ )++ chosen = provider.strip() or str(+ getattr(uw, f"{slot}_provider", "") or ""+ ).strip()+ current = str(getattr(uw, f"{slot}_model", "") or "").strip()+ if not chosen:+ return {+ "provider": "",+ "current_model": current,+ "models": [],+ "source": "curated",+ "fetched_at": 0.0,+ "selects": "model",+ "reason": "no provider is selected for this slot yet",+ }++ if slot == "embedding":+ from jarvis.ultrawiki import embedding_models # noqa: PLC0415 — lazy (AP-26)++ result = await embedding_models.list_embedding_models(chosen, cfg)+ payload = result.as_dict()+ return {+ "provider": chosen,+ "current_model": current,+ "models": payload["models"],+ "source": payload["source"],+ "fetched_at": time.time(),+ "selects": "model",+ "reason": payload["reason"],+ }++ # distill + the "llm" reranker both grade with an ordinary chat provider,+ # so they share the brain catalog rather than a second copy of it.+ if slot == "rerank" and chosen != "llm":+ # A vendor cross-encoder pins its own model; there is nothing to pick.+ return {+ "provider": chosen,+ "current_model": "",+ "models": [],+ "source": "curated",+ "fetched_at": 0.0,+ "selects": "model",+ "reason": "this reranker uses its own fixed model",+ }+ if slot == "rerank":+ chosen = str(getattr(uw, "distill_provider", "") or "").strip()+ if not chosen:+ return {+ "provider": "",+ "current_model": current,+ "models": [],+ "source": "curated",+ "fetched_at": 0.0,+ "selects": "model",+ "reason": (+ "the chat-graded reranker follows your provider chain — "+ "pin a distillation provider to choose its model"+ ),+ }++ try:+ from jarvis.ui.web.provider_routes import ( # noqa: PLC0415 — lazy+ _get_model_catalog,+ )++ catalog = _get_model_catalog(request)+ result = await catalog.list_models(chosen, force_refresh=refresh)+ except Exception as exc: # noqa: BLE001 — a dead catalog must not 500 the screen+ log.debug("slot model catalog failed for %s", chosen, exc_info=True)+ return {+ "provider": chosen,+ "current_model": current,+ "models": [],+ "source": "curated",+ "fetched_at": 0.0,+ "selects": "model",+ "reason": f"model list unavailable ({type(exc).__name__})",+ }+ return {+ "provider": chosen,+ "current_model": current,+ "models": [{"id": m.id, "label": m.label} for m in result.models],+ "source": result.source,+ "fetched_at": result.fetched_at,+ "selects": "model",+ "reason": "",+ }++# ---------------------------------------------------------------------------# Storage — the guided Supabase link# ---------------------------------------------------------------------------diff --git a/jarvis/ultrawiki/embedding_models.py b/jarvis/ultrawiki/embedding_models.pynew file mode 100644index 0000000000..ce5d66f010--- /dev/null+++ b/jarvis/ultrawiki/embedding_models.py@@ -0,0 +1,295 @@+"""Model discovery for the UltraWiki embedding slot.++Why this exists: the embedding card used to be a free-text box. Typing a model+id from memory is how you end up with `gemini-embedding-01`, a 404 on the first+real embed, and a paused pipeline whose cause is one character wide. The chat+providers never had that problem — they get a searchable dropdown fed by the+provider's own catalog (:mod:`jarvis.brain.model_catalog`) — and there is no+reason the embedding slot should be the exception.++So each backend gets the same treatment, in the same order of preference:++1. **Live** — ask the provider what it actually serves, so a model released+ after this build still shows up with no code change.+2. **Curated** — a short, current, hand-kept list when the provider has no+ listing endpoint (Voyage) or the call fails (no key, offline, rate limit).++Never a hard failure: an unreachable catalog degrades to the curated list, and+the UI keeps its "type a custom id" escape hatch, so a brand-new model is+always reachable. Discovery is read-only and unauthenticated where possible;+credentials ride the usual secret chain and are never logged.+"""++from __future__ import annotations++import logging+from dataclasses import dataclass+from typing import Any++import httpx++from jarvis.core.config import get_secret, get_secret_any++log = logging.getLogger(__name__)++__all__ = [+ "EmbeddingModel",+ "EmbeddingModelList",+ "CURATED_EMBEDDING_MODELS",+ "list_embedding_models",+]++#: A catalog call must not stall the settings screen; a slow provider falls+#: back to the curated list rather than holding the page.+_TIMEOUT = httpx.Timeout(connect=3.0, read=6.0, write=3.0, pool=3.0)++#: Mirrors the Gemini credential candidates used by the embedding backend.+_GEMINI_KEY_CANDIDATES: tuple[tuple[str, str], ...] = (+ ("gemini_api_key", "GEMINI_API_KEY"),+ ("google_aistudio_api_key", "GOOGLE_AIStudio_API_KEY"),+ ("google_api_key", "GOOGLE_API_KEY"),+)+++@dataclass(frozen=True, slots=True)+class EmbeddingModel:+ """One selectable embedding model. Shape mirrors the brain picker's rows."""++ id: str+ label: str++ def as_dict(self) -> dict[str, str]:+ return {"id": self.id, "label": self.label}+++@dataclass(frozen=True, slots=True)+class EmbeddingModelList:+ """Discovery result. ``source`` is honest about where the list came from."""++ models: tuple[EmbeddingModel, ...]+ #: "live" (the provider answered) | "curated" (hand-kept fallback)+ source: str+ #: Empty when live; why the fallback was used otherwise.+ reason: str = ""++ def as_dict(self) -> dict[str, Any]:+ return {+ "models": [m.as_dict() for m in self.models],+ "source": self.source,+ "reason": self.reason,+ }+++#: Hand-kept fallback per backend. Deliberately short — the current, sensible+#: choices, not an archive. Ordered best-default-first; the settings card's+#: placeholder still comes from provider_catalog.DEFAULT_MODELS.+CURATED_EMBEDDING_MODELS: dict[str, tuple[tuple[str, str], ...]] = {+ "ollama": (+ ("bge-m3", "bge-m3 — multilingual, strong all-rounder"),+ ("nomic-embed-text", "nomic-embed-text — fast, English-first"),+ ("mxbai-embed-large", "mxbai-embed-large — larger, higher quality"),+ ("snowflake-arctic-embed2", "snowflake-arctic-embed2 — multilingual"),+ ("all-minilm", "all-minilm — tiny and quick"),+ ),+ "gemini": (+ ("gemini-embedding-001", "gemini-embedding-001"),+ ("text-embedding-004", "text-embedding-004"),+ ),+ "openai": (+ ("text-embedding-3-small", "text-embedding-3-small — cheap, strong"),+ ("text-embedding-3-large", "text-embedding-3-large — highest quality"),+ ("text-embedding-ada-002", "text-embedding-ada-002 — legacy"),+ ),+ "voyage": (+ ("voyage-3.5", "voyage-3.5 — general purpose"),+ ("voyage-3.5-lite", "voyage-3.5-lite — cheaper, faster"),+ ("voyage-3-large", "voyage-3-large — highest quality"),+ ("voyage-code-3", "voyage-code-3 — tuned for code"),+ ),+ "mistral": (+ ("mistral-embed", "mistral-embed"),+ ("codestral-embed", "codestral-embed — tuned for code"),+ ),+ "cohere": (+ ("embed-v4.0", "embed-v4.0 — current, multilingual"),+ ("embed-multilingual-v3.0", "embed-multilingual-v3.0"),+ ("embed-english-v3.0", "embed-english-v3.0"),+ ),+}+++def _curated(provider: str, reason: str) -> EmbeddingModelList:+ rows = CURATED_EMBEDDING_MODELS.get(provider, ())+ return EmbeddingModelList(+ models=tuple(EmbeddingModel(id=i, label=lbl) for i, lbl in rows),+ source="curated",+ reason=reason,+ )+++def _live(models: list[EmbeddingModel]) -> EmbeddingModelList:+ return EmbeddingModelList(models=tuple(models), source="live")+++async def _get_json(+ url: str,+ *,+ headers: dict[str, str] | None = None,+ transport: httpx.AsyncBaseTransport | None = None,+) -> Any:+ async with httpx.AsyncClient(timeout=_TIMEOUT, transport=transport) as client:+ response = await client.get(url, headers=headers)+ response.raise_for_status()+ return response.json()+++async def _ollama(cfg: Any, transport: Any) -> EmbeddingModelList:+ """Everything the local Ollama has pulled.++ Ollama exposes no "is this an embedding model" flag, so the list is what is+ installed and the user picks. That is honest: guessing by name would hide a+ freshly pulled model behind a filter the user cannot see.+ """+ ultrawiki = getattr(cfg, "ultrawiki", None)+ endpoint = str(+ getattr(ultrawiki, "ollama_endpoint", "") or "http://localhost:11434"+ ).rstrip("/")+ data = await _get_json(f"{endpoint}/api/tags", transport=transport)+ rows = data.get("models") if isinstance(data, dict) else None+ if not isinstance(rows, list):+ raise ValueError("unexpected /api/tags shape")+ models = [+ EmbeddingModel(id=str(row["name"]), label=str(row["name"]))+ for row in rows+ if isinstance(row, dict) and row.get("name")+ ]+ if not models:+ return _curated(+ "ollama",+ "Ollama is running but has no models pulled yet — "+ "'ollama pull bge-m3' installs a good default.",+ )+ return _live(models)+++async def _gemini(cfg: Any, transport: Any) -> EmbeddingModelList:+ """Gemini models that actually serve embedContent (capability, not name)."""+ key = get_secret_any(_GEMINI_KEY_CANDIDATES)+ if not key:+ return _curated("gemini", "no Gemini API key saved yet")+ data = await _get_json(+ "https://generativelanguage.googleapis.com/v1beta/models?pageSize=200",+ headers={"x-goog-api-key": key},+ transport=transport,+ )+ rows = data.get("models") if isinstance(data, dict) else None+ if not isinstance(rows, list):+ raise ValueError("unexpected models shape")+ models: list[EmbeddingModel] = []+ for row in rows:+ if not isinstance(row, dict):+ continue+ methods = row.get("supportedGenerationMethods") or []+ if not any(str(m).lower() == "embedcontent" for m in methods):+ continue+ name = str(row.get("name") or "").removeprefix("models/")+ if name:+ models.append(+ EmbeddingModel(id=name, label=str(row.get("displayName") or name))+ )+ return _live(models) if models else _curated("gemini", "no embedding models listed")+++async def _openai_shaped(+ provider: str, url: str, slot: str, transport: Any, *, needle: str+) -> EmbeddingModelList:+ """OpenAI-compatible ``/v1/models``, narrowed to embedding models."""+ key = get_secret(slot)+ if not key:+ return _curated(provider, "no API key saved yet")+ data = await _get_json(+ url, headers={"Authorization": f"Bearer {key}"}, transport=transport+ )+ rows = data.get("data") if isinstance(data, dict) else None+ if not isinstance(rows, list):+ raise ValueError("unexpected /v1/models shape")+ models = [+ EmbeddingModel(id=str(row["id"]), label=str(row["id"]))+ for row in rows+ if isinstance(row, dict) and needle in str(row.get("id", "")).lower()+ ]+ return _live(models) if models else _curated(provider, "no embedding models listed")+++async def _cohere(cfg: Any, transport: Any) -> EmbeddingModelList:+ """Cohere lets us ask for the embed endpoint's models directly."""+ key = get_secret("cohere_api_key")+ if not key:+ return _curated("cohere", "no API key saved yet")+ data = await _get_json(+ "https://api.cohere.com/v1/models?endpoint=embed&page_size=100",+ headers={"Authorization": f"Bearer {key}"},+ transport=transport,+ )+ rows = data.get("models") if isinstance(data, dict) else None+ if not isinstance(rows, list):+ raise ValueError("unexpected models shape")+ models = [+ EmbeddingModel(id=str(row["name"]), label=str(row["name"]))+ for row in rows+ if isinstance(row, dict) and row.get("name")+ ]+ return _live(models) if models else _curated("cohere", "no embedding models listed")+++async def list_embedding_models(+ provider: str,+ cfg: Any,+ *,+ transport: httpx.AsyncBaseTransport | None = None,+) -> EmbeddingModelList:+ """The selectable models for one embedding backend. Never raises.++ Any discovery failure — no key, offline, throttled, a changed response+ shape — degrades to the curated list with the reason attached, because a+ settings dropdown that shows nothing is worse than one showing five known+ good options.+ """+ provider = (provider or "").strip()+ if provider not in CURATED_EMBEDDING_MODELS:+ return EmbeddingModelList(+ models=(), source="curated", reason=f"unknown embedding provider {provider!r}"+ )+ try:+ if provider == "ollama":+ return await _ollama(cfg, transport)+ if provider == "gemini":+ return await _gemini(cfg, transport)+ if provider == "openai":+ return await _openai_shaped(+ "openai",+ "https://api.openai.com/v1/models",+ "openai_api_key",+ transport,+ needle="embedding",+ )+ if provider == "mistral":+ return await _openai_shaped(+ "mistral",+ "https://api.mistral.ai/v1/models",+ "mistral_api_key",+ transport,+ needle="embed",+ )+ if provider == "cohere":+ return await _cohere(cfg, transport)+ # Voyage publishes no model-listing endpoint; the curated list is the+ # only honest answer, and the custom-id row still reaches anything new.+ return _curated("voyage", "Voyage publishes no model list — these are the current ones")+ except httpx.HTTPStatusError as exc:+ return _curated(provider, f"the provider answered HTTP {exc.response.status_code}")+ except httpx.HTTPError as exc:+ return _curated(provider, f"the provider was unreachable ({type(exc).__name__})")+ except Exception as exc: # noqa: BLE001 — discovery never breaks the screen+ log.debug("embedding model discovery failed for %s", provider, exc_info=True)+ return _curated(provider, f"model discovery failed ({type(exc).__name__})")diff --git a/jarvis/ultrawiki/embeddings.py b/jarvis/ultrawiki/embeddings.pyindex 26e42aa8ed..ec629bccc3 100644--- a/jarvis/ultrawiki/embeddings.py+++ b/jarvis/ultrawiki/embeddings.py@@ -273,14 +273,15 @@ class _OpenAIShapedEmbedding(_HttpEmbedding):def ready(self) -> tuple[bool, str]:if self._key():return True, ""- # Place-neutral on purpose: this line is read on the UltraWiki- # settings card (where the key field now sits), in CLI output, and in- # logs. It used to send the user to the API-Keys view, which has no- # field for this slot -- a dead end dressed up as an instruction.+ # Short and place-neutral: the line is read on the settings card (where+ # the key field now sits, right below it), in CLI output and in logs.+ # It used to send the user to the API-Keys view, which has no field for+ # this slot -- a dead end dressed up as an instruction -- and to spell+ # out the raw snake_case slot name, which is noise next to the input+ # box it names. The env var stays: that is the headless recovery path.return False, (- f"No {self._KEY_LABEL} API key is configured - enter "- f"{self._SECRET_SLOT} on this provider's card, or set the "- f"{self._SECRET_SLOT.upper()} environment variable."+ f"No {self._KEY_LABEL} API key yet - add one below, "+ f"or set {self._SECRET_SLOT.upper()}.")async def embed(self, texts: list[str], *, model: str) -> list[list[float]]:diff --git a/jarvis/ultrawiki/provider_catalog.py b/jarvis/ultrawiki/provider_catalog.pyindex 4098bf9cb9..8a7795875b 100644--- a/jarvis/ultrawiki/provider_catalog.py+++ b/jarvis/ultrawiki/provider_catalog.py@@ -117,10 +117,9 @@ STORAGE_PROVIDERS: tuple[UltraWikiProviderSpec, ...] = (db_backend="sqlite",recommended=True,credential_help=(- "A single file under the Jarvis data directory. Zero setup, works "- "offline on every operating system, and nothing leaves this "- "machine. Pick a cloud store below only when you want the same "- "memory on several devices."+ "A single file on this machine. Zero setup, works offline, "+ "nothing leaves the device. Pick a cloud store only if you want "+ "the same memory on several machines."),),UltraWikiProviderSpec(@@ -138,10 +137,9 @@ STORAGE_PROVIDERS: tuple[UltraWikiProviderSpec, ...] = ("@<region>.pooler.supabase.com:6543/postgres"),credential_help=(- "Hosted Postgres with a generous free tier. Connect signs you in "- "through your browser, lists your projects, and builds the "- "connection string for you — you only supply the database "- "password, which Supabase never hands back over its API."+ "Hosted Postgres with a generous free tier. Signing in lists "+ "your projects and builds the connection string for you — you "+ "only add the database password."),),UltraWikiProviderSpec(@@ -156,9 +154,8 @@ STORAGE_PROVIDERS: tuple[UltraWikiProviderSpec, ...] = ("postgresql://<user>:<password>@<endpoint>.neon.tech/<db>?sslmode=require"),credential_help=(- "Serverless Postgres that scales to zero when idle. Copy the "- "pooled connection string from the Neon console — it already "- "contains the password — and paste it below."+ "Serverless Postgres that scales to zero when idle. Paste the "+ "pooled connection string from the Neon console."),),UltraWikiProviderSpec(@@ -171,10 +168,9 @@ STORAGE_PROVIDERS: tuple[UltraWikiProviderSpec, ...] = (db_backend="postgres",connection_hint="postgresql://<user>:<password>@<host>:5432/<database>",credential_help=(- "Your own Postgres, AWS RDS, Google Cloud SQL, Azure Database, "- "Railway, Render — anything that speaks Postgres. Paste the full "- "connection string. Install the pgvector extension for semantic "- "search; without it keyword search still works."+ "Your own server, RDS, Cloud SQL, Azure, Railway — anything "+ "that speaks Postgres. Add pgvector for semantic search; without "+ "it keyword search still works."),),)@@ -203,10 +199,9 @@ EMBEDDING_PROVIDERS: tuple[UltraWikiProviderSpec, ...] = (default_base_url="http://localhost:11434",recommended=True,credential_help=(- "Embeds fully on your own machine — no API key, no cloud account, "- "no per-item cost, and no text ever leaves your network. Install "- "Ollama and pull an embedding model (ollama pull bge-m3). Point "- "the server URL at another machine to share one Ollama box."+ "Runs on your own machine: no key, no per-item cost, and no "+ "text leaves your network. Needs Ollama installed with an "+ "embedding model pulled."),),UltraWikiProviderSpec(@@ -218,9 +213,8 @@ EMBEDDING_PROVIDERS: tuple[UltraWikiProviderSpec, ...] = (dashboard_url="https://aistudio.google.com/app/apikey",default_model="gemini-embedding-001",credential_help=(- "The same Google AI Studio key as the Gemini brain (starts with "- "AIza or AQ.) — no second key needed. Billed per token on your AI "- "Studio project."+ "The same Google AI Studio key as the Gemini brain — no second "+ "key needed. Billed per token."),),UltraWikiProviderSpec(@@ -232,8 +226,8 @@ EMBEDDING_PROVIDERS: tuple[UltraWikiProviderSpec, ...] = (dashboard_url="https://platform.openai.com/api-keys",default_model="text-embedding-3-small",credential_help=(- "The same OpenAI key as the GPT brain (starts with sk-). "- "text-embedding-3-small is inexpensive and strong for this job."+ "The same OpenAI key as the GPT brain. The small embedding "+ "model is inexpensive and strong for this job."),),UltraWikiProviderSpec(@@ -245,9 +239,8 @@ EMBEDDING_PROVIDERS: tuple[UltraWikiProviderSpec, ...] = (dashboard_url="https://dash.voyageai.com/api-keys",default_model="voyage-3.5",credential_help=(- "A retrieval-specialised embedding provider — usually the best "- "search quality per euro here. The same key also powers the "- "Voyage reranker below."+ "Specialised in retrieval — usually the best search quality per "+ "euro. One key also covers the Voyage reranker."),),UltraWikiProviderSpec(@@ -259,8 +252,7 @@ EMBEDDING_PROVIDERS: tuple[UltraWikiProviderSpec, ...] = (dashboard_url="https://console.mistral.ai/api-keys",default_model="mistral-embed",credential_help=(- "European provider (data processed in the EU). One model, "- "mistral-embed, billed per token on your Mistral account."+ "European provider, data processed in the EU. Billed per token."),),UltraWikiProviderSpec(@@ -272,8 +264,8 @@ EMBEDDING_PROVIDERS: tuple[UltraWikiProviderSpec, ...] = (dashboard_url="https://dashboard.cohere.com/api-keys",default_model="embed-v4.0",credential_help=(- "Strong multilingual embeddings — a good pick when your notes mix "- "languages. The same key also powers the Cohere reranker below."+ "Strong multilingual embeddings — a good pick when your notes "+ "mix languages. One key also covers the Cohere reranker."),),)@@ -302,11 +294,9 @@ RERANK_PROVIDERS: tuple[UltraWikiProviderSpec, ...] = (dashboard_url=None,recommended=True,credential_help=(- "Grades the best candidates with the chat providers you already "- "have — a cloud key, a subscription CLI, or a local Ollama model "- "offline. Needs no extra account and no second key. Slightly "- "slower than a dedicated reranker, which barely matters because "- "the stage only re-scores a handful of results."+ "Grades results with the chat providers you already have — a "+ "cloud key, a subscription CLI, or a local Ollama model. No "+ "extra account, no second key."),),UltraWikiProviderSpec(@@ -318,9 +308,8 @@ RERANK_PROVIDERS: tuple[UltraWikiProviderSpec, ...] = (dashboard_url="https://dash.voyageai.com/api-keys",default_model="rerank-2.5",credential_help=(- "A dedicated cross-encoder: lower latency than grading with a chat "- "model, at the cost of a paid single-vendor account. The same "- "Voyage key as the embedding slot — one key covers both."+ "A dedicated scoring model: faster than grading with a chat "+ "model, but needs a paid Voyage account. Same key as above."),),UltraWikiProviderSpec(@@ -332,8 +321,8 @@ RERANK_PROVIDERS: tuple[UltraWikiProviderSpec, ...] = (dashboard_url="https://dashboard.cohere.com/api-keys",default_model="rerank-v3.5",credential_help=(- "Cohere's rerank model, strong across languages. The same Cohere "- "key as the embedding slot — one key covers both."+ "Cohere's scoring model, strong across languages. Same key as "+ "the embedding slot."),),)@@ -366,9 +355,8 @@ DISTILL_PROVIDERS: tuple[UltraWikiProviderSpec, ...] = (default_model="gemini-3.5-flash",recommended=True,credential_help=(- "Google AI Studio key (AIza / AQ.). A fast flash model is exactly "- "right here — distillation is a high-volume background job, not a "- "reasoning task."+ "Google AI Studio key. A fast flash model fits well here: this "+ "is a high-volume background job, not a reasoning task."),),UltraWikiProviderSpec(@@ -378,7 +366,7 @@ DISTILL_PROVIDERS: tuple[UltraWikiProviderSpec, ...] = (auth_mode="api_key",secret_keys=("openai_api_key",),dashboard_url="https://platform.openai.com/api-keys",- credential_help="OpenAI API key (sk-), shared with the GPT brain.",+ credential_help="Shared with the GPT brain — no second key needed.",),UltraWikiProviderSpec(id="claude-api",@@ -387,7 +375,7 @@ DISTILL_PROVIDERS: tuple[UltraWikiProviderSpec, ...] = (auth_mode="api_key",secret_keys=("anthropic_api_key",),dashboard_url="https://console.anthropic.com/settings/keys",- credential_help="Anthropic API key (sk-ant-), shared with the Claude brain.",+ credential_help="Shared with the Claude brain — no second key needed.",),UltraWikiProviderSpec(id="openrouter",@@ -397,8 +385,8 @@ DISTILL_PROVIDERS: tuple[UltraWikiProviderSpec, ...] = (secret_keys=("openrouter_api_key",),dashboard_url="https://openrouter.ai/keys",credential_help=(- "OpenRouter API key (sk-or-). One key reaches many models — handy "- "when you want a cheap model for this background job."+ "One key reaches many models — handy for picking a cheap one "+ "for this background job."),),UltraWikiProviderSpec(@@ -408,7 +396,7 @@ DISTILL_PROVIDERS: tuple[UltraWikiProviderSpec, ...] = (auth_mode="api_key",secret_keys=("grok_api_key",),dashboard_url="https://console.x.ai/",- credential_help="xAI API key (xai-), shared with the Grok brain.",+ credential_help="Shared with the Grok brain — no second key needed.",),UltraWikiProviderSpec(id="nvidia",@@ -418,8 +406,8 @@ DISTILL_PROVIDERS: tuple[UltraWikiProviderSpec, ...] = (secret_keys=("nvidia_api_key",),dashboard_url="https://build.nvidia.com/settings/api-keys",credential_help=(- "NVIDIA API key (nvapi-) from build.nvidia.com. The free tier is "- "slow to first token, which matters little for a background job."+ "Key from build.nvidia.com. The free tier is slow to start, "+ "which matters little for a background job."),),UltraWikiProviderSpec(@@ -432,9 +420,8 @@ DISTILL_PROVIDERS: tuple[UltraWikiProviderSpec, ...] = (supports_base_url=True,default_base_url="http://localhost:11434",credential_help=(- "Distills on your own machine — no key, no cost, nothing leaves "- "your network. Slower than a hosted flash model, but this runs in "- "the background so latency barely matters."+ "Runs on your own machine: no key, no cost, nothing leaves "+ "your network. Slower, but this runs in the background."),),)diff --git a/jarvis/ultrawiki/rerank.py b/jarvis/ultrawiki/rerank.pyindex abafe7a9cf..2ebf13d6c6 100644--- a/jarvis/ultrawiki/rerank.py+++ b/jarvis/ultrawiki/rerank.py@@ -109,12 +109,12 @@ class _HttpReranker:def ready(self) -> tuple[bool, str]:if self._key():return True, ""- # Place-neutral: the key field lives on this provider's own settings- # card now, not in the API-Keys view (which has no slot for it).+ # Short and place-neutral: the key field sits right below this line on+ # the provider's own card, so naming the raw snake_case slot is noise.+ # The env var stays -- it is the headless recovery path.return False, (- f"No {self._KEY_LABEL} API key is configured - enter "- f"{self._SECRET_SLOT} on this provider's card, or set the "- f"{self._SECRET_SLOT.upper()} environment variable."+ f"No {self._KEY_LABEL} API key yet - add one below, "+ f"or set {self._SECRET_SLOT.upper()}.")def _payload(self, query: str, documents: list[str], top_k: int) -> dict[str, Any]:diff --git a/tests/unit/ultrawiki/test_embedding_models.py b/tests/unit/ultrawiki/test_embedding_models.pynew file mode 100644index 0000000000..a1c3bd8a9c--- /dev/null+++ b/tests/unit/ultrawiki/test_embedding_models.py@@ -0,0 +1,188 @@+"""Embedding-model discovery, driven fully offline through MockTransport.++The property that matters: the settings dropdown is NEVER empty and NEVER+wrong. Live where the provider lists its models, curated where it does not,+and curated-with-a-reason on every failure — because a picker showing nothing+sends the user straight back to typing a model id from memory, which is the+defect this module exists to end.+"""++from __future__ import annotations++import json+from types import SimpleNamespace++import httpx+import pytest++from jarvis.ultrawiki import embedding_models as em+++def cfg():+ return SimpleNamespace(+ ultrawiki=SimpleNamespace(ollama_endpoint="http://localhost:11434")+ )++[email protected](autouse=True)+def no_secrets(monkeypatch):+ """No credential unless a test says so — never read the dev box's keyring."""+ monkeypatch.setattr("jarvis.ultrawiki.embedding_models.get_secret", lambda *_a, **_k: None)+ monkeypatch.setattr(+ "jarvis.ultrawiki.embedding_models.get_secret_any", lambda *_a, **_k: None+ )+++def _transport(routes: dict[str, tuple[int, object]]) -> httpx.MockTransport:+ def handler(request: httpx.Request) -> httpx.Response:+ status, payload = routes.get(request.url.path, (404, {"error": "nope"}))+ return httpx.Response(status, content=json.dumps(payload).encode())++ return httpx.MockTransport(handler)+++async def test_ollama_lists_what_is_actually_pulled(cfg):+ transport = _transport(+ {+ "/api/tags": (+ 200,+ {"models": [{"name": "bge-m3:latest"}, {"name": "nomic-embed-text"}]},+ )+ }+ )+ result = await em.list_embedding_models("ollama", cfg, transport=transport)+ assert result.source == "live"+ assert [m.id for m in result.models] == ["bge-m3:latest", "nomic-embed-text"]+++async def test_an_empty_ollama_says_what_to_pull(cfg):+ """"No models" must read as an instruction, not as an empty dropdown."""+ transport = _transport({"/api/tags": (200, {"models": []})})+ result = await em.list_embedding_models("ollama", cfg, transport=transport)+ assert result.source == "curated"+ assert "pull" in result.reason+ assert result.models # the curated list still gives the user something+++async def test_an_offline_ollama_falls_back_with_a_reason(cfg):+ def handler(_request: httpx.Request) -> httpx.Response:+ raise httpx.ConnectError("connection refused")++ result = await em.list_embedding_models(+ "ollama", cfg, transport=httpx.MockTransport(handler)+ )+ assert result.source == "curated"+ assert "unreachable" in result.reason+ assert any(m.id == "bge-m3" for m in result.models)+++async def test_gemini_keeps_only_models_that_serve_embeddings(cfg, monkeypatch):+ """Capability, not a name pattern (AP-21).++ Filtering by "does the id contain 'embed'" would drop a future embedding+ model named otherwise AND admit a chat model called `gemini-embedded-x`.+ The API states which methods each model serves; that is the gate.+ """+ monkeypatch.setattr(+ "jarvis.ultrawiki.embedding_models.get_secret_any", lambda *_a, **_k: "key"+ )+ transport = _transport(+ {+ "/v1beta/models": (+ 200,+ {+ "models": [+ {+ "name": "models/gemini-3.5-flash",+ "supportedGenerationMethods": ["generateContent"],+ },+ {+ "name": "models/gemini-embedding-001",+ "displayName": "Gemini Embedding 001",+ "supportedGenerationMethods": ["embedContent"],+ },+ ]+ },+ )+ }+ )+ result = await em.list_embedding_models("gemini", cfg, transport=transport)+ assert result.source == "live"+ assert [m.id for m in result.models] == ["gemini-embedding-001"]+ assert result.models[0].label == "Gemini Embedding 001"+++async def test_a_keyless_cloud_provider_shows_the_curated_list(cfg):+ result = await em.list_embedding_models("openai", cfg, transport=_transport({}))+ assert result.source == "curated"+ assert "no API key" in result.reason+ assert any(m.id == "text-embedding-3-small" for m in result.models)+++async def test_openai_narrows_the_full_model_list_to_embeddings(cfg, monkeypatch):+ monkeypatch.setattr(+ "jarvis.ultrawiki.embedding_models.get_secret", lambda *_a, **_k: "sk-test"+ )+ transport = _transport(+ {+ "/v1/models": (+ 200,+ {+ "data": [+ {"id": "gpt-5.5"},+ {"id": "text-embedding-3-small"},+ {"id": "text-embedding-3-large"},+ ]+ },+ )+ }+ )+ result = await em.list_embedding_models("openai", cfg, transport=transport)+ assert result.source == "live"+ assert [m.id for m in result.models] == [+ "text-embedding-3-small",+ "text-embedding-3-large",+ ]+++async def test_voyage_has_no_listing_endpoint_and_says_so(cfg):+ """Curated is the honest answer, not a failure — the reason explains why."""+ result = await em.list_embedding_models("voyage", cfg, transport=_transport({}))+ assert result.source == "curated"+ assert "no model list" in result.reason+ assert any(m.id == "voyage-3.5" for m in result.models)+++async def test_an_http_error_never_escapes_as_an_exception(cfg, monkeypatch):+ monkeypatch.setattr(+ "jarvis.ultrawiki.embedding_models.get_secret", lambda *_a, **_k: "sk-test"+ )+ transport = _transport({"/v1/models": (500, {"error": "boom"})})+ result = await em.list_embedding_models("openai", cfg, transport=transport)+ assert result.source == "curated"+ assert "500" in result.reason+++async def test_an_unknown_provider_returns_empty_rather_than_guessing(cfg):+ result = await em.list_embedding_models("nonsense", cfg, transport=_transport({}))+ assert result.models == ()+ assert "unknown embedding provider" in result.reason+++def test_every_backend_has_a_curated_list():+ """A backend with no fallback would show an empty dropdown when offline."""+ from jarvis.ultrawiki.embeddings import EMBEDDING_BACKENDS++ assert set(em.CURATED_EMBEDDING_MODELS) == set(EMBEDDING_BACKENDS)+ for provider, rows in em.CURATED_EMBEDDING_MODELS.items():+ assert rows, provider+++def test_the_catalog_default_model_is_in_its_curated_list():+ """The card's placeholder must be a model the dropdown actually offers."""+ from jarvis.ultrawiki import provider_catalog++ for spec in provider_catalog.EMBEDDING_PROVIDERS:+ ids = {i for i, _label in em.CURATED_EMBEDDING_MODELS[spec.id]}+ assert spec.default_model in ids, spec.iddiff --git a/tests/unit/ultrawiki/test_embeddings.py b/tests/unit/ultrawiki/test_embeddings.pyindex e5d600dd95..117ba53237 100644--- a/tests/unit/ultrawiki/test_embeddings.py+++ b/tests/unit/ultrawiki/test_embeddings.py@@ -302,17 +302,17 @@ def test_keyed_backend_ready_without_key_is_false_and_honest(no_secrets, backendusable, reason = backend_class().ready()assert usable is Falseassert reason # never an empty reason on a not-ready verdict- # The reason must name BOTH recovery paths, because the two kinds of- # install fix this differently: a desktop user types the credential into- # the slot named here, a headless VPS exports the environment variable.- # (Asserted by slot + env var rather than by the name of a UI screen —- # that literal went stale the moment the key field moved onto the- # provider's own card.)+ # The reason must name the HEADLESS recovery path — the environment+ # variable — because a server install has no card to type into. The+ # desktop path is not spelled out here on purpose: the key field sits+ # directly below this line, so repeating its raw snake_case slot name is+ # noise. (Asserted by env var rather than by the name of a UI screen: that+ # literal went stale the moment the field moved onto the provider's card.)backend = backend_class()- slot = backend._SECRET_SLOT if hasattr(backend, "_SECRET_SLOT") else ""+ slot = getattr(backend, "_SECRET_SLOT", "")if slot:- assert slot in reasonassert slot.upper() in reason+ assert "add one below" in reason@pytest.mark.parametrize(diff --git a/tests/unit/ultrawiki/test_rerank.py b/tests/unit/ultrawiki/test_rerank.pyindex 1c3e9003bc..8ddb520083 100644--- a/tests/unit/ultrawiki/test_rerank.py+++ b/tests/unit/ultrawiki/test_rerank.py@@ -161,11 +161,11 @@ def test_ready_without_key_is_false_with_honest_reason(no_secrets, backend_classusable, reason = backend.ready()assert usable is Falseassert reason- # Names both recovery paths: the credential slot a desktop user fills in- # on the provider's card, and the environment variable a headless install- # exports instead.- assert backend._SECRET_SLOT in reason+ # Names the headless recovery path (the env var) and points at the field+ # on the card for everyone else. The raw snake_case slot name is+ # deliberately absent — the input box it would name is right below.assert backend._SECRET_SLOT.upper() in reason+ assert "add one below" in reason@pytest.mark.parametrize("backend_class", [VoyageReranker, CohereReranker])diff --git a/tests/unit/web/test_ultrawiki_routes.py b/tests/unit/web/test_ultrawiki_routes.pyindex 40303d9f0f..29505b4b00 100644--- a/tests/unit/web/test_ultrawiki_routes.py+++ b/tests/unit/web/test_ultrawiki_routes.py@@ -1009,3 +1009,80 @@ def test_supabase_link_is_flagged_dangerous(env) -> None:spec = env.server.app.openapi()operation = spec["paths"]["/api/ultrawiki/storage/supabase/link"]["post"]assert operation.get("x-jarvis-dangerous") is True+++# ---------------------------------------------------------------------------+# Model lists per slot+# ---------------------------------------------------------------------------+++def test_slot_models_answer_in_the_shape_the_model_picker_consumes(+ env, monkeypatch+) -> None:+ """The slots reuse the API-Keys model picker, so the payload must match it.++ A separate look-alike picker was the alternative, and it would have drifted+ from the original within a release. Same shape in, same component out.+ """+ from jarvis.ultrawiki import embedding_models++ async def fake_list(provider, cfg, *, transport=None):+ return embedding_models.EmbeddingModelList(+ models=(embedding_models.EmbeddingModel(id="bge-m3", label="bge-m3"),),+ source="live",+ )++ monkeypatch.setattr(embedding_models, "list_embedding_models", fake_list)+ _activate(env)+ response = env.client.get("/api/ultrawiki/models/embedding")+ assert response.status_code == 200, response.text+ body = response.json()+ assert set(body) >= {+ "provider",+ "current_model",+ "models",+ "source",+ "fetched_at",+ "selects",+ }+ assert body["provider"] == "gemini"+ assert body["current_model"] == "fake-embed"+ assert body["models"] == [{"id": "bge-m3", "label": "bge-m3"}]+ assert body["selects"] == "model"+++def test_slot_models_are_empty_but_honest_before_a_provider_is_picked(env) -> None:+ response = env.client.get("/api/ultrawiki/models/embedding")+ assert response.status_code == 200+ body = response.json()+ assert body["models"] == []+ assert "no provider" in body["reason"]+++def test_a_vendor_reranker_offers_no_model_choice(env) -> None:+ """Voyage and Cohere pin their own cross-encoder; an empty picker is right."""+ response = env.client.get("/api/ultrawiki/models/rerank?provider=cohere")+ assert response.status_code == 200+ body = response.json()+ assert body["models"] == []+ assert "fixed model" in body["reason"]+++def test_an_unknown_slot_is_a_404(env) -> None:+ assert env.client.get("/api/ultrawiki/models/storage").status_code == 404+ assert env.client.get("/api/ultrawiki/models/nonsense").status_code == 404+++def test_a_dead_model_catalog_degrades_instead_of_500ing(env, monkeypatch) -> None:+ """A settings screen must render even when a provider catalog is down."""+ import jarvis.ui.web.provider_routes as provider_routes++ def boom(_request):+ raise RuntimeError("catalog exploded")++ monkeypatch.setattr(provider_routes, "_get_model_catalog", boom)+ response = env.client.get("/api/ultrawiki/models/distill?provider=gemini")+ assert response.status_code == 200+ body = response.json()+ assert body["models"] == []+ assert "RuntimeError" in body["reason"]