Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(providers): base-url editing + honest local provider test

Ruben Lütkeb4ce830b8d94
diff --git a/jarvis/brain/provider_test.py b/jarvis/brain/provider_test.py
index 6884aa400a..220b14dff6 100644
--- a/jarvis/brain/provider_test.py
+++ b/jarvis/brain/provider_test.py
@@ -100,11 +100,15 @@ _BILLING_MARKERS = BILLING_LIMIT_MARKERS
# "No key stored" shapes from the plugins' own _ensure_client guards.
_MISSING_KEY_MARKERS = (
- ("kein", "gefunden"), # "Kein OpenAI-API-Key gefunden ..."
+ ("kein", "gefunden"), # i18n-allow: legacy German key-error shape
("no api key",), # "No API key found ..."
("no key found",),
("not configured",),
("missing api key",),
+ # Local OpenAI-compatible provider without a configured server URL —
+ # "enter the address on the card", the same actionable amber as a
+ # missing key (see jarvis/plugins/brain/local_openai.py).
+ ("needs a server url",),
)
# Reachability failures (no HTTP status code present).
@@ -118,6 +122,16 @@ _UNREACHABLE_MARKERS = (
"network",
"econnrefused",
"name or service not known",
+ # Local providers phrase it honestly ("Ollama not reachable at … — is it
+ # running?"); the classifier must land on UNREACHABLE, not a red ERROR.
+ "not reachable",
+)
+
+# A reachable LOCAL server with nothing to run — the fix is a pull/load, not
+# a key or a network check (see the local brain plugins' error texts).
+_NO_LOCAL_MODEL_MARKERS = (
+ "no models installed",
+ "lists no models",
)
@@ -160,6 +174,10 @@ def classify_provider_error(message: str | None) -> str:
return UNREACHABLE
# No HTTP status code in the message.
+ if any(m in msg for m in _NO_LOCAL_MODEL_MARKERS):
+ # Reachable local server, nothing loaded — "pull a model", not an
+ # integration bug and not a connectivity problem.
+ return MODEL_UNAVAILABLE
if any(m in msg for m in _UNREACHABLE_MARKERS):
return UNREACHABLE
if _has_billing(msg):
diff --git a/jarvis/core/config_writer.py b/jarvis/core/config_writer.py
index ecdff5ff9e..7413baf470 100644
--- a/jarvis/core/config_writer.py
+++ b/jarvis/core/config_writer.py
@@ -1477,6 +1477,62 @@ def set_brain_provider_model(
)
+def set_provider_base_url(
+ provider: str, base_url: str | None, *, path: Path = DEFAULT_CONFIG_FILE
+) -> None:
+ """Persist (or clear) ``[brain.providers.<provider>].base_url``.
+
+ Backs the API-Keys card's server-URL field for local/self-hosted providers
+ (``PUT /api/providers/{id}/base-url``). ``None``/"" writes an EMPTY string
+ rather than deleting the key — "" is falsy everywhere the override is read
+ (``resolve_provider_endpoint``), and keeping the key present means the
+ drift-soll layer and the TOML always agree (BUG-010 class). Same atomic
+ discipline as every setter here (AP-7); tomlkit quotes hyphenated provider
+ ids (``[brain.providers."local-openai"]``) on its own.
+ """
+ path = _ensure_writable_config_path(path)
+ cleaned = (base_url or "").strip()
+
+ with _WRITE_LOCK:
+ raw = path.read_text(encoding="utf-8")
+ had_bom = raw.startswith(_BOM)
+ if had_bom:
+ raw = raw[len(_BOM) :]
+ doc: TOMLDocument = tomlkit.parse(raw)
+
+ brain = doc.get("brain")
+ if brain is None:
+ brain = tomlkit.table()
+ doc["brain"] = brain
+ providers = brain.get("providers")
+ if providers is None:
+ # Super-table flag via the factory (see set_brain_provider_model).
+ providers = tomlkit.table(True)
+ brain["providers"] = providers
+ block = providers.get(provider)
+ if block is None:
+ block = tomlkit.table()
+ providers[provider] = block
+ block["base_url"] = cleaned
+
+ out = tomlkit.dumps(doc)
+ if had_bom:
+ out = _BOM + out
+ _atomic_write(path, out)
+
+ # Best-effort drift-soll sync (never raises, never blocks the TOML write).
+ try:
+ _update_config_soll_section( # i18n-allow
+ f"brain.providers.{provider}", {"base_url": cleaned}
+ )
+ except Exception as exc: # noqa: BLE001 — best-effort, must not propagate
+ log.warning(
+ "Could not sync brain.providers.%s base_url to config-soll.json: %s", # i18n-allow
+ provider,
+ exc,
+ )
+
+
def set_telephony_config(values: dict[str, object], *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Patch ``[integrations.twilio]`` with the given non-secret fields.
diff --git a/jarvis/ui/web/frontend/src/hooks/useProviders.ts b/jarvis/ui/web/frontend/src/hooks/useProviders.ts
index 435c7ef122..5e3c22b886 100644
--- a/jarvis/ui/web/frontend/src/hooks/useProviders.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useProviders.ts
@@ -65,6 +65,13 @@ export interface ProviderDescriptor {
caution?: string | null;
/** Gemini's Vertex alternative; null for single-path providers. */
alt_credential: AltCredential | null;
+ /** Local/self-hosted cards: whether the card exposes an editable server URL
+ * (persisted via PUT /api/providers/{id}/base-url). */
+ supports_base_url?: boolean;
+ /** Placeholder while no override is stored; null = the user must set one. */
+ default_base_url?: string | null;
+ /** The stored server-URL override; null = the vendor default is in effect. */
+ base_url?: string | null;
/**
* Codex only: legacy credential readiness kept in /api/providers for older
* UI consumers. The current UI does not render Codex as a switchable Brain;
@@ -421,6 +428,26 @@ export async function deleteSecret(key: string): Promise<void> {
}
}
+export async function saveProviderBaseUrl(
+ providerId: string,
+ baseUrl: string | null,
+): Promise<string | null> {
+ const res = await fetch(
+ `/api/providers/${encodeURIComponent(providerId)}/base-url`,
+ {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ base_url: baseUrl }),
+ },
+ );
+ if (!res.ok) {
+ const detail = await res.json().catch(() => ({}));
+ throw new Error(detail?.detail ?? `base-url ${res.status}`);
+ }
+ const data = (await res.json()) as { base_url: string | null };
+ return data.base_url ?? null;
+}
+
export async function startCodexLogin(): Promise<void> {
const res = await fetch("/api/codex/login", { method: "POST" });
const body = await res.json().catch(() => ({}));
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index b211fdae33..0dfce1453c 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -75,7 +75,8 @@
"taskbar": "Taskbar",
"contacts": "Kontakte",
"feedback": "Feedback",
- "agent_instructions": "{name}.md"
+ "agent_instructions": "{name}.md",
+ "agentic_ide": "Agentic IDE"
},
"agent_instructions": {
"subtitle": "Deine persönlichen Präferenzen, wie der Assistent mit dir arbeitet — Ton, Sprache, Voreinstellungen, dauerhafte Fakten. Getrennt vom System-Prompt und hebelt niemals Sicherheit oder Bestätigungen aus.",
@@ -1004,6 +1005,16 @@
"integration_bad_note": "Provider konnte nicht erreicht werden.",
"failed": "Test fehlgeschlagen"
},
+ "apikeys_base_url": {
+ "label": "Server-URL",
+ "placeholder_required": "z. B. http://localhost:8000 — erforderlich",
+ "save": "Speichern",
+ "saving": "Speichere…",
+ "saved": "Server-URL gespeichert",
+ "cleared": "Server-URL auf den Standard zurückgesetzt",
+ "hint_default": "Leer lassen, um die oben gezeigte Standard-Adresse zu verwenden.",
+ "hint_required": "Dieser Anbieter braucht eine Server-URL — trage ein, wo dein lokaler Server läuft."
+ },
"apikeys_model": {
"heading": "Modell",
"recommended_tag": "Empfohlen",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index a7f18595ba..e9a684963c 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -75,7 +75,8 @@
"taskbar": "Taskbar",
"contacts": "Contacts",
"feedback": "Feedback",
- "agent_instructions": "{name}.md"
+ "agent_instructions": "{name}.md",
+ "agentic_ide": "Agentic IDE"
},
"agent_instructions": {
"subtitle": "Your personal preferences for how the assistant works with you — tone, language, defaults, standing facts. Separate from the System Prompt, and it never overrides safety or confirmations.",
@@ -1005,6 +1006,16 @@
"integration_bad_note": "The provider could not be reached.",
"failed": "Test failed"
},
+ "apikeys_base_url": {
+ "label": "Server URL",
+ "placeholder_required": "e.g. http://localhost:8000 — required",
+ "save": "Save",
+ "saving": "Saving…",
+ "saved": "Server URL saved",
+ "cleared": "Server URL reset to the default",
+ "hint_default": "Leave empty to use the default address shown above.",
+ "hint_required": "This provider needs a server URL — enter where your local server runs."
+ },
"apikeys_model": {
"heading": "Model",
"recommended_tag": "Recommended",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index 76c2a6d6a7..f916696adb 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -1005,6 +1005,16 @@
"integration_bad_note": "No se pudo contactar al proveedor.",
"failed": "Prueba fallida"
},
+ "apikeys_base_url": {
+ "label": "URL del servidor",
+ "placeholder_required": "p. ej. http://localhost:8000 — obligatorio",
+ "save": "Guardar",
+ "saving": "Guardando…",
+ "saved": "URL del servidor guardada",
+ "cleared": "URL del servidor restablecida al valor predeterminado",
+ "hint_default": "Déjalo vacío para usar la dirección predeterminada mostrada arriba.",
+ "hint_required": "Este proveedor necesita una URL de servidor: indica dónde se ejecuta tu servidor local."
+ },
"apikeys_model": {
"heading": "Modelo",
"recommended_tag": "Recomendado",
diff --git a/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx b/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx
index 1363f37444..919a489387 100644
--- a/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx
+++ b/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx
@@ -24,6 +24,7 @@ import {
type ProviderTestStatus,
type ProviderTier,
type SectionHealth,
+ saveProviderBaseUrl,
sectionHealthForSubject,
startCodexLogin,
switchBrainProvider,
@@ -1727,6 +1728,77 @@ function ActiveControl({
);
}
+function BaseUrlField({
+ descriptor,
+ onChanged,
+}: {
+ descriptor: ProviderDescriptor;
+ onChanged: () => void;
+}) {
+ const t = useT();
+ const pushToast = useEventStore((s) => s.pushToast);
+ const [value, setValue] = useState(descriptor.base_url ?? "");
+ const [saving, setSaving] = useState(false);
+
+ // Follow refetches (e.g. after another card action) without clobbering an
+ // in-flight edit: only resync while the user is not mid-save.
+ useEffect(() => {
+ setValue(descriptor.base_url ?? "");
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [descriptor.base_url]);
+
+ const dirty = value.trim() !== (descriptor.base_url ?? "");
+
+ async function save() {
+ setSaving(true);
+ try {
+ const stored = await saveProviderBaseUrl(descriptor.id, value.trim() || null);
+ setValue(stored ?? "");
+ pushToast(
+ "success",
+ stored ? t("apikeys_base_url.saved") : t("apikeys_base_url.cleared"),
+ );
+ onChanged();
+ } catch (e) {
+ pushToast("error", e instanceof Error ? e.message : String(e));
+ } finally {
+ setSaving(false);
+ }
+ }
+
+ return (
+ <div className="space-y-1">
+ <label className="text-[10px] uppercase tracking-wider text-muted-foreground">
+ {t("apikeys_base_url.label")}
+ </label>
+ <div className="flex gap-2">
+ <input
+ type="url"
+ value={value}
+ onChange={(e) => setValue(e.target.value)}
+ placeholder={
+ descriptor.default_base_url ?? t("apikeys_base_url.placeholder_required")
+ }
+ className="h-8 w-full rounded-md border border-border bg-background px-2 text-xs"
+ />
+ <Button
+ size="sm"
+ variant="secondary"
+ onClick={save}
+ disabled={saving || !dirty}
+ >
+ {saving ? t("apikeys_base_url.saving") : t("apikeys_base_url.save")}
+ </Button>
+ </div>
+ <p className="text-[11px] leading-relaxed text-muted-foreground">
+ {descriptor.default_base_url
+ ? t("apikeys_base_url.hint_default")
+ : t("apikeys_base_url.hint_required")}
+ </p>
+ </div>
+ );
+}
+
function AuthWidget({
descriptor,
onChanged,
@@ -1739,10 +1811,30 @@ function AuthWidget({
return (
<div className="space-y-2">
<ProviderBillingBadge billing={descriptor.billing} />
+ {descriptor.supports_base_url && (
+ <BaseUrlField descriptor={descriptor} onChanged={onChanged} />
+ )}
{descriptor.auth_mode === "none" && (
- <p className="text-xs text-muted-foreground">
- Local provider — no credentials needed.
- </p>
+ <>
+ <p className="text-xs text-muted-foreground">
+ {descriptor.secret_keys.length > 0
+ ? "Local provider — runs without credentials. The key below is optional, only for servers that enforce one (e.g. vLLM --api-key)."
+ : "Local provider — no credentials needed."}
+ </p>
+ {descriptor.secret_keys.map((k) => (
+ <ApiKeyForm
+ key={k}
+ secretKey={k}
+ dashboardUrl={descriptor.dashboard_url}
+ configured={Boolean(descriptor.secrets_set[k])}
+ effectiveConfigured={Boolean(descriptor.secrets_effective?.[k])}
+ sharedWith={descriptor.secret_shared_with?.[k] ?? []}
+ credentialHelp={descriptor.credential_help}
+ onChanged={onChanged}
+ onSavedActivate={onSavedActivate}
+ />
+ ))}
+ </>
)}
{descriptor.auth_mode === "codex" && (
<CodexAuthWidget descriptor={descriptor} onChanged={onChanged} />
diff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.py
index 53d75b74ea..249bab145b 100644
--- a/jarvis/ui/web/provider_routes.py
+++ b/jarvis/ui/web/provider_routes.py
@@ -287,6 +287,22 @@ def _codex_brain_usable() -> bool:
return False
+def _stored_base_url(spec: ProviderSpec) -> str | None:
+ """The persisted ``[brain.providers.<id>].base_url`` override, or ``None``.
+
+ Only read for cards that expose the URL field; "" (the cleared state the
+ writer leaves behind) reports as ``None`` so the UI shows the placeholder.
+ """
+ if not spec.supports_base_url:
+ return None
+ try:
+ prov = cfg_mod.load_config().brain.providers.get(spec.id)
+ except Exception: # noqa: BLE001 — a card list must never 500 on config trouble
+ return None
+ value = (getattr(prov, "base_url", None) or "").strip()
+ return value or None
+
+
def _spec_to_payload(
spec: ProviderSpec,
*,
@@ -366,6 +382,11 @@ def _spec_to_payload(
"credential_help": spec.credential_help,
"signup_url": spec.signup_url,
"billing": provider_billing(spec),
+ # Local/self-hosted cards: editable server URL
+ # (PUT /providers/{id}/base-url); None base_url = vendor default.
+ "supports_base_url": spec.supports_base_url,
+ "default_base_url": spec.default_base_url,
+ "base_url": _stored_base_url(spec),
# Maintainer-recommended pick for this tier (UI badge) + the model it
# points at. Presentation only — never gates behavior (AP-21).
"recommended": spec.recommended,
@@ -1626,6 +1647,56 @@ async def set_brain_model(
return _apply_stt_model(provider_id, value, body, request)
+class BaseUrlBody(BaseModel):
+ # None or "" clears the override → back to the vendor default.
+ base_url: str | None = Field(default=None, max_length=500)
+
+
+class BaseUrlResponse(BaseModel):
+ ok: bool = True
+ provider: str
+ base_url: str | None
+ default_base_url: str | None
+
+
[email protected]("/providers/{provider_id}/base-url")
+async def set_provider_base_url(provider_id: str, body: BaseUrlBody) -> BaseUrlResponse:
+ """Set (or clear) the server URL of a local/self-hosted provider.
+
+ Only cards with ``supports_base_url`` accept one (400 otherwise). The URL
+ is normalized to a bare server root (a pasted ``…/v1`` suffix is stripped,
+ ``0.0.0.0`` maps to localhost) and persisted atomically to
+ ``[brain.providers.<id>].base_url``; clearing falls back to the vendor
+ default (ollama: OLLAMA_HOST → http://localhost:11434).
+ """
+ spec = get_spec(provider_id)
+ if spec is None:
+ raise HTTPException(status_code=404, detail=f"Unknown provider: {provider_id}")
+ if not spec.supports_base_url:
+ raise HTTPException(
+ status_code=400,
+ detail=f"'{provider_id}' does not accept a server URL.",
+ )
+ cleaned = (body.base_url or "").strip()
+ if cleaned:
+ if not cleaned.lower().startswith(("http://", "https://")):
+ raise HTTPException(
+ status_code=422,
+ detail="The server URL must start with http:// or https://.",
+ )
+ from jarvis.plugins.brain.ollama import normalize_server_root
+
+ cleaned = normalize_server_root(cleaned)
+ from jarvis.core import config_writer
+
+ config_writer.set_provider_base_url(provider_id, cleaned or None)
+ return BaseUrlResponse(
+ provider=provider_id,
+ base_url=cleaned or None,
+ default_base_url=spec.default_base_url,
+ )
+
+
@router.get("/providers/{provider_id}/cu-model")
async def get_cu_model(provider_id: str, request: Request) -> CuModelResponse:
"""Return the per-provider Computer-Use model selection (Phase 3).
diff --git a/jarvis/ui/web/provider_spec.py b/jarvis/ui/web/provider_spec.py
index 20dd486d37..cb29bdc9b6 100644
--- a/jarvis/ui/web/provider_spec.py
+++ b/jarvis/ui/web/provider_spec.py
@@ -78,6 +78,14 @@ class ProviderSpec:
# behavior (AP-21). Set on NVIDIA NIM: the free dev tier's 10-30s+ TTFB makes
# it sluggish as a main/voice brain. ``None`` = no caution.
caution: str | None = None
+ # Local/self-hosted providers: the card exposes an editable server URL
+ # (persisted as ``[brain.providers.<id>].base_url`` via
+ # ``PUT /api/providers/{id}/base-url``). ``default_base_url`` is the
+ # placeholder shown while no override is stored — ``None`` with
+ # ``supports_base_url=True`` means the user MUST set one (local-openai:
+ # no guessable default port).
+ supports_base_url: bool = False
+ default_base_url: str | None = None
def provider_billing(spec: ProviderSpec) -> Billing:
@@ -276,6 +284,8 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
dashboard_url=None,
install_hint="ollama pull qwen3.5",
signup_url="https://ollama.com/download",
+ supports_base_url=True,
+ default_base_url="http://localhost:11434",
credential_help=(
"Runs models fully local through an Ollama server — no API key, "
"no cloud account, nothing leaves this machine. Install Ollama, "
@@ -284,6 +294,24 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
"the server URL at another machine to share one Ollama box."
),
),
+ ProviderSpec(
+ id="local-openai",
+ label="Local server (OpenAI-compatible)",
+ tier="brain",
+ auth_mode="none",
+ secret_keys=("local_openai_api_key",),
+ dashboard_url=None,
+ signup_url="https://huggingface.co/docs/transformers/main/serving",
+ credential_help=(
+ "Any self-hosted server that speaks the OpenAI chat format: "
+ "HuggingFace transformers serve (http://localhost:8000), llama.cpp "
+ "llama-server (http://localhost:8080), LM Studio "
+ "(http://localhost:1234), vLLM, or an existing TGI. Set the server "
+ "URL on this card — no cloud account, nothing leaves your network. "
+ "The API key is optional; most local servers ignore it."
+ ),
+ supports_base_url=True,
+ ),
# ── TTS ───────────────────────────────────────────────────────────────
# Voice-Output cards render in this tuple order. OpenRouter leads (one key
# reaches many vetted speech models); Inworld sits last as a premium
diff --git a/tests/unit/brain/test_provider_test.py b/tests/unit/brain/test_provider_test.py
index 4efd6ae78d..ca6c95ca78 100644
--- a/tests/unit/brain/test_provider_test.py
+++ b/tests/unit/brain/test_provider_test.py
@@ -132,6 +132,45 @@ def test_timeout_is_unreachable() -> None:
assert classify_provider_error("timeout after 25.0s") == "unreachable"
+def test_local_server_not_reachable_is_unreachable() -> None:
+ """The local brains phrase connectivity honestly ("… not reachable at … —
+ is it running?"); that must read as unreachable, and the port number must
+ never be mistaken for an HTTP status code."""
+ msg = (
+ "RuntimeError: Ollama not reachable at http://localhost:11434 — is it "
+ "running? Start it (or install from https://ollama.com/download), then retry."
+ )
+ assert classify_provider_error(msg) == "unreachable"
+
+
+def test_local_server_without_models_is_model_unavailable() -> None:
+ """Reachable local server, nothing pulled — the fix is `ollama pull`, so
+ the chip must say model-unavailable, not integration error."""
+ msg = (
+ "RuntimeError: Ollama at http://localhost:11434 has no models installed "
+ "— run: ollama pull qwen3.5, then retry."
+ )
+ assert classify_provider_error(msg) == "model_unavailable"
+
+
+def test_local_openai_empty_model_list_is_model_unavailable() -> None:
+ msg = (
+ "RuntimeError: The server at http://localhost:8000 lists no models "
+ "(/v1/models is empty) — load a model in the server, or set one explicitly."
+ )
+ assert classify_provider_error(msg) == "model_unavailable"
+
+
+def test_local_openai_missing_base_url_is_not_configured() -> None:
+ """No server URL on the card = the local analogue of "no key set" — an
+ actionable amber, never a red integration error."""
+ msg = (
+ "RuntimeError: The local OpenAI-compatible provider needs a server URL "
+ "— set it on the provider card."
+ )
+ assert classify_provider_error(msg) == "not_configured"
+
+
def test_unknown_error_is_error() -> None:
assert classify_provider_error("ValueError: something structurally broke") == "error"
diff --git a/tests/unit/ui/web/test_provider_base_url_routes.py b/tests/unit/ui/web/test_provider_base_url_routes.py
new file mode 100644
index 0000000000..8cb9f20c54
--- /dev/null
+++ b/tests/unit/ui/web/test_provider_base_url_routes.py
@@ -0,0 +1,144 @@
+"""PUT /api/providers/{id}/base-url + the base-url card payload fields.
+
+The server-URL field is what makes a local provider reconfigurable IN-APP
+(§3: never by hand-editing jarvis.toml). Pins: normalization to a bare server
+root, honest 400/404/422 refusals, the payload triple
+(supports_base_url / default_base_url / base_url), and the atomic TOML write.
+"""
+
+from __future__ import annotations
+
+import pytest
+import tomlkit
+from fastapi.testclient import TestClient
+
+from jarvis.core.bus import EventBus
+from jarvis.core.config import JarvisConfig
+from jarvis.ui.web.server import WebServer
+
+
+def server() -> WebServer:
+ cfg = JarvisConfig()
+ cfg.ui.dev_mode = True
+ srv = WebServer(cfg, bus=EventBus())
+ srv.app.state.config = cfg
+ return srv
+
+
+def recorded_writes(monkeypatch: pytest.MonkeyPatch) -> list[tuple[str, str | None]]:
+ calls: list[tuple[str, str | None]] = []
+
+ def _record(provider: str, base_url: str | None, **kwargs) -> None:
+ calls.append((provider, base_url))
+
+ monkeypatch.setattr("jarvis.core.config_writer.set_provider_base_url", _record)
+ return calls
+
+
+def test_put_normalizes_to_server_root(
+ server: WebServer, recorded_writes: list[tuple[str, str | None]]
+) -> None:
+ with TestClient(server.app) as client:
+ resp = client.put(
+ "/api/providers/ollama/base-url",
+ json={"base_url": "http://gpu.lan:11434/v1/"},
+ )
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["base_url"] == "http://gpu.lan:11434"
+ assert body["default_base_url"] == "http://localhost:11434"
+ assert recorded_writes == [("ollama", "http://gpu.lan:11434")]
+
+
+def test_put_clear_resets_to_vendor_default(
+ server: WebServer, recorded_writes: list[tuple[str, str | None]]
+) -> None:
+ with TestClient(server.app) as client:
+ resp = client.put("/api/providers/ollama/base-url", json={"base_url": None})
+ assert resp.status_code == 200
+ assert resp.json()["base_url"] is None
+ assert recorded_writes == [("ollama", None)]
+
+
+def test_put_rejects_non_http_scheme(
+ server: WebServer, recorded_writes: list[tuple[str, str | None]]
+) -> None:
+ with TestClient(server.app) as client:
+ resp = client.put("/api/providers/local-openai/base-url", json={"base_url": "ftp://nope"})
+ assert resp.status_code == 422
+ assert recorded_writes == []
+
+
+def test_put_refuses_cloud_provider(
+ server: WebServer, recorded_writes: list[tuple[str, str | None]]
+) -> None:
+ """Cloud cards keep their advanced [brain.providers.<id>].base_url override
+ (team proxy), but the CARD field is local-provider-only by design."""
+ with TestClient(server.app) as client:
+ resp = client.put("/api/providers/gemini/base-url", json={"base_url": "http://x:1"})
+ assert resp.status_code == 400
+ assert recorded_writes == []
+
+
+def test_put_unknown_provider_is_404(server: WebServer) -> None:
+ with TestClient(server.app) as client:
+ resp = client.put("/api/providers/does-not-exist/base-url", json={"base_url": "http://x:1"})
+ assert resp.status_code == 404
+
+
+def test_provider_payload_carries_base_url_fields(server: WebServer) -> None:
+ with TestClient(server.app) as client:
+ data = client.get("/api/providers").json()
+ items = data["providers"] if isinstance(data, dict) else data
+ by_id = {p["id"]: p for p in items}
+
+ ollama = by_id["ollama"]
+ assert ollama["supports_base_url"] is True
+ assert ollama["default_base_url"] == "http://localhost:11434"
+ assert ollama["base_url"] is None # no override stored in a fresh config
+
+ local = by_id["local-openai"]
+ assert local["supports_base_url"] is True
+ assert local["default_base_url"] is None # the user must set one
+
+ gemini = by_id["gemini"]
+ assert gemini["supports_base_url"] is False
+
+
+# ── The TOML writer itself (AP-7 discipline) ─────────────────────────────
+def test_set_provider_base_url_writes_quoted_table(tmp_path, monkeypatch) -> None:
+ from jarvis.core import config_writer
+
+ # Keep the best-effort drift-soll sync away from the real scripts/ file.
+ monkeypatch.setattr(config_writer, "_update_config_soll_section", lambda *a, **k: None)
+ toml_path = tmp_path / "jarvis.toml"
+ toml_path.write_text('[brain]\nprimary = "gemini"\n', encoding="utf-8")
+
+ config_writer.set_provider_base_url("local-openai", "http://localhost:8000", path=toml_path)
+ doc = tomlkit.parse(toml_path.read_text(encoding="utf-8"))
+ # Round-trip through the parser proves the hyphenated id serialized to a
+ # VALID table key (TOML bare keys allow dashes).
+ assert doc["brain"]["providers"]["local-openai"]["base_url"] == "http://localhost:8000"
+
+ # Clearing writes an empty string (falsy everywhere the override is read)
+ # instead of deleting the key, so TOML and drift-soll stay in agreement.
+ config_writer.set_provider_base_url("local-openai", None, path=toml_path)
+ doc = tomlkit.parse(toml_path.read_text(encoding="utf-8"))
+ assert doc["brain"]["providers"]["local-openai"]["base_url"] == ""
+
+
+def test_set_provider_base_url_preserves_bom(tmp_path, monkeypatch) -> None:
+ """BOM-safe like every writer here (AP-7 / BUG-018)."""
+ from jarvis.core import config_writer
+
+ monkeypatch.setattr(config_writer, "_update_config_soll_section", lambda *a, **k: None)
+ toml_path = tmp_path / "jarvis.toml"
+ toml_path.write_text('[brain]\nprimary = "gemini"\n', encoding="utf-8")
+
+ config_writer.set_provider_base_url("ollama", "http://gpu.lan:11434", path=toml_path)
+ raw = toml_path.read_text(encoding="utf-8")
+ assert raw.startswith("")
+ doc = tomlkit.parse(raw.lstrip(""))
+ assert doc["brain"]["providers"]["ollama"]["base_url"] == "http://gpu.lan:11434"