Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

fix(providers): keep the configured Ollama address on Add Provider and reset

purple0152721da5f0
diff --git a/src-tauri/src/commands/process.rs b/src-tauri/src/commands/process.rs
index db7ac086..91468c9d 100644
--- a/src-tauri/src/commands/process.rs
+++ b/src-tauri/src/commands/process.rs
@@ -3204,7 +3204,13 @@ fn get_ollama_host_blocking(state: &AppState) -> Result<serde_json::Value, Strin
.and_then(|u| u.host_str().map(|h| h.to_lowercase()))
.map(|h| matches!(h.as_str(), "localhost" | "127.0.0.1" | "::1" | "0.0.0.0"))
.unwrap_or(false);
- Ok(serde_json::json!({"base": base, "isLocal": is_local}))
+ // `defaultBase`: where "Reset AI Backends" points Ollama (OLLAMA_HOST,
+ // else the default), see state::ollama_default_base.
+ Ok(serde_json::json!({
+ "base": base,
+ "isLocal": is_local,
+ "defaultBase": crate::state::ollama_default_base(),
+ }))
}
/// Auto-start Ollama on app launch (called from setup)
diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rs
index 4adb3cf5..485cc049 100644
--- a/src-tauri/src/state.rs
+++ b/src-tauri/src/state.rs
@@ -175,52 +175,73 @@ pub(crate) fn load_comfy_config_values() -> (u16, String) {
(port, host)
}
+/// Normalise an Ollama address the way Ollama reads OLLAMA_HOST: bare
+/// `host:port`, scheme-less `host`, or full URL, returned as a full URL
+/// without trailing slash. Empty input gives the default.
+fn normalize_ollama_base(raw: &str) -> String {
+ let trimmed = raw.trim().trim_end_matches('/');
+ if trimmed.is_empty() {
+ "http://localhost:11434".to_string()
+ } else if trimmed.starts_with("http://") || trimmed.starts_with("https://") {
+ trimmed.to_string()
+ } else {
+ format!("http://{}", trimmed)
+ }
+}
+
+/// The address Ollama has when LU's own setting is left out: `OLLAMA_HOST`
+/// if set, else the default. This is what "Reset AI Backends to defaults"
+/// goes back to. config.json is skipped on purpose: it still holds the
+/// address the user is resetting away from, and a reset that kept it would
+/// not be one; a hard-coded port would point past a user's OLLAMA_HOST.
+fn env_or_default_ollama_base(env: Option<&str>) -> String {
+ normalize_ollama_base(env.unwrap_or(""))
+}
+
+pub(crate) fn ollama_default_base() -> String {
+ env_or_default_ollama_base(std::env::var("OLLAMA_HOST").ok().as_deref())
+}
+
/// Read persisted Ollama base URL with the following priority:
/// 1. `ollama_base` in config.json (GUI-configured)
/// 2. `OLLAMA_HOST` env var (Ollama's own convention)
/// 3. Default `http://localhost:11434`
///
-/// Accepts bare `host:port`, scheme-less `host`, or full URL — returns full
-/// URL without trailing slash. Matches Ollama's own OLLAMA_HOST semantics so
-/// setting it as an env var before launching LU "just works".
+/// Matches Ollama's own OLLAMA_HOST semantics so setting it as an env var
+/// before launching LU "just works".
pub(crate) fn load_ollama_base() -> String {
- let normalize = |raw: &str| -> String {
- let trimmed = raw.trim().trim_end_matches('/');
- if trimmed.is_empty() {
- "http://localhost:11434".to_string()
- } else if trimmed.starts_with("http://") || trimmed.starts_with("https://") {
- trimmed.to_string()
- } else {
- format!("http://{}", trimmed)
- }
- };
-
// Priority 1: config.json override (GUI takes precedence)
{
let config_file = crate::os_paths::app_config_json();
if let Ok(raw) = std::fs::read_to_string(&config_file) {
if let Ok(v) = serde_json::from_str::<serde_json::Value>(&raw) {
if let Some(b) = v.get("ollama_base").and_then(|x| x.as_str()) {
- let normalized = normalize(b);
- if !normalized.is_empty() {
- return normalized;
- }
+ return normalize_ollama_base(b);
}
}
}
}
- // Priority 2: OLLAMA_HOST env var — same semantics as Ollama itself.
- // Ollama docs explicitly document e.g. `OLLAMA_HOST=0.0.0.0:11434`.
- if let Ok(env) = std::env::var("OLLAMA_HOST") {
- let normalized = normalize(&env);
- if !normalized.is_empty() {
- return normalized;
- }
+ // Priority 2 and 3: OLLAMA_HOST env var, same semantics as Ollama
+ // itself (its docs show e.g. `OLLAMA_HOST=0.0.0.0:11434`), else default.
+ ollama_default_base()
+}
+
+#[cfg(test)]
+mod ollama_default_base_tests {
+ use super::env_or_default_ollama_base;
+
+ #[test]
+ fn reset_follows_ollama_host_and_never_a_fixed_port_when_it_is_set() {
+ assert_eq!(env_or_default_ollama_base(Some("127.0.0.1:18902")), "http://127.0.0.1:18902");
+ assert_eq!(env_or_default_ollama_base(Some("https://box.lan:9000/")), "https://box.lan:9000");
}
- // Priority 3: default
- "http://localhost:11434".to_string()
+ #[test]
+ fn reset_without_ollama_host_is_the_default() {
+ assert_eq!(env_or_default_ollama_base(None), "http://localhost:11434");
+ assert_eq!(env_or_default_ollama_base(Some(" ")), "http://localhost:11434");
+ }
}
pub struct AppState {
diff --git a/src/components/layout/AppShell.tsx b/src/components/layout/AppShell.tsx
index d3e46a85..82088cee 100644
--- a/src/components/layout/AppShell.tsx
+++ b/src/components/layout/AppShell.tsx
@@ -22,7 +22,7 @@ import {
import { useUIStore, readViewportWidth } from '../../stores/uiStore'
import { useSettingsStore } from '../../stores/settingsStore'
import { useCompareStore } from '../../stores/compareStore'
-import { useProviderStore } from '../../stores/providerStore'
+import { useProviderStore, rememberOllamaResetBase } from '../../stores/providerStore'
import { mayEnableFromWizard } from '../../lib/onboarding-provider-gate'
import { sameEndpoint } from '../../lib/openai-entries'
import { useChatStore } from '../../stores/chatStore'
@@ -815,7 +815,9 @@ export function AppShell() {
if (!cancelled) armSubscription()
try {
- const res = await backendCall<{ base?: string }>('get_ollama_host')
+ const res = await backendCall<{ base?: string; defaultBase?: string }>('get_ollama_host')
+ // Where "Reset AI Backends" points Ollama (OLLAMA_HOST, else default).
+ rememberOllamaResetBase(res?.defaultBase)
if (!cancelled && res?.base) {
setOllamaBase(res.base)
const current = useProviderStore.getState().providers.ollama?.baseUrl
diff --git a/src/components/settings/ProviderConfig.tsx b/src/components/settings/ProviderConfig.tsx
index 3dc0b8b3..c7bfdbf6 100644
--- a/src/components/settings/ProviderConfig.tsx
+++ b/src/components/settings/ProviderConfig.tsx
@@ -418,6 +418,12 @@ export function ProviderSettings() {
applyPreset(preset)
}
+ /** The address a preset row stands for: Ollama's is the configured one. */
+ function presetAddress(preset: typeof PROVIDER_PRESETS[0]): string {
+ if (preset.providerId === 'ollama') return providers.ollama?.baseUrl?.trim() || preset.baseUrl
+ return preset.baseUrl
+ }
+
function applyPreset(preset: typeof PROVIDER_PRESETS[0]) {
// GitHub #173: an OpenAI-compatible backend no longer has to push the one
// in the slot out. While the slot is on and serves something else, the
@@ -437,7 +443,11 @@ export function ProviderSettings() {
}
// Enable the selected provider WITHOUT disabling others
if (preset.providerId === 'ollama') {
- setProviderConfig('ollama', { enabled: true, baseUrl: preset.baseUrl })
+ // Jaeger B, B7: the slot already carries the address Rust resolved
+ // (config.json > OLLAMA_HOST) or the one typed in by hand. Picking
+ // Ollama turns it on there; the preset's localhost:11434 is only for
+ // a slot that has no address at all.
+ setProviderConfig('ollama', { enabled: true, baseUrl: presetAddress(preset) })
} else if (preset.providerId === 'anthropic') {
setProviderConfig('anthropic', { enabled: true, name: preset.name, baseUrl: preset.baseUrl, isLocal: false })
} else {
@@ -982,7 +992,7 @@ export function ProviderSettings() {
<span className="font-medium">{preset.name}</span>
{isActive && <span className="text-[0.5rem] text-green-700 dark:text-green-400">Active</span>}
</div>
- {preset.baseUrl && <span className="block text-[0.55rem] text-gray-500 font-mono">{preset.baseUrl}</span>}
+ {presetAddress(preset) && <span className="block text-[0.55rem] text-gray-500 font-mono">{presetAddress(preset)}</span>}
</button>
)
})}
@@ -1005,7 +1015,7 @@ export function ProviderSettings() {
<span className="font-medium">{preset.name}</span>
{isActive && <span className="text-[0.5rem] text-green-700 dark:text-green-400">Active</span>}
</div>
- {preset.baseUrl && <span className="block text-[0.55rem] text-gray-500 font-mono">{preset.baseUrl}</span>}
+ {presetAddress(preset) && <span className="block text-[0.55rem] text-gray-500 font-mono">{presetAddress(preset)}</span>}
</button>
)
})}
diff --git a/src/components/settings/__tests__/ollama-address-survives-add-and-reset.test.ts b/src/components/settings/__tests__/ollama-address-survives-add-and-reset.test.ts
new file mode 100644
index 00000000..b79023d5
--- /dev/null
+++ b/src/components/settings/__tests__/ollama-address-survives-add-and-reset.test.ts
@@ -0,0 +1,141 @@
+// @vitest-environment jsdom
+/**
+ * Jaeger B, B7: two buttons in Settings, AI Backends wrote Ollama's address
+ * back to a fixed http://localhost:11434 without a word.
+ *
+ * Add Provider: the list showed "Ollama, Active, http://localhost:11434"
+ * while the store held the real address, and a click on that row set the
+ * preset's 11434 as baseUrl, so the model list went away or came from a
+ * different Ollama. Reset AI Backends to defaults wrote the same fixed port,
+ * even with OLLAMA_HOST set.
+ *
+ * Expected: the list shows the configured address and picking the active
+ * Ollama keeps it; a reset goes to what Rust reports as `defaultBase`
+ * (OLLAMA_HOST, else the default), not to a hard-coded port and not to the
+ * custom address being reset away from.
+ *
+ * Nothing here talks to an Ollama: backend and providers are mocked.
+ *
+ * Run: npx vitest run src/components/settings/__tests__/ollama-address-survives-add-and-reset.test.ts
+ */
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import { createElement } from 'react'
+import { render, screen, cleanup, act, fireEvent } from '@testing-library/react'
+import type { ProviderConfig, ProviderId } from '../../../api/providers/types'
+
+const backend = vi.hoisted(() => ({ backendCall: vi.fn(async (..._a: unknown[]): Promise<unknown> => ({})) }))
+
+vi.mock('../../../api/in-tauri', () => ({ isTauri: () => true }))
+vi.mock('../../../api/backend', async () => {
+ const actual = await vi.importActual<typeof import('../../../api/backend')>('../../../api/backend')
+ return {
+ ...actual,
+ backendCall: backend.backendCall,
+ isTauri: () => true,
+ isMacOS: () => false,
+ openExternal: vi.fn(),
+ secretGet: vi.fn().mockRejectedValue(new Error('no keychain here')),
+ secretSet: vi.fn(),
+ secretDelete: vi.fn(),
+ secretParkGet: vi.fn().mockRejectedValue(new Error('keychain unavailable (web build)')),
+ secretParkSet: vi.fn().mockRejectedValue(new Error('keychain unavailable (web build)')),
+ secretParkDelete: vi.fn().mockRejectedValue(new Error('keychain unavailable (web build)')),
+ }
+})
+vi.mock('../../../api/builtin-ensure', () => ({
+ readBuiltinSlotStatus: vi.fn(async () => null),
+ diagnoseBuiltinEngine: vi.fn(async () => ({ ok: false, reason: '' })),
+}))
+vi.mock('../../../api/providers', async () => {
+ const actual = await vi.importActual<typeof import('../../../api/providers')>('../../../api/providers')
+ const client = { checkConnection: vi.fn(async () => true), listModels: vi.fn(async () => []) }
+ return { ...actual, getProvider: () => client, getOpenAIEntryProvider: () => client }
+})
+
+const { ProviderSettings } = await import('../ProviderConfig')
+const { useProviderStore } = await import('../../../stores/providerStore')
+const { syncOllamaBaseFromRust, resetOllamaBaseSyncForTests } = await import('../../../lib/ollama-host-sync')
+
+const CUSTOM = 'http://127.0.0.1:18903'
+const ENV = 'http://127.0.0.1:18902'
+
+const slot = (id: ProviderId, name: string, baseUrl: string, extra: Partial<ProviderConfig> = {}): ProviderConfig =>
+ ({ id, name, enabled: false, baseUrl, apiKey: '', isLocal: false, ...extra })
+
+function baseline(ollamaEnabled: boolean) {
+ useProviderStore.setState({
+ providers: {
+ ollama: slot('ollama', 'Ollama', CUSTOM, { enabled: ollamaEnabled, isLocal: true }),
+ openai: slot('openai', 'LM Studio', 'http://localhost:1234/v1', { enabled: true, isLocal: true, managed: false }),
+ anthropic: slot('anthropic', 'Anthropic', 'https://api.anthropic.com'),
+ 'lu-cloud': slot('lu-cloud', 'LU Cloud', 'https://lu-labs.ai/api/inference/v1'),
+ },
+ openaiEntries: [],
+ engineOptedOut: true,
+ })
+}
+
+async function open() {
+ render(createElement(ProviderSettings))
+ await act(async () => { await new Promise((r) => setTimeout(r, 0)) })
+}
+
+function ollamaRow(): HTMLButtonElement {
+ fireEvent.click(screen.getByText('Add Provider'))
+ const name = screen.getAllByText('Ollama').find((el) => el.closest('button')?.className.includes('text-left'))!
+ return name.closest('button') as HTMLButtonElement
+}
+
+beforeEach(() => {
+ resetOllamaBaseSyncForTests()
+ backend.backendCall.mockReset()
+ backend.backendCall.mockImplementation(async (cmd: unknown) => {
+ if (cmd === 'get_ollama_host') return { base: CUSTOM, defaultBase: ENV }
+ return {}
+ })
+})
+afterEach(cleanup)
+
+describe('Add Provider, Ollama', () => {
+ it('the list shows the configured address, not the preset 11434', async () => {
+ baseline(true)
+ await open()
+ const row = ollamaRow()
+ expect(row.textContent).toContain(CUSTOM)
+ expect(row.textContent).not.toContain('11434')
+ })
+
+ it('picking the active Ollama keeps its address', async () => {
+ baseline(true)
+ await open()
+ const row = ollamaRow()
+ await act(async () => { fireEvent.click(row); await new Promise((r) => setTimeout(r, 0)) })
+ expect(useProviderStore.getState().providers.ollama.baseUrl).toBe(CUSTOM)
+ expect(useProviderStore.getState().providers.ollama.enabled).toBe(true)
+ })
+
+ it('switching a disabled Ollama on keeps its address too', async () => {
+ baseline(false)
+ await open()
+ const row = ollamaRow()
+ await act(async () => { fireEvent.click(row); await new Promise((r) => setTimeout(r, 0)) })
+ expect(useProviderStore.getState().providers.ollama.baseUrl).toBe(CUSTOM)
+ expect(useProviderStore.getState().providers.ollama.enabled).toBe(true)
+ })
+})
+
+describe('Reset AI Backends to defaults', () => {
+ it('points Ollama at OLLAMA_HOST as Rust reports it, not at 11434 or the old custom address', async () => {
+ baseline(true)
+ await syncOllamaBaseFromRust()
+ useProviderStore.getState().resetProvidersToDefaults()
+ expect(useProviderStore.getState().providers.ollama.baseUrl).toBe(ENV)
+ })
+
+ it('a single-slot reset of Ollama does the same', async () => {
+ baseline(true)
+ await syncOllamaBaseFromRust()
+ useProviderStore.getState().resetProvider('ollama')
+ expect(useProviderStore.getState().providers.ollama.baseUrl).toBe(ENV)
+ })
+})
diff --git a/src/lib/ollama-host-sync.ts b/src/lib/ollama-host-sync.ts
index 2b8d4223..8885e292 100644
--- a/src/lib/ollama-host-sync.ts
+++ b/src/lib/ollama-host-sync.ts
@@ -24,7 +24,7 @@ let pending: Promise<void> | null = null
const RUST_TIMEOUT_MS = 3000
async function pull(): Promise<void> {
- const { useProviderStore } = await import('../stores/providerStore')
+ const { useProviderStore, rememberOllamaResetBase } = await import('../stores/providerStore')
// Erst nach der Hydrierung schreiben, sonst spielt `persist` den alten
// baseUrl aus localStorage darueber (siehe AppShell, Schritt 2).
@@ -41,9 +41,10 @@ async function pull(): Promise<void> {
// antwortet, darf die Modellliste nicht anhalten.
let timer: ReturnType<typeof setTimeout> | undefined
const res = await Promise.race([
- backendCall<{ base?: string }>('get_ollama_host'),
+ backendCall<{ base?: string; defaultBase?: string }>('get_ollama_host'),
new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error('timeout')), RUST_TIMEOUT_MS) }),
]).finally(() => clearTimeout(timer))
+ rememberOllamaResetBase(res?.defaultBase)
if (res?.base) {
setOllamaBase(res.base)
const current = useProviderStore.getState().providers.ollama?.baseUrl
diff --git a/src/stores/providerStore.ts b/src/stores/providerStore.ts
index 8f2888de..23688d21 100644
--- a/src/stores/providerStore.ts
+++ b/src/stores/providerStore.ts
@@ -154,6 +154,27 @@ const DEFAULT_PROVIDERS: Record<FixedProviderId, ProviderConfig> = {
},
}
+/**
+ * Where a reset points Ollama. Rust reports it with `get_ollama_host` as
+ * `defaultBase`: OLLAMA_HOST if set, else the default. config.json is not
+ * part of it, because that file still holds the address being reset away
+ * from. Until Rust has answered (or outside Tauri) it is the shipped default.
+ * Before this the reset wrote a fixed localhost:11434 even with OLLAMA_HOST
+ * set, and the store subscription then pinned that port in config.json.
+ */
+let ollamaResetBase = DEFAULT_PROVIDERS.ollama.baseUrl
+
+export function rememberOllamaResetBase(base: string | undefined | null): void {
+ const b = base?.trim().replace(/\/+$/, '')
+ if (b) ollamaResetBase = b
+}
+
+function shippedDefault(id: FixedProviderId): ProviderConfig {
+ return id === 'ollama'
+ ? { ...DEFAULT_PROVIDERS.ollama, baseUrl: ollamaResetBase }
+ : DEFAULT_PROVIDERS[id]
+}
+
/**
* The model/provider invariant, asked on EVERY path that can switch a slot off.
*
@@ -561,7 +582,7 @@ export const useProviderStore = create<ProviderState>()(
set((state) => ({
providers: {
...state.providers,
- [id]: DEFAULT_PROVIDERS[id],
+ [id]: shippedDefault(id),
},
}))
// Opus review, round 2, Blocker 7: DEFAULT_PROVIDERS.openai carries
@@ -594,7 +615,7 @@ export const useProviderStore = create<ProviderState>()(
}
for (const id of Object.keys(DEFAULT_PROVIDERS) as FixedProviderId[]) {
next[id] = {
- ...DEFAULT_PROVIDERS[id],
+ ...shippedDefault(id),
apiKey: state.providers[id]?.apiKey ?? '',
...(id === 'lu-cloud' ? { enabled: state.providers[id]?.enabled ?? false } : {}),
}