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(wiki): explain the maintenance run and give the settings card a real model picker
Ruben Lütkee791141c8546
diff --git a/jarvis/ui/web/frontend/src/__tests__/i18n.test.ts b/jarvis/ui/web/frontend/src/__tests__/i18n.test.tsindex 0b4255aa19..b36ceec1d6 100644--- a/jarvis/ui/web/frontend/src/__tests__/i18n.test.ts+++ b/jarvis/ui/web/frontend/src/__tests__/i18n.test.ts@@ -33,6 +33,30 @@ describe("locale completeness (raw-key bug guard)", () => {}});+describe("wiki_provider namespace parity (all locales share the same keys)", () => {+ const keysFor = (loc: unknown) =>+ Object.keys((loc as { wiki_provider?: Record<string, string> }).wiki_provider ?? {}).sort();+ const reference = keysFor(en);++ it("en: has a non-empty wiki_provider namespace", () => {+ expect(reference.length).toBeGreaterThan(0);+ });++ for (const [name, loc] of Object.entries(LOCALES)) {+ it(`${name}: wiki_provider keys match en exactly`, () => {+ expect(keysFor(loc)).toEqual(reference);+ });++ it(`${name}: every wiki_provider value is a non-empty string`, () => {+ const ns = (loc as { wiki_provider?: Record<string, unknown> }).wiki_provider ?? {};+ for (const [key, value] of Object.entries(ns)) {+ expect(typeof value, `${name}.wiki_provider.${key}`).toBe("string");+ expect((value as string).trim().length, `${name}.wiki_provider.${key}`).toBeGreaterThan(0);+ }+ });+ }+});+describe("settings_view languages group (folded-in section)", () => {for (const [name, loc] of Object.entries(LOCALES)) {it(`${name}: has a languages group title for the Settings panel`, () => {diff --git a/jarvis/ui/web/frontend/src/hooks/useWikiProvider.ts b/jarvis/ui/web/frontend/src/hooks/useWikiProvider.tsindex 2ade45f22c..185ee4cd97 100644--- a/jarvis/ui/web/frontend/src/hooks/useWikiProvider.ts+++ b/jarvis/ui/web/frontend/src/hooks/useWikiProvider.ts@@ -14,12 +14,33 @@ import { useCallback, useEffect, useState } from "react";export interface WikiProviderOption {provider: string;models: string[];+ /** "agent" = OAuth-CLI Jarvis-Agent provider (Codex/Antigravity), "api" otherwise. */+ kind?: "api" | "agent";+ /** Whether the wiki fallback chain sees a usable credential for this provider. */+ ready?: boolean;+}++/**+ * What the NEXT maintenance run will actually use — resolved by the backend+ * through the same helper the runtime uses, so this is fact, not a guess.+ * `ready: false` means the key-aware chain will cross to another provider.+ */+export interface WikiResolvedState {+ provider: string;+ model: string;+ ready: boolean;}export interface WikiProviderState {provider: string;model: string;available: WikiProviderOption[];+ resolved?: WikiResolvedState;+ brain_primary?: string;+ // PUT-only echo fields (the save response reuses this shape).+ persisted?: boolean;+ applied_live?: boolean;+ restart_required?: boolean;}const ENDPOINT = "/api/settings/wiki-provider";diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex c5cfe8849c..52c7c49310 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -960,6 +960,13 @@"guide_realtime_body": "OpenAI: GPT Realtime (der Anbieter-Standard) klingt am natürlichsten; GPT Realtime Mini ist die günstige Wahl. Google: Gemini 3.1 Flash Live ist das aktuelle Live-Flaggschiff. „Anbieter-Standard“ löst immer auf das empfohlene Modell auf — du kannst es einfach so lassen.","guide_computer_use_title": "Welcher Provider soll das Tool Model antreiben?","guide_computer_use_body": "Das Tool Model übernimmt jede Aktion, die Jarvis für dich ausführt — auch Computer-Use, das Screenshots deines Bildschirms liest und deshalb ein Modell braucht, das Bilder versteht; die Auswahl blendet reine Text-Modelle aus. Im Zweifel: beim Haupt-Brain-Provider und seinem Standard-Modell bleiben.",+ "reco_title": "Persönliche Empfehlung",+ "reco_realtime_pick": "OpenAI Realtime",+ "reco_realtime_why": "Gemini Live ist genauso in Ordnung, beides funktioniert.",+ "reco_computer_use_pick": "Gemini 3.5 Flash",+ "reco_computer_use_why": "die schnellste Latenz für Tool-Aufrufe.",+ "reco_subagents_pick": "ChatGPT- oder Claude-Max-Subscription",+ "reco_subagents_why": "Flatrate für schwere Hintergrundarbeit.","mode_status_unknown": "Der Engine-Status ist noch nicht geladen - der Schalter wird frei, sobald das Backend antwortet. Bleibt das so, starte die App neu."},"apikeys_test": {@@ -1496,7 +1503,19 @@"apply": "Übernehmen","applying": "Übernehme…","loading": "Wiki-Einstellungen werden geladen…",- "load_error": "Konnte die Wiki-Provider-Einstellungen nicht laden."+ "load_error": "Konnte die Wiki-Provider-Einstellungen nicht laden.",+ "how_title": "Wie funktioniert das?",+ "how_intro": "Jarvis pflegt sein Langzeitgedächtnis automatisch. Jeder Pflege-Lauf hat drei Schritte:",+ "how_step1": "Mitlesen: Während jedes Gesprächs liest ein günstiges Modell still mit und notiert Fakten-Kandidaten, die es sich zu merken lohnt (Vorlieben, Namen, Projekte, Termine).",+ "how_step2": "Abgleichen: Ein Richter-Durchgang vergleicht jeden Kandidaten mit den vorhandenen Wiki-Seiten und entscheidet: neue Seite anlegen, bestehende aktualisieren oder verwerfen.",+ "how_step3": "Nachlesen: Am Ende einer Live-Sprachsitzung wird das komplette Transkript noch einmal durchgesehen, damit nichts verloren geht.",+ "how_model_note": "Alle Schritte laufen über den Provider und das Modell, die du hier wählst — wählst du z. B. Codex, führt wirklich Codex den Lauf aus. Leer gelassen übernimmt der Brain-Provider mit seinem günstigen, schnellen Modell. Ist der gewählte Provider gerade nicht erreichbar, springt automatisch ein anderer eingerichteter Provider ein, damit das Gedächtnis weiterläuft.",+ "option_agent_suffix": "Jarvis-Agent",+ "option_no_key": "kein Schlüssel hinterlegt",+ "model_reset": "Zurück auf den günstigen Standard",+ "resolved_label": "Nächster Lauf verwendet:",+ "provider_default_model": "Provider-Standard",+ "resolved_fallback_warning": "Für diesen Provider sind keine Zugangsdaten hinterlegt — der Lauf weicht automatisch auf einen anderen eingerichteten Provider aus."},"subagent_model": {"description": "Jarvis-Agents (schwere Hintergrund-Worker) können auf einem eigenen Modell laufen, getrennt vom Chat-Brain. Lass das Feld leer, um das stärkste Modell des aktiven Jarvis-Agent-Providers zu nutzen.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex f7c00b9c77..f45b9aeebe 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -961,6 +961,13 @@"guide_realtime_body": "OpenAI: GPT Realtime (the provider default) sounds the most natural; GPT Realtime Mini is the budget pick. Google: Gemini 3.1 Flash Live is the current Live flagship. \"Provider default\" always resolves to the recommended model, so you can simply leave it.","guide_computer_use_title": "Which provider should power the Tool Model?","guide_computer_use_body": "The Tool Model handles every action Jarvis takes for you — including Computer-Use, which reads screenshots of your screen, so it needs a model that understands images; the picker hides text-only models. If unsure, keep your main Brain provider and its default model.",+ "reco_title": "Personal recommendation",+ "reco_realtime_pick": "OpenAI Realtime",+ "reco_realtime_why": "Gemini Live is fine too, either works.",+ "reco_computer_use_pick": "Gemini 3.5 Flash",+ "reco_computer_use_why": "the snappiest tool latency.",+ "reco_subagents_pick": "ChatGPT or Claude Max subscription",+ "reco_subagents_why": "flat rate for heavy background work.","mode_status_unknown": "Engine status has not loaded yet - the switch unlocks as soon as the backend answers. If this persists, restart the app."},"apikeys_test": {@@ -1497,7 +1504,19 @@"apply": "Apply","applying": "Applying…","loading": "Loading Wiki settings…",- "load_error": "Could not load the Wiki provider settings."+ "load_error": "Could not load the Wiki provider settings.",+ "how_title": "How does this work?",+ "how_intro": "Jarvis maintains its long-term memory automatically. Every maintenance run has three steps:",+ "how_step1": "Read along: during every conversation a cheap model silently reads along and notes candidate facts worth remembering (preferences, names, projects, dates).",+ "how_step2": "Reconcile: a judge pass compares each candidate against the existing wiki pages and decides: create a new page, update an existing one, or discard.",+ "how_step3": "Sweep: when a live voice session ends, the full transcript is reviewed once more so nothing slips through.",+ "how_model_note": "Every step runs on the provider and model you pick here — pick Codex, and Codex really performs the run. Left empty, the brain's provider takes over with its cheap, fast model. If the chosen provider is unreachable, another configured provider steps in automatically so memory keeps working.",+ "option_agent_suffix": "Jarvis-Agent",+ "option_no_key": "no key configured",+ "model_reset": "Back to the cheap default",+ "resolved_label": "Next run uses:",+ "provider_default_model": "provider default",+ "resolved_fallback_warning": "No credentials are configured for this provider — the run automatically falls back to another configured provider."},"subagent_model": {"description": "Jarvis-Agents (heavy background workers) can run on their own model, separate from the chat brain. Leave the field empty to use the active Jarvis-Agent provider's strongest model.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 620dd6b78c..37c60bd657 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -960,6 +960,13 @@"guide_realtime_body": "OpenAI: GPT Realtime (el predeterminado del proveedor) suena más natural; GPT Realtime Mini es la opción económica. Google: Gemini 3.1 Flash Live es el buque insignia actual de Live. «Predeterminado del proveedor» siempre resuelve al modelo recomendado, así que puedes dejarlo tal cual.","guide_computer_use_title": "¿Qué proveedor debería impulsar el Tool Model?","guide_computer_use_body": "El Tool Model se encarga de cada acción que Jarvis realiza por ti — incluido Computer-Use, que lee capturas de tu pantalla y necesita un modelo que entienda imágenes; el selector oculta los modelos de solo texto. En caso de duda, quédate con tu proveedor Brain principal y su modelo predeterminado.",+ "reco_title": "Recomendación personal",+ "reco_realtime_pick": "OpenAI Realtime",+ "reco_realtime_why": "Gemini Live también vale, cualquiera funciona.",+ "reco_computer_use_pick": "Gemini 3.5 Flash",+ "reco_computer_use_why": "la latencia más rápida para herramientas.",+ "reco_subagents_pick": "Suscripción de ChatGPT o Claude Max",+ "reco_subagents_why": "tarifa plana para el trabajo pesado en segundo plano.","mode_status_unknown": "El estado del motor aún no se ha cargado: el selector se desbloquea en cuanto el backend responda. Si persiste, reinicia la aplicación."},"apikeys_test": {@@ -1496,7 +1503,19 @@"apply": "Aplicar","applying": "Aplicando…","loading": "Cargando ajustes del Wiki…",- "load_error": "No se pudieron cargar los ajustes del proveedor del Wiki."+ "load_error": "No se pudieron cargar los ajustes del proveedor del Wiki.",+ "how_title": "¿Cómo funciona?",+ "how_intro": "Jarvis mantiene su memoria a largo plazo automáticamente. Cada pasada de mantenimiento tiene tres pasos:",+ "how_step1": "Leer: durante cada conversación, un modelo económico lee en silencio y anota hechos candidatos que vale la pena recordar (preferencias, nombres, proyectos, fechas).",+ "how_step2": "Conciliar: una pasada de juez compara cada candidato con las páginas existentes del wiki y decide: crear una página nueva, actualizar una existente o descartar.",+ "how_step3": "Repasar: al terminar una sesión de voz en vivo, se revisa una vez más la transcripción completa para que nada se pierda.",+ "how_model_note": "Cada paso usa el proveedor y el modelo que elijas aquí — si eliges Codex, es realmente Codex quien ejecuta la pasada. Si lo dejas vacío, el proveedor del cerebro toma el relevo con su modelo rápido y económico. Si el proveedor elegido no está disponible, otro proveedor configurado entra automáticamente para que la memoria siga funcionando.",+ "option_agent_suffix": "Jarvis-Agent",+ "option_no_key": "sin clave configurada",+ "model_reset": "Volver al predeterminado barato",+ "resolved_label": "La próxima pasada usará:",+ "provider_default_model": "predeterminado del proveedor",+ "resolved_fallback_warning": "No hay credenciales configuradas para este proveedor — la pasada recurre automáticamente a otro proveedor configurado."},"subagent_model": {"description": "Los Jarvis-Agents (workers pesados en segundo plano) pueden ejecutarse con su propio modelo, separado de la IA del chat. Deja el campo vacío para usar el modelo más potente del proveedor de Jarvis-Agents activo.",diff --git a/jarvis/ui/web/frontend/src/views/settings/WikiProviderCard.test.tsx b/jarvis/ui/web/frontend/src/views/settings/WikiProviderCard.test.tsxindex 71d7bc8355..0f4f29fd58 100644--- a/jarvis/ui/web/frontend/src/views/settings/WikiProviderCard.test.tsx+++ b/jarvis/ui/web/frontend/src/views/settings/WikiProviderCard.test.tsx@@ -1,4 +1,4 @@-import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";import { afterEach, describe, expect, it, vi } from "vitest";// Identity translator so rendered text equals the i18n key (assert keys exactly).@@ -14,28 +14,92 @@ vi.mock("@/store/events", () => ({import { WikiProviderCard } from "./WikiProviderCard";-// Object-shape fixture per the canonical backend (Task 2): `available` is a list-// of { provider, models[] } objects, NOT bare strings.+// Object-shape fixture per the canonical backend: `available` rows carry+// {provider, models[], kind, ready}; `resolved` states what the next run uses.const INITIAL = {provider: "",model: "",available: [- { provider: "gemini", models: ["gemini-3-flash-preview", "gemini-3.1-pro-preview"] },- { provider: "openai", models: ["gpt-5.5"] },+ {+ provider: "gemini",+ models: ["gemini-3-flash-preview", "gemini-3.1-pro-preview"],+ kind: "api",+ ready: true,+ },+ { provider: "openai", models: ["gpt-5.5"], kind: "api", ready: false },+ { provider: "codex", models: [], kind: "agent", ready: true },],+ resolved: { provider: "gemini", model: "gemini-3-flash-preview", ready: true },+ brain_primary: "gemini",};+// Per-provider live catalog served to BrainModelSelector (the model picker).+const CATALOGS: Record<string, { id: string; label: string }[]> = {+ gemini: [+ { id: "gemini-3-flash-preview", label: "Gemini 3 Flash" },+ { id: "gemini-3.1-pro-preview", label: "Gemini 3.1 Pro" },+ ],+ codex: [+ { id: "gpt-5.6-sol", label: "GPT-5.6 Sol" },+ { id: "gpt-5.5", label: "GPT-5.5" },+ ],+};++/**+ * URL-routing fetch stub: settings GET/PUT + the per-provider model catalog.+ * Returns the mock so tests can inspect recorded calls.+ */+function stubFetch(overrides?: { state?: typeof INITIAL; putBody?: object }) {+ const state = overrides?.state ?? INITIAL;+ const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {+ if (url === "/api/settings/wiki-provider") {+ if (init?.method === "PUT") {+ const sent = JSON.parse(init.body as string);+ return {+ ok: true,+ json: async () =>+ overrides?.putBody ?? {+ ...state,+ provider: sent.provider,+ model: sent.model,+ persisted: true,+ applied_live: true,+ restart_required: false,+ },+ };+ }+ return { ok: true, json: async () => state };+ }+ const catalog = url.match(/^\/api\/providers\/([^/]+)\/models/);+ if (catalog) {+ const id = decodeURIComponent(catalog[1]);+ return {+ ok: true,+ json: async () => ({+ provider: id,+ current_model: "",+ models: CATALOGS[id] ?? [],+ source: "curated",+ fetched_at: 0,+ selects: "model",+ }),+ };+ }+ throw new Error(`unexpected fetch: ${url}`);+ });+ vi.stubGlobal("fetch", fetchMock);+ return fetchMock;+}+afterEach(() => {cleanup();vi.restoreAllMocks();+ vi.unstubAllGlobals();});describe("WikiProviderCard", () => {it("renders the Wiki tier label and the provider select once loaded", async () => {- vi.stubGlobal(- "fetch",- vi.fn().mockResolvedValue({ ok: true, json: async () => INITIAL }),- );+ stubFetch();render(<WikiProviderCard />);expect(screen.getByText("wiki_provider.tier_label")).toBeDefined();@@ -55,61 +119,98 @@ describe("WikiProviderCard", () => {expect(screen.queryByLabelText("wiki_provider.provider_label")).toBeNull();});- it("repopulates the model options from the chosen provider", async () => {- vi.stubGlobal(- "fetch",- vi.fn().mockResolvedValue({ ok: true, json: async () => INITIAL }),- );+ it("shows the how-it-works explainer with all three steps", async () => {+ stubFetch();+ render(<WikiProviderCard />);++ await screen.findByText("wiki_provider.how_title");+ expect(screen.getByText("wiki_provider.how_step1")).toBeDefined();+ expect(screen.getByText("wiki_provider.how_step2")).toBeDefined();+ expect(screen.getByText("wiki_provider.how_step3")).toBeDefined();+ expect(screen.getByText("wiki_provider.how_model_note")).toBeDefined();+ });++ it("shows what the next run actually uses (resolved line)", async () => {+ stubFetch();+ render(<WikiProviderCard />);++ await screen.findByText("wiki_provider.resolved_label");+ expect(screen.getByText(/gemini · gemini-3-flash-preview/)).toBeDefined();+ });++ it("warns when the resolved provider has no credentials", async () => {+ stubFetch({+ state: {+ ...INITIAL,+ provider: "openai",+ resolved: { provider: "openai", model: "gpt-5.5", ready: false },+ },+ });+ render(<WikiProviderCard />);++ await screen.findByText("wiki_provider.resolved_fallback_warning");+ });++ it("labels agent providers and keyless providers in the dropdown", async () => {+ stubFetch();+ render(<WikiProviderCard />);++ await screen.findByLabelText("wiki_provider.provider_label");+ expect(+ screen.getByText("codex — wiki_provider.option_agent_suffix"),+ ).toBeDefined();+ expect(+ screen.getByText("openai (wiki_provider.option_no_key)"),+ ).toBeDefined();+ });++ it('renders NO model dropdown while the provider is "same as brain"', async () => {+ stubFetch();+ render(<WikiProviderCard />);++ await screen.findByLabelText("wiki_provider.provider_label");+ // Static text instead of a pointless one-option dropdown.+ expect(screen.getByText("wiki_provider.model_follow_primary")).toBeDefined();+ expect(screen.queryByLabelText("apikeys_model.model_label")).toBeNull();+ });++ it("opens the catalog picker for a concrete provider and saves the pick", async () => {+ const fetchMock = stubFetch();render(<WikiProviderCard />);const providerSelect = (await screen.findByLabelText("wiki_provider.provider_label",)) as HTMLSelectElement;- const modelSelect = screen.getByLabelText(- "wiki_provider.model_label",- ) as HTMLSelectElement;- // "Same as brain" provider → only the cheap-default model option.- expect(within(modelSelect).queryByText("gemini-3-flash-preview")).toBeNull();+ // Picking codex mounts the shared model picker fed by codex's catalog.+ fireEvent.change(providerSelect, { target: { value: "codex" } });+ const trigger = await screen.findByLabelText("apikeys_model.model_label");+ fireEvent.click(trigger);- // Picking gemini surfaces gemini's models; openai's stay hidden.- fireEvent.change(providerSelect, { target: { value: "gemini" } });- expect(within(modelSelect).getByText("gemini-3-flash-preview")).toBeDefined();- expect(within(modelSelect).getByText("gemini-3.1-pro-preview")).toBeDefined();- expect(within(modelSelect).queryByText("gpt-5.5")).toBeNull();-- // Switching to openai swaps the model options.- fireEvent.change(providerSelect, { target: { value: "openai" } });- expect(within(modelSelect).getByText("gpt-5.5")).toBeDefined();- expect(within(modelSelect).queryByText("gemini-3-flash-preview")).toBeNull();- });+ // Codex's real lineup appears (the old tier-default list was empty).+ const row = await screen.findByText("GPT-5.6 Sol");+ fireEvent.click(row);- it("sends a PUT with the chosen provider and model when Apply is clicked", async () => {- const applied = {- provider: "gemini",- model: "gemini-3.1-pro-preview",- available: INITIAL.available,- };- const fetchMock = vi- .fn()- // GET on mount- .mockResolvedValueOnce({ ok: true, json: async () => INITIAL })- // PUT on Apply- .mockResolvedValueOnce({ ok: true, json: async () => applied })- // refetch() GET after a successful Apply- .mockResolvedValueOnce({ ok: true, json: async () => applied });- vi.stubGlobal("fetch", fetchMock);+ await waitFor(() => {+ const put = fetchMock.mock.calls.find(([, opts]) => opts?.method === "PUT");+ expect(put).toBeTruthy();+ expect(put?.[0]).toBe("/api/settings/wiki-provider");+ expect(JSON.parse(put?.[1]?.body as string)).toMatchObject({+ provider: "codex",+ model: "gpt-5.6-sol",+ });+ });+ });+ it("sends a PUT with the chosen provider when Apply is clicked", async () => {+ const fetchMock = stubFetch();render(<WikiProviderCard />);+const providerSelect = (await screen.findByLabelText("wiki_provider.provider_label",)) as HTMLSelectElement;- const modelSelect = screen.getByLabelText(- "wiki_provider.model_label",- ) as HTMLSelectElement;fireEvent.change(providerSelect, { target: { value: "gemini" } });- fireEvent.change(modelSelect, { target: { value: "gemini-3.1-pro-preview" } });fireEvent.click(screen.getByRole("button", { name: "wiki_provider.apply" }));await waitFor(() => {@@ -118,7 +219,26 @@ describe("WikiProviderCard", () => {expect(put?.[0]).toBe("/api/settings/wiki-provider");expect(JSON.parse(put?.[1]?.body as string)).toMatchObject({provider: "gemini",- model: "gemini-3.1-pro-preview",+ model: "",+ });+ });+ });++ it("offers a reset back to the cheap default when a model is pinned", async () => {+ const fetchMock = stubFetch({+ state: { ...INITIAL, provider: "gemini", model: "gemini-3.1-pro-preview" },+ });+ render(<WikiProviderCard />);++ const reset = await screen.findByText("wiki_provider.model_reset");+ fireEvent.click(reset);++ await waitFor(() => {+ const put = fetchMock.mock.calls.find(([, opts]) => opts?.method === "PUT");+ expect(put).toBeTruthy();+ expect(JSON.parse(put?.[1]?.body as string)).toMatchObject({+ provider: "gemini",+ model: "",});});});diff --git a/jarvis/ui/web/frontend/src/views/settings/WikiProviderCard.tsx b/jarvis/ui/web/frontend/src/views/settings/WikiProviderCard.tsxindex bbfda3f13f..c39bccb468 100644--- a/jarvis/ui/web/frontend/src/views/settings/WikiProviderCard.tsx+++ b/jarvis/ui/web/frontend/src/views/settings/WikiProviderCard.tsx@@ -1,7 +1,9 @@import { useState } from "react";-import { BookOpen, Loader2 } from "lucide-react";+import { BookOpen, ChevronDown, Info, Loader2 } from "lucide-react";import { Button } from "@/components/ui/button";import { cn } from "@/lib/utils";+import { BrainModelSelector } from "@/components/BrainModelSelector";+import type { BrainModelSaveResult } from "@/hooks/useProviders";import { saveWikiProvider, useWikiProvider } from "@/hooks/useWikiProvider";import { useEventStore } from "@/store/events";import { useT } from "@/i18n";@@ -15,13 +17,20 @@ const FOLLOW_PRIMARY = "";/*** "Wiki" tier card in the API-Keys & Providers screen. Lets the user pick the* dedicated Wiki-curator provider + (optional) model via- * `GET/PUT /api/settings/wiki-provider`. The endpoint exposes `available` as a- * list of `{ provider, models[] }` objects, so the provider `<select>` is fed by- * the provider ids and the model `<select>` is fed by the chosen provider's- * `models[]` plus a leading "Same as brain (cheap default)" option. An empty- * provider/model is intentional and means "follow brain.primary" / "use the- * cheap-fast model of the chosen provider" (the ack-brain follow_brain pattern),- * so both fields are optional and surfaced as the "Same as brain" option.+ * `GET/PUT /api/settings/wiki-provider`.+ *+ * The provider `<select>` is fed by the endpoint's `available` matrix (agent+ * providers such as Codex are labelled, keyless ones flagged). The model pick+ * uses the shared searchable {@link BrainModelSelector} against the chosen+ * provider's live catalog (`GET /api/providers/{id}/models`) — the same picker+ * the Jarvis-Agent model pin uses, so e.g. Codex offers its real model lineup+ * instead of an empty tier-default list. Picking a model saves provider+model+ * in one PUT; the Apply button remains for provider-only changes.+ *+ * An empty provider/model is intentional and means "follow brain.primary" /+ * "use the cheap-fast model of the chosen provider". The `resolved` line below+ * the pickers states what the NEXT maintenance run will actually use (resolved+ * server-side by the same helper the runtime uses).*/export function WikiProviderCard() {const t = useT();@@ -36,26 +45,54 @@ export function WikiProviderCard() {const providerValue = provider ?? data?.provider ?? FOLLOW_PRIMARY;const modelValue = model ?? data?.model ?? FOLLOW_PRIMARY;- // Model options come from the chosen provider's `models[]`. When the provider- // is "Same as brain" (empty), there is no concrete model list to pin, so only- // the cheap-default option is offered.- const modelOptions =- data?.available.find((p) => p.provider === providerValue)?.models ?? [];+ // Shared save path: provider+model always travel together in one PUT, so the+ // Apply button, the model picker, and the reset link can never disagree.+ async function applySelection(nextProvider: string, nextModel: string) {+ const next = await saveWikiProvider(nextProvider, nextModel);+ // Reset local edits so the inputs re-sync to the server-resolved state.+ setProvider(null);+ setModel(null);+ void refetch();+ return next;+ }async function handleApply() {setPending(true);try {- const next = await saveWikiProvider(providerValue, modelValue);- // Reset local edits so the inputs re-sync to the server-resolved state.- setProvider(null);- setModel(null);+ const next = await applySelection(providerValue, modelValue);pushToast("success",next.provider? `Wiki → ${next.provider}${next.model ? ` · ${next.model}` : ""}`: t("wiki_provider.follow_primary"),);- void refetch();+ } catch (e) {+ pushToast("error", (e as Error).message);+ } finally {+ setPending(false);+ }+ }++ // The model picker saves immediately (same UX as the Jarvis-Agent model pin):+ // returning the save result lets BrainModelSelector render its own toast.+ async function handleModelSave(m: string): Promise<BrainModelSaveResult> {+ const next = await applySelection(providerValue, m);+ return {+ ok: true,+ provider: next.provider,+ model: next.model,+ persisted: next.persisted ?? true,+ applied_live: next.applied_live ?? true,+ restart_required: next.restart_required ?? false,+ probe: null,+ };+ }++ async function handleModelReset() {+ setPending(true);+ try {+ await applySelection(providerValue, FOLLOW_PRIMARY);+ pushToast("success", t("wiki_provider.model_follow_primary"));} catch (e) {pushToast("error", (e as Error).message);} finally {@@ -71,6 +108,15 @@ export function WikiProviderCard() {setModel(FOLLOW_PRIMARY);}+ function providerOptionLabel(p: { provider: string; kind?: string; ready?: boolean }) {+ let label = p.provider;+ if (p.kind === "agent") label += ` — ${t("wiki_provider.option_agent_suffix")}`;+ if (p.ready === false) label += ` (${t("wiki_provider.option_no_key")})`;+ return label;+ }++ const resolved = data?.resolved;+return (<SettingsBlockicon={BookOpen}@@ -87,6 +133,24 @@ export function WikiProviderCard() {{!loading && data && (<div className="space-y-4">+ {/* "How does this work?" — native <details>, the app's collapsible idiom. */}+ <details className="group rounded-md border border-border/60 bg-muted/20 px-3 py-2">+ <summary className="flex cursor-pointer select-none list-none items-center gap-1.5 text-xs font-medium text-muted-foreground hover:text-foreground [&::-webkit-details-marker]:hidden">+ <Info className="h-3.5 w-3.5 shrink-0" />+ {t("wiki_provider.how_title")}+ <ChevronDown className="h-3 w-3 shrink-0 transition-transform group-open:rotate-180" />+ </summary>+ <div className="mt-2 space-y-1.5 text-xs leading-relaxed text-muted-foreground">+ <p>{t("wiki_provider.how_intro")}</p>+ <ol className="list-decimal space-y-1 pl-4">+ <li>{t("wiki_provider.how_step1")}</li>+ <li>{t("wiki_provider.how_step2")}</li>+ <li>{t("wiki_provider.how_step3")}</li>+ </ol>+ <p>{t("wiki_provider.how_model_note")}</p>+ </div>+ </details>+<div className="grid gap-4 sm:grid-cols-2"><SettingsField label={t("wiki_provider.provider_label")}><select@@ -100,29 +164,63 @@ export function WikiProviderCard() {.filter((p) => p.provider !== FOLLOW_PRIMARY).map((p) => (<option key={p.provider} value={p.provider}>- {p.provider}+ {providerOptionLabel(p)}</option>))}</select></SettingsField>- <SettingsField label={t("wiki_provider.model_label")}>- <select- aria-label={t("wiki_provider.model_label")}- value={modelValue}- onChange={(e) => setModel(e.target.value)}- className={cn(settingsInputCls, "font-mono")}- >- <option value={FOLLOW_PRIMARY}>{t("wiki_provider.model_follow_primary")}</option>- {modelOptions.map((m) => (- <option key={m} value={m}>- {m}- </option>- ))}- </select>- </SettingsField>+ {providerValue === FOLLOW_PRIMARY ? (+ // No concrete provider → there is no model list to pick from, so+ // no dead dropdown: a static line states what "empty" means.+ <SettingsField label={t("wiki_provider.model_label")}>+ <div className={cn(settingsInputCls, "flex items-center text-muted-foreground")}>+ {t("wiki_provider.model_follow_primary")}+ </div>+ </SettingsField>+ ) : (+ <div className="space-y-1.5">+ <BrainModelSelector+ providerId={providerValue}+ controlled+ currentModel={modelValue}+ headingLabel={t("wiki_provider.model_label")}+ placeholder={t("wiki_provider.model_follow_primary")}+ onSave={handleModelSave}+ />+ {modelValue !== FOLLOW_PRIMARY && (+ <button+ type="button"+ onClick={() => void handleModelReset()}+ disabled={pending}+ className="text-[11px] text-muted-foreground underline-offset-2 hover:text-foreground hover:underline"+ >+ {t("wiki_provider.model_reset")}+ </button>+ )}+ </div>+ )}</div>+ {/* Honest ground truth: what the next maintenance run will actually use. */}+ {resolved && resolved.provider && (+ <div className="space-y-1">+ <p className="text-[11px] text-muted-foreground">+ {t("wiki_provider.resolved_label")}{" "}+ <span className="font-mono text-foreground/80">+ {resolved.provider}+ {" · "}+ {resolved.model || t("wiki_provider.provider_default_model")}+ </span>+ </p>+ {resolved.ready === false && (+ <p className="text-[11px] text-amber-500">+ {t("wiki_provider.resolved_fallback_warning")}+ </p>+ )}+ </div>+ )}+<p className="text-[11px] text-muted-foreground">{t("wiki_provider.model_hint")}</p>diff --git a/jarvis/ui/web/settings_routes.py b/jarvis/ui/web/settings_routes.pyindex 7ece3d8dfa..8e8e2b3b1b 100644--- a/jarvis/ui/web/settings_routes.py+++ b/jarvis/ui/web/settings_routes.py@@ -1905,6 +1905,23 @@ def _wiki_curator_cfg(request: Request) -> WikiCuratorConfig | None:return getattr(wiki, "curator", None)+def _wiki_ready_providers(request: Request, names: set[str]) -> set[str]:+ """Providers the wiki fallback chain treats as credential-ready.++ Mirrors the runtime chain's own eligibility check+ (``credential_ready_wiki_providers``), so the UI's "ready" flag can never+ disagree with what a maintenance run will actually do. Fail-open: a probe+ error must not break the settings page (the chain is fail-open too).+ """+ try:+ from jarvis.memory.wiki.provider_chain import credential_ready_wiki_providers++ return credential_ready_wiki_providers(available=names, config=_config(request))+ except Exception: # noqa: BLE001+ log.debug("wiki provider readiness probe failed", exc_info=True)+ return set(names)++def _available_brain_providers(request: Request) -> list[dict[str, object]]:"""Selectable (provider, models) pairs for the Wiki picker.@@ -1913,8 +1930,16 @@ def _available_brain_providers(request: Request) -> list[dict[str, object]]:Each provider lists its cheap router model first, then its deep model, sothe UI can offer "cheap default" plus an upgrade. The provider's own[brain.providers.<name>].model override (if set) is surfaced too.++ Each row also carries ``kind`` ("agent" for the OAuth-CLI Jarvis-Agent+ providers such as Codex/Antigravity, "api" otherwise) and ``ready``+ (whether the wiki chain sees a usable credential), so the picker can label+ agent providers and warn about keyless ones. The frontend fetches the full+ per-provider model catalog separately via GET /api/providers/{id}/models;+ ``models`` here stays the small tier-default list for older consumers."""from jarvis.brain.manager import TIER_DEFAULTS_BY_PROVIDER+ from jarvis.ui.web.provider_spec import get_specnames: list[str] = []brain = getattr(request.app.state, "brain", None)@@ -1928,6 +1953,7 @@ def _available_brain_providers(request: Request) -> list[dict[str, object]]:cfg = _config(request)providers_cfg = getattr(getattr(cfg, "brain", None), "providers", {}) or {}+ ready = _wiki_ready_providers(request, set(names))out: list[dict[str, object]] = []for name in names:@@ -1941,10 +1967,49 @@ def _available_brain_providers(request: Request) -> list[dict[str, object]]:override = getattr(providers_cfg.get(name), "model", "") if providers_cfg else ""if override and override not in models:models.insert(0, override)- out.append({"provider": name, "models": models})+ spec = get_spec(name)+ kind = (+ "agent"+ if getattr(spec, "auth_mode", "") in ("codex", "antigravity")+ else "api"+ )+ out.append(+ {"provider": name, "models": models, "kind": kind, "ready": name in ready}+ )return out+def _wiki_resolved_state(request: Request) -> dict[str, object]:+ """What the NEXT wiki maintenance run will actually use.++ Resolves through the SAME helper the runtime uses+ (``curator_llm._resolve_provider_and_model``: provider "" → brain.primary,+ model "" → that provider's cheap router-tier model), so the UI line "next+ run uses X · Y" is a statement of fact, not a guess. ``ready`` mirrors the+ chain's credential check — False means the key-aware fallback will cross to+ another provider instead of running the configured one.+ """+ cfg = _config(request)+ curator = _wiki_curator_cfg(request)+ provider = ""+ model = ""+ try:+ from jarvis.memory.wiki.curator_llm import _resolve_provider_and_model++ if curator is not None and cfg is not None:+ resolved_provider, resolved_model = _resolve_provider_and_model(curator, cfg)+ provider = resolved_provider or ""+ model = resolved_model or ""+ except Exception: # noqa: BLE001 — degrade to the raw config pair, never 500+ log.debug("wiki resolved-state helper failed", exc_info=True)+ provider = (getattr(curator, "provider", "") or "").strip() or getattr(+ getattr(cfg, "brain", None), "primary", ""+ )+ model = (getattr(curator, "model", "") or "").strip()+ ready = bool(provider) and provider in _wiki_ready_providers(request, {provider})+ return {"provider": provider, "model": model, "ready": ready}++@router.get("/wiki-provider")async def get_wiki_provider(request: Request) -> dict[str, object]:"""Current Wiki-curator provider/model + the selectable matrix.@@ -1955,10 +2020,17 @@ async def get_wiki_provider(request: Request) -> dict[str, object]:pin."""curator = _wiki_curator_cfg(request)+ # Credential probes walk keyring/env/.env — keep them off the event loop.+ available, resolved = await asyncio.to_thread(+ lambda: (_available_brain_providers(request), _wiki_resolved_state(request))+ )+ cfg = _config(request)return {"provider": getattr(curator, "provider", "") or "","model": getattr(curator, "model", "") or "",- "available": _available_brain_providers(request),+ "available": available,+ "resolved": resolved,+ "brain_primary": getattr(getattr(cfg, "brain", None), "primary", "") or "",}@@ -1969,7 +2041,8 @@ async def put_wiki_provider(body: WikiProviderBody, request: Request) -> dict[st# Resolve the selectable matrix ONCE: reused for validation below and for# the response body (avoids a second BrainManager round-trip per PUT).- available = _available_brain_providers(request)+ # Off-thread: the readiness column probes keyring/env credentials.+ available = await asyncio.to_thread(_available_brain_providers, request)# Validate the provider against the selectable matrix. An empty provider is# valid and means "follow brain.primary" (resolved later by the curator).@@ -2033,11 +2106,17 @@ async def put_wiki_provider(body: WikiProviderBody, request: Request) -> dict[stexcept Exception as exc: # noqa: BLE001 — never fail the save on a live hiccuplog.warning("wiki-provider live-apply failed (persisted; applies next ingest): %s", exc)+ # Recompute AFTER the in-memory update so the response reflects the pick+ # the way the next maintenance run will actually resolve it.+ resolved = await asyncio.to_thread(_wiki_resolved_state, request)+ cfg = _config(request)return {"ok": True,"provider": provider,"model": model,"available": available,+ "resolved": resolved,+ "brain_primary": getattr(getattr(cfg, "brain", None), "primary", "") or "","persisted": persisted,"applied_live": applied_live,# The curator re-resolves on the next ingest; when not live-applied itdiff --git a/tests/integration/test_wiki_provider_route.py b/tests/integration/test_wiki_provider_route.pyindex 440fc31d37..b5440bdd73 100644--- a/tests/integration/test_wiki_provider_route.py+++ b/tests/integration/test_wiki_provider_route.py@@ -96,6 +96,42 @@ def test_get_returns_current_config_and_available(server: WebServer) -> None:# Cheap/fast router model is listed first for each provider.gemini = next(r for r in body["available"] if r["provider"] == "gemini")assert gemini["models"][0] == "gemini-3-flash-preview"+ # Every row carries the picker metadata: kind (api|agent) + readiness.+ for row in body["available"]:+ assert row["kind"] in ("api", "agent")+ assert isinstance(row["ready"], bool)+ assert gemini["kind"] == "api"+++def test_get_reports_what_the_next_run_actually_uses(server: WebServer) -> None:+ """`resolved` mirrors curator_llm._resolve_provider_and_model, not a guess."""+ with TestClient(server.app) as client:+ resp = client.get("/api/settings/wiki-provider")+ assert resp.status_code == 200+ body = resp.json()+ cfg = server.app.state.config+ # Fresh config (provider="") → the next run follows brain.primary.+ assert body["brain_primary"] == cfg.brain.primary+ resolved = body["resolved"]+ assert resolved["provider"] == cfg.brain.primary+ # Model resolves to the provider's cheap router default (a concrete id+ # or "" when the provider has none); readiness is env-dependent → bool.+ assert isinstance(resolved["model"], str)+ assert isinstance(resolved["ready"], bool)+++def test_put_response_resolves_the_new_pick(server: WebServer) -> None:+ """After a PUT the resolved block reflects the just-saved pair."""+ with TestClient(server.app) as client:+ resp = client.put(+ "/api/settings/wiki-provider",+ json={"provider": "grok", "model": "grok-4.3"},+ )+ assert resp.status_code == 200+ resolved = resp.json()["resolved"]+ assert resolved["provider"] == "grok"+ # An explicit model always wins over the cheap router default.+ assert resolved["model"] == "grok-4.3"def test_put_persists_by_default(