Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix: address review — degraded Ollama in custom routing, discovery timeout, URL binding test

shanudcaa0398f448
diff --git a/app/src/components/settings/panels/AIPanel.tsx b/app/src/components/settings/panels/AIPanel.tsx
index b062988918..324fdd1aad 100644
--- a/app/src/components/settings/panels/AIPanel.tsx
+++ b/app/src/components/settings/panels/AIPanel.tsx
@@ -390,7 +390,7 @@ const AIPanel = ({
initial={current}
cloudProviders={draft.cloudProviders}
localModels={installed}
- ollamaRunning={ollama.state === 'running'}
+ ollamaRunning={ollama.state === 'running' || ollama.state === 'degraded'}
modelRegistry={draft.modelRegistry}
onClose={() => setPickerFor(null)}
onSubmit={(next, vision) => {
diff --git a/src/openhuman/inference/embeddings/factory_tests.rs b/src/openhuman/inference/embeddings/factory_tests.rs
index 5f932860f9..6610afb062 100644
--- a/src/openhuman/inference/embeddings/factory_tests.rs
+++ b/src/openhuman/inference/embeddings/factory_tests.rs
@@ -102,16 +102,13 @@ fn config_aware_factory_builds_managed_provider() {
}
}
-/// #6032 regression: the config-aware factory must use
-/// `ollama_base_url_from_config` (config > env > default) for the `"ollama"`
-/// provider, not the env-only `ollama_base_url()`. A custom `local_ai.base_url`
-/// must therefore be reflected in the built provider's name — currently the
-/// name is always `"ollama"` regardless of URL, but the URL surfaces in the
-/// provider's `.base_url()` (via `EmbeddingProvider::base_url`). We probe the
-/// observable effect: building the provider succeeds and the default URL
-/// differs from the custom-URL build. The key invariant is that the factory
-/// arm IS config-aware and does NOT fall through to the credential-store path
-/// that ignores `config.local_ai.base_url`.
+/// #6032: both the config-URL and default-URL paths of the `"ollama"` arm must
+/// construct successfully. This is the build-side smoke check; the *binding*
+/// proof (that `config.local_ai.base_url` is the URL actually used) is
+/// [`config_aware_factory_ollama_embeds_against_config_base_url`] below —
+/// `create_embedding_provider_with_config` returns `Box<dyn EmbeddingProvider>`,
+/// whose trait surface is `name`/`model_id`/`dimensions`/`embed`, so there is
+/// no `base_url()` accessor to assert against here.
#[test]
fn config_aware_factory_ollama_honours_config_base_url() {
let tmp = TempDir::new().unwrap();
@@ -140,6 +137,61 @@ fn config_aware_factory_ollama_honours_config_base_url() {
assert_eq!(default_p.name(), "ollama");
}
+/// #6032 binding proof: an `"ollama"` provider built through
+/// `create_embedding_provider_with_config` must send its embed request to
+/// `config.local_ai.base_url`, not the env-only `ollama_base_url()` default. A
+/// local mock stands in for the Ollama daemon at a random port set as
+/// `local_ai.base_url`; a regression to the credential-store path (which calls
+/// `ollama_base_url()` → `localhost:11434`) would never hit the mock. This is
+/// the assertion the build-only test above cannot make, since the returned
+/// trait object exposes no URL accessor.
+#[tokio::test]
+async fn config_aware_factory_ollama_embeds_against_config_base_url() {
+ use std::sync::{Arc, Mutex};
+
+ use axum::{extract::State, routing::post, Json, Router};
+
+ // Mock Ollama `/api/embed`: records that it was hit and echoes a
+ // 3-dimensional vector (matching the requested `dims`).
+ #[derive(Clone, Default)]
+ struct Hit {
+ count: Arc<Mutex<usize>>,
+ }
+ let hit = Hit::default();
+ let app = Router::new()
+ .route(
+ "/api/embed",
+ post(
+ |State(h): State<Hit>, Json(_body): Json<serde_json::Value>| async move {
+ *h.count.lock().unwrap() += 1;
+ Json(serde_json::json!({ "embeddings": [[0.1_f32, 0.2, 0.3]] }))
+ },
+ ),
+ )
+ .with_state(hit.clone());
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let base = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port());
+ tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
+
+ let tmp = TempDir::new().unwrap();
+ let mut config = test_config(&tmp);
+ config.local_ai.base_url = Some(base.clone());
+
+ let provider =
+ create_embedding_provider_with_config(&config, "ollama", "nomic-embed-text", 3, "", None)
+ .expect("ollama provider builds with a config base_url");
+
+ let vectors = provider
+ .embed(&["binding probe"])
+ .await
+ .expect("factory-built ollama embedder must reach the config base_url");
+ assert_eq!(vectors.first().map(|v| v.len()).unwrap_or(0), 3);
+ assert!(
+ *hit.count.lock().unwrap() >= 1,
+ "embed must hit the configured local_ai.base_url, proving the ollama arm is config-aware"
+ );
+}
+
/// Non-managed providers delegate unchanged to the credentialed factory —
/// the config scope has no effect on BYO-key / local providers.
#[test]
diff --git a/src/openhuman/inference/local/service/ollama_admin/diagnostics.rs b/src/openhuman/inference/local/service/ollama_admin/diagnostics.rs
index c8a6fae02d..8e909dac2c 100644
--- a/src/openhuman/inference/local/service/ollama_admin/diagnostics.rs
+++ b/src/openhuman/inference/local/service/ollama_admin/diagnostics.rs
@@ -60,8 +60,20 @@ impl LocalAiService {
health_status
);
+ // A `Degraded` daemon answered only on the 8s health retry, so model
+ // discovery must give it the same headroom — otherwise the default 5s
+ // budget times out, the catalog comes back empty, and local models are
+ // hidden despite the daemon being reachable (#6032).
+ let discovery_timeout = match health_status {
+ OllamaHealthStatus::Degraded => std::time::Duration::from_secs(8),
+ _ => std::time::Duration::from_secs(5),
+ };
+
let (models, tags_error) = if healthy {
- match self.list_models_at(&base_url).await {
+ match self
+ .list_models_at_with_timeout(&base_url, discovery_timeout)
+ .await
+ {
Ok(models) => (models, None),
Err(e) => (vec![], Some(e)),
}
@@ -258,19 +270,37 @@ impl LocalAiService {
pub(in crate::openhuman::inference::local::service) async fn list_models_at(
&self,
base: &str,
+ ) -> Result<Vec<OllamaModelTag>, String> {
+ self.list_models_at_with_timeout(base, std::time::Duration::from_secs(5))
+ .await
+ }
+
+ /// Same as [`list_models_at`] but with a caller-chosen request timeout.
+ ///
+ /// The diagnostics path widens this to cover the degraded-probe window
+ /// (#6032): a server that answers `/api/tags` in 5-8s is classified
+ /// `Degraded` by the health probe, but discovery on the default 5s budget
+ /// would time out and hand back an empty catalog — which hides local
+ /// models even though the daemon is reachable. Matching the timeout to the
+ /// health-probe window keeps a slow-but-alive Ollama's models selectable.
+ pub(in crate::openhuman::inference::local::service) async fn list_models_at_with_timeout(
+ &self,
+ base: &str,
+ timeout: std::time::Duration,
) -> Result<Vec<OllamaModelTag>, String> {
let url = format!("{base}/api/tags");
tracing::debug!(
target: "local_ai::ollama_admin",
%base,
%url,
+ ?timeout,
"[local_ai:ollama_admin] list_models: sending GET"
);
let response = self
.http
.get(&url)
- .timeout(std::time::Duration::from_secs(5))
+ .timeout(timeout)
.send()
.await
.map_err(|e| {
diff --git a/src/openhuman/inference/local/service/ollama_admin_tests_part_01_tests.rs b/src/openhuman/inference/local/service/ollama_admin_tests_part_01_tests.rs
index e7169dd6ff..83ede4110c 100644
--- a/src/openhuman/inference/local/service/ollama_admin_tests_part_01_tests.rs
+++ b/src/openhuman/inference/local/service/ollama_admin_tests_part_01_tests.rs
@@ -100,6 +100,130 @@ async fn ollama_healthy_returns_false_on_unreachable_url() {
}
}
+// #6032 — two-phase health probe classification. `ollama_health_status_at`
+// returns `Running` on a fast 200, `Degraded` when the 2s fast probe times out
+// but the 8s retry succeeds, and `Stopped` otherwise.
+
+#[tokio::test]
+async fn ollama_health_status_running_on_fast_200() {
+ use super::super::health::OllamaHealthStatus;
+ let _guard = crate::openhuman::inference::inference_test_guard();
+
+ let app = Router::new().route("/api/tags", get(|| async { Json(json!({ "models": [] })) }));
+ let base = spawn_mock(app).await;
+ let config = Config::default();
+ let service = LocalAiService::new(&config);
+ assert_eq!(
+ service.ollama_health_status_at(&base).await,
+ OllamaHealthStatus::Running
+ );
+}
+
+#[tokio::test]
+async fn ollama_health_status_stopped_when_unreachable() {
+ use super::super::health::OllamaHealthStatus;
+ let _guard = crate::openhuman::inference::inference_test_guard();
+
+ // Unbound port → connect refused (not a timeout) → Stopped.
+ let config = Config::default();
+ let service = LocalAiService::new(&config);
+ assert_eq!(
+ service.ollama_health_status_at("http://127.0.0.1:1").await,
+ OllamaHealthStatus::Stopped
+ );
+}
+
+#[tokio::test]
+async fn ollama_health_status_degraded_on_slow_then_fast() {
+ use std::sync::atomic::{AtomicUsize, Ordering};
+ use std::sync::Arc;
+
+ use axum::extract::State;
+
+ use super::super::health::OllamaHealthStatus;
+ let _guard = crate::openhuman::inference::inference_test_guard();
+
+ // Stateful mock: the FIRST /api/tags call sleeps past the 2s fast-probe
+ // timeout; every later call answers instantly. This is exactly a
+ // momentarily-busy daemon — the fast probe times out, the 8s retry
+ // succeeds → Degraded.
+ let calls: Arc<AtomicUsize> = Arc::new(AtomicUsize::new(0));
+ let app = Router::new()
+ .route(
+ "/api/tags",
+ get(|State(calls): State<Arc<AtomicUsize>>| async move {
+ if calls.fetch_add(1, Ordering::SeqCst) == 0 {
+ tokio::time::sleep(std::time::Duration::from_millis(3000)).await;
+ }
+ Json(json!({ "models": [] }))
+ }),
+ )
+ .with_state(calls);
+ let base = spawn_mock(app).await;
+ let config = Config::default();
+ let service = LocalAiService::new(&config);
+ assert_eq!(
+ service.ollama_health_status_at(&base).await,
+ OllamaHealthStatus::Degraded
+ );
+}
+
+#[tokio::test]
+async fn diagnostics_degraded_ollama_stays_running_and_lists_models() {
+ use std::sync::atomic::{AtomicUsize, Ordering};
+ use std::sync::Arc;
+
+ use axum::extract::State;
+ use axum::routing::post;
+
+ let _guard = crate::openhuman::inference::inference_test_guard();
+
+ // Same slow-first-call mock, but returns a real model so we can prove that
+ // model discovery still succeeds under the degraded (8s) timeout — the
+ // whole point of #6032: a slow-but-alive daemon must keep its models
+ // selectable rather than collapsing to an empty catalog.
+ let tags_calls: Arc<AtomicUsize> = Arc::new(AtomicUsize::new(0));
+ let app = Router::new()
+ .route(
+ "/api/tags",
+ get(|State(calls): State<Arc<AtomicUsize>>| async move {
+ if calls.fetch_add(1, Ordering::SeqCst) == 0 {
+ tokio::time::sleep(std::time::Duration::from_millis(3000)).await;
+ }
+ Json(json!({
+ "models": [
+ {"name": "llama3:latest", "modified_at": "", "size": 1u64, "digest": "d"}
+ ]
+ }))
+ }),
+ )
+ .route("/api/show", post(|| async { Json(json!({})) }))
+ .with_state(tags_calls);
+ let base = spawn_mock(app).await;
+
+ let mut config = Config::default();
+ config.local_ai.provider = "ollama".to_string();
+ config.local_ai.base_url = Some(base);
+ let service = LocalAiService::new(&config);
+
+ let report = service.diagnostics(&config).await.expect("diagnostics ok");
+ assert_eq!(
+ report["ollama_status"], "degraded",
+ "a slow-but-alive daemon must report degraded, not stopped"
+ );
+ assert_eq!(
+ report["ollama_running"], true,
+ "degraded still counts as running so local models stay selectable"
+ );
+ let models = report["installed_models"]
+ .as_array()
+ .expect("installed_models array");
+ assert!(
+ !models.is_empty(),
+ "model discovery must survive the degraded timeout window (non-empty catalog)"
+ );
+}
+
#[tokio::test]
async fn ensure_ollama_server_requires_external_runtime_when_unreachable() {
let _guard = crate::openhuman::inference::inference_test_guard();