Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Ollama is found again after a restart without Re-check (26c) (#764)
Oleksandr Ivanchenkoafa0136172bc
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex 8eff3086..0ea1e6af 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -166,7 +166,7 @@ import { NeedsYouStrip } from './components/NeedsYouStrip';import { chainBudgetApi } from './chainBudget';import { needsYouRows, attentionRows } from './chatsTab';import { Space, eventsUrl, getCurrentSpace, pickInitialChat } from './spaces';-import { canRunNow } from './engines';+import { canRunNow, isUsable } from './engines';import { useEngines } from './useEngines';import { canInstall, setupApi } from './setupInstall';import { claudeNeedsSignIn } from './claudeLogin';@@ -451,6 +451,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({// card and the bots' online dots all read whether anything can run.const engines = useEngines(true);const canRun = canRunNow(engines.engines);+ const ollamaReady = engines.engines ? engines.engines.some((e) => e.id === 'ollama' && isUsable(e)) : null;const offerClaude = canRun === false && claudeNeedsSignIn(engines.engines);// Claude Code isn't here but kwant can install it: "Set up Claude" installs, then signs in, in one go.const claudeMissing = canRun === false && !!engines.engines?.some((e) => e.id === 'claude' && e.status === 'not_installed' && e.enabled !== false);@@ -4671,6 +4672,9 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({if (k) openAgentSettings(k, 'profile');}}canRun={canRun}+ ollamaReady={ollamaReady}+ onRecheckEngines={() => void engines.recheck()}+ recheckingEngines={engines.rechecking}titleExtra={workingBadge || skillsBadge || approvalsBadge ? (<>diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsxindex a073e8a2..7a52cf29 100644--- a/frontend/src/components/ChatView.tsx+++ b/frontend/src/components/ChatView.tsx@@ -420,6 +420,11 @@ export interface ChatViewProps {onEditBot?: (botName: string) => void;/** Whether anything can run a bot in this space now (null while unknown). */canRun?: boolean | null;+ /** Whether Ollama answers now (null while unknown), for a bot's "Ollama isn't answering" card. */+ ollamaReady?: boolean | null;+ /** Checks the engines again, from that card's Re-check button. */+ onRecheckEngines?: () => void;+ recheckingEngines?: boolean;/** The open chat's turn is paused on a question: it is waiting for the person, not working. */awaitingAnswer?: boolean;/** …and the pause is a browser step (sign-in, CAPTCHA) rather than a question. */@@ -670,6 +675,9 @@ export const ChatView: React.FC<ChatViewProps> = ({onChangeTeamFolder,onEditBot,canRun = null,+ ollamaReady = null,+ onRecheckEngines,+ recheckingEngines,awaitingAnswer,awaitingBrowser,awaitingBot,@@ -1686,6 +1694,9 @@ export const ChatView: React.FC<ChatViewProps> = ({spaceName={spaceName ?? 'this space'}canRun={canRun}onOpenAccounts={onOpenAccounts}+ ollamaReady={ollamaReady}+ onRecheck={onRecheckEngines}+ rechecking={recheckingEngines}flash={flashId === msg.id}/></div>diff --git a/frontend/src/components/SetupNeededCard.tsx b/frontend/src/components/SetupNeededCard.tsxindex 0807c73f..eb99392f 100644--- a/frontend/src/components/SetupNeededCard.tsx+++ b/frontend/src/components/SetupNeededCard.tsx@@ -1,18 +1,26 @@-import React from 'react';-import { AlertTriangle, CheckCircle2, KeyRound } from 'lucide-react';+import React, { useEffect, useRef, useState } from 'react';+import { AlertTriangle, CheckCircle2, KeyRound, RefreshCw } from 'lucide-react';import { parseMetaObject } from '../questions';-/** A turn nothing could run (message meta kind `setup_needed`, from src/drivers/engines.rs). */+/** A turn nothing could run (message meta kind `setup_needed`, from src/drivers/engines.rs).+ * `ollama_down`: the bot is pinned to Ollama and Ollama isn't answering at `url`. */export interface SetupMeta {- reason: 'no_account' | 'host_off';+ reason: 'no_account' | 'host_off' | 'ollama_down';+ url?: string;}export function parseSetupMeta(raw: unknown): SetupMeta | null {const m = parseMetaObject(raw);if (!m || m.kind !== 'setup_needed') return null;+ if (m.reason === 'ollama_down') return { reason: 'ollama_down', url: typeof m.url === 'string' && m.url ? m.url : undefined };return { reason: m.reason === 'host_off' ? 'host_off' : 'no_account' };}+/** The `ollama_down` detail line; `stillDown` once a Re-check has found Ollama still not answering. */+export function ollamaDownDetail(url: string | undefined, stillDown: boolean): string {+ return `Ollama ${stillDown ? 'still ' : ''}isn't answering at ${url ?? 'the address in Settings'}. Start it, then try again.`;+}+interface Props {meta: SetupMeta;botName: string;@@ -20,17 +28,36 @@ interface Props {/** Whether something can run now; once it can, the card says to send the message again. */canRun: boolean | null;onOpenAccounts: () => void;+ /** Whether Ollama answers now (null while unknown): an `ollama_down` card is fixed only by Ollama. */+ ollamaReady?: boolean | null;+ /** Checks the engines again (an `ollama_down` card's button). An `ollama_down` card never offers+ * Accounts: an account can't start Ollama. */+ onRecheck?: () => void;+ rechecking?: boolean;flash?: boolean;}/** Shown in place of the bot's reply when no account could run its turn, with a way to fix it. */-export const SetupNeededCard: React.FC<Props> = ({ meta, botName, spaceName, canRun, onOpenAccounts, flash }) => {- const fixed = canRun === true;+export const SetupNeededCard: React.FC<Props> = ({ meta, botName, spaceName, canRun, onOpenAccounts, ollamaReady, onRecheck, rechecking, flash }) => {+ const ollama = meta.reason === 'ollama_down';+ const fixed = ollama ? ollamaReady === true : canRun === true;+ // A Re-check that ends with Ollama still down says so, or the press looks like it did nothing.+ const [stillDown, setStillDown] = useState(false);+ const wasRechecking = useRef(rechecking);+ useEffect(() => {+ if (wasRechecking.current && !rechecking && ollamaReady !== true) setStillDown(true);+ wasRechecking.current = rechecking;+ }, [rechecking, ollamaReady]);const detail = fixed- ? `An account works in ${spaceName} now. Send your message again to get a reply.`- : meta.reason === 'host_off'- ? `This computer's AI accounts are off in ${spaceName} and no other account is on. Turn one on, or add an account.`- : `No account can run bots in ${spaceName} yet. Sign in with Claude, ChatGPT or Grok, or add an API key.`;+ ? ollama+ ? 'Ollama is answering now. Send your message again to get a reply.'+ : `An account works in ${spaceName} now. Send your message again to get a reply.`+ : ollama+ ? ollamaDownDetail(meta.url, stillDown)+ : meta.reason === 'host_off'+ ? `This computer's AI accounts are off in ${spaceName} and no other account is on. Turn one on, or add an account.`+ : `No account can run bots in ${spaceName} yet. Sign in with Claude, ChatGPT or Grok, or add an API key.`;+ const recheck = ollama && !!onRecheck;return (<div className={`flex items-start gap-3.5 w-full max-w-5xl rounded-xl ${flash ? 'kw-flash' : ''}`} data-setup-card={meta.reason}><div@@ -49,7 +76,19 @@ export const SetupNeededCard: React.FC<Props> = ({ meta, botName, spaceName, can><p className="text-sm font-medium text-zinc-100">{fixed ? `${botName} can answer now` : `${botName} can't answer yet`}</p><p className="mt-1 text-xs text-zinc-400 leading-relaxed">{detail}</p>- {!fixed && (+ {!fixed && recheck && (+ <button+ type="button"+ onClick={onRecheck}+ disabled={rechecking}+ data-setup-recheck+ className="mt-3 inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium text-white bg-sky-600 hover:bg-sky-500 disabled:opacity-60 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-300"+ >+ <RefreshCw size={13} aria-hidden="true" className={rechecking ? 'animate-spin motion-reduce:animate-none' : undefined} />+ {rechecking ? 'Checking…' : 'Re-check'}+ </button>+ )}+ {!fixed && !ollama && (<buttontype="button"onClick={onOpenAccounts}diff --git a/frontend/src/useEngines.ts b/frontend/src/useEngines.tsindex 64a2ff2d..4806c2da 100644--- a/frontend/src/useEngines.ts+++ b/frontend/src/useEngines.ts@@ -1,6 +1,9 @@// Engine status from GET /api/engines, shared by Settings, the kwant form and the sidebar.import { useCallback, useEffect, useRef, useState } from 'react';-import type { EngineInfo } from './engines';+import { canRunNow, type EngineInfo } from './engines';++/** How often the cached status is read again while Ollama is down or nothing can run. */+export const DOWN_POLL_MS = 30_000;export interface EnginesApi {/** null until the first load; [] from a server that has no engine checks. */@@ -16,7 +19,8 @@ export interface EnginesApi {apply: (engines: EngineInfo[]) => void;}-/** Loads /api/engines while `active`; polls briefly while any engine is still "checking". */+/** Loads /api/engines while `active`; polls briefly while any engine is still "checking", and slowly+ * while Ollama's last check failed or nothing can run (the server keeps looking at Ollama). */export function useEngines(active: boolean): EnginesApi {const [engines, setEngines] = useState<EngineInfo[] | null>(null);const [error, setError] = useState<string | null>(null);@@ -58,6 +62,16 @@ export function useEngines(active: boolean): EnginesApi {return () => window.clearTimeout(t);}, [active, anyChecking, engines, load]);+ // After a failed Ollama check the server looks again on its own (15 s, 30 s, 60 s, then every+ // 5 min), and with nothing able to run, a late engine is what everyone waits for: read the cached+ // status again every 30 s meanwhile, so the sidebar and space agree without a reload.+ const waiting = !!engines?.some((e) => e.id === 'ollama' && e.enabled !== false && e.status === 'error') || canRunNow(engines) === false;+ useEffect(() => {+ if (!active || !waiting || anyChecking) return;+ const t = window.setTimeout(load, DOWN_POLL_MS);+ return () => window.clearTimeout(t);+ }, [active, waiting, anyChecking, engines, load]);+const recheck = useCallback(async () => {setRechecking(true);setError(null);diff --git a/frontend/tests/setupNotice.test.mjs b/frontend/tests/setupNotice.test.mjsindex 03202417..f45d2ae8 100644--- a/frontend/tests/setupNotice.test.mjs+++ b/frontend/tests/setupNotice.test.mjs@@ -3,7 +3,7 @@ import test from 'node:test';import { loadBundled } from './bundle.mjs';const m = await loadBundled(`- export { SetupNeededCard, parseSetupMeta } from './src/components/SetupNeededCard';+ export { SetupNeededCard, parseSetupMeta, ollamaDownDetail } from './src/components/SetupNeededCard';export { canRunNow } from './src/engines';export { renderToStaticMarkup } from 'react-dom/server.browser';export { createElement } from 'react';@@ -57,3 +57,50 @@ test('canRunNow is unknown while loading or checking, never a false "nothing canassert.equal(m.canRunNow([e('claude', 'ready'), e('codex', 'checking')]), true);assert.equal(m.canRunNow([e('claude', 'ready', { enabled: false })]), false);});++test('a bot pinned to Ollama that cannot reach it gets an Ollama card with Re-check, not Add an account', () => {+ // What src/drivers/engines.rs ollama_down_notice saves on the message.+ assert.deepEqual(m.parseSetupMeta({ kind: 'setup_needed', reason: 'ollama_down', url: 'http://127.0.0.1:11434' }), {+ reason: 'ollama_down',+ url: 'http://127.0.0.1:11434',+ });+ assert.deepEqual(m.parseSetupMeta({ kind: 'setup_needed', reason: 'ollama_down' }), { reason: 'ollama_down', url: undefined });+ assert.deepEqual(m.parseSetupMeta({ kind: 'setup_needed', reason: 'ollama_down', url: 42 }), { reason: 'ollama_down', url: undefined });++ const meta = { reason: 'ollama_down', url: 'http://127.0.0.1:11434' };+ const html = card({ meta, onRecheck: () => {}, ollamaReady: false });+ assert.match(html, /Architect can(’|'|')t answer yet/);+ assert.match(html, /Ollama isn(’|'|')t answering at http:\/\/127\.0\.0\.1:11434\. Start it, then try again\./);+ assert.match(html, /data-setup-recheck/);+ assert.match(html, /Re-check<\/button>/);+ assert.doesNotMatch(html, /Add an account/);+ // Another account working does not fix a bot pinned to Ollama+ assert.match(card({ meta, onRecheck: () => {}, ollamaReady: false, canRun: true }), /can(’|'|')t answer yet/);++ const checking = card({ meta, onRecheck: () => {}, rechecking: true });+ assert.match(checking, /Checking…/);+ // The spinner stops under reduced motion; the label carries the state+ assert.match(checking, /class="[^"]*animate-spin motion-reduce:animate-none"/);+ // Same fallback phrase as the server's (src/drivers/engines.rs shown_url)+ assert.match(card({ meta: { reason: 'ollama_down' }, onRecheck: () => {} }), /at the address in Settings\./);+ // Without a Re-check handler there is no button at all, never Accounts+ assert.doesNotMatch(card({ meta }), /<button/);++ const fixed = card({ meta, onRecheck: () => {}, ollamaReady: true });+ assert.match(fixed, /Architect can answer now/);+ assert.match(fixed, /Ollama is answering now\. Send your message again/);+ assert.doesNotMatch(fixed, /<button/);+});++test('a Re-check that finds Ollama still down says so', () => {+ assert.equal(+ m.ollamaDownDetail('http://127.0.0.1:11434', false),+ "Ollama isn't answering at http://127.0.0.1:11434. Start it, then try again.",+ );+ assert.equal(+ m.ollamaDownDetail('http://127.0.0.1:11434', true),+ "Ollama still isn't answering at http://127.0.0.1:11434. Start it, then try again.",+ );+ assert.equal(m.ollamaDownDetail(undefined, true), "Ollama still isn't answering at the address in Settings. Start it, then try again.");+ assert.equal(m.ollamaDownDetail(undefined, false), "Ollama isn't answering at the address in Settings. Start it, then try again.");+});diff --git a/src/drivers/engines.rs b/src/drivers/engines.rsindex cd98efe8..3ce4297e 100644--- a/src/drivers/engines.rs+++ b/src/drivers/engines.rs@@ -22,6 +22,34 @@ pub const NO_ENGINE_MESSAGE: &str = "No account can run bots here yet. Add one ipub const HOST_OFF_MESSAGE: &str ="This machine is off in this space and no other account is on. Turn one on in Settings › This space › Accounts.";+/// What a turn pinned to Ollama gets when Ollama still isn't answering after a second look.+pub fn ollama_down_message(root: &str) -> String {+ format!("Ollama isn't answering at {}. Start it, then try again.", shown_url(root))+}++/// The chat message a bot pinned to Ollama leaves when Ollama isn't answering, and its `meta`:+/// kind `setup_needed`, reason `ollama_down`, so the app offers Re-check instead of "add an account".+pub fn ollama_down_notice(bot: &str, root: &str) -> (String, Value) {+ let url = shown_url(root);+ (+ format!("⚠️ [{bot}] {}", ollama_down_message(root)),+ serde_json::json!({ "kind": "setup_needed", "reason": "ollama_down", "url": url }),+ )+}++/// `url` as a chat may show it: any user name or password in it is dropped.+fn shown_url(url: &str) -> String {+ match reqwest::Url::parse(url) {+ Ok(mut u) if !u.username().is_empty() || u.password().is_some() => {+ let _ = u.set_username("");+ let _ = u.set_password(None);+ u.to_string().trim_end_matches('/').to_string()+ }+ Ok(_) => url.to_string(),+ Err(_) => "the address in Settings".into(),+ }+}+/// The chat message `bot` leaves when nothing can run its turn, and its `meta`: kind/// `setup_needed`, so the app shows a card with a button to Accounts instead of a reply./// `reason` is `host_off` when This machine is switched off in the space, else `no_account`.@@ -317,6 +345,9 @@ pub struct ProbeEnv {/// Ollama server root (no `/v1`).pub ollama_root: String,pub ollama_installed: bool,+ /// The person set Ollama up: its binary is on this host, or Settings or `OLLAMA_URL` name a+ /// server. Only then does a failed check look again on its own (see [`EngineRegistry::watch_ollama`]).+ pub ollama_configured: bool,pub anthropic_base: String,pub openai_base: String,pub xai_base: String,@@ -334,6 +365,9 @@ impl ProbeEnv {.filter(|k| !k.trim().is_empty())}let ollama_url = db.get_setting("ollama_url").await.ok().flatten();+ let ollama_installed = super::find_cli_binary("ollama").is_some();+ let named = |u: Option<String>| u.is_some_and(|u| !u.trim().is_empty());+ let ollama_configured = ollama_installed || named(ollama_url.clone()) || named(std::env::var("OLLAMA_URL").ok());Self {claude_bin: super::find_cli_binary("claude"),claude_config_dir: None,@@ -343,7 +377,8 @@ impl ProbeEnv {openai_key: key(db, "openai_api_key", "OPENAI_API_KEY").await,xai_key: key(db, "xai_api_key", "XAI_API_KEY").await,ollama_root: super::ollama_root(ollama_url.as_deref()),- ollama_installed: super::find_cli_binary("ollama").is_some(),+ ollama_installed,+ ollama_configured,anthropic_base: "https://api.anthropic.com".into(),openai_base: "https://api.openai.com".into(),xai_base: "https://api.x.ai".into(),@@ -729,8 +764,28 @@ pub struct EngineRegistry {/// Turned off in Settings (`engines_disabled`).disabled: RwLock<HashSet<EngineId>>,running: tokio::sync::Mutex<()>,+ /// Held by a one-engine check from [`EngineRegistry::recheck_joined`], so turns and the+ /// Ollama watcher that need the same check at once share one.+ one: tokio::sync::Mutex<()>,+}++/// How long the Ollama watcher waits before each look after a failed check: 15 s, 30 s, 60 s,+/// then every 5 minutes until Ollama answers.+pub const OLLAMA_BACKOFF: [Duration; 4] = [+ Duration::from_secs(15),+ Duration::from_secs(30),+ Duration::from_secs(60),+ Duration::from_secs(300),+];++/// The wait before look number `step` (0-based) after a failed check; the last one repeats.+pub fn backoff_delay(delays: &[Duration], step: usize) -> Duration {+ delays.get(step).or(delays.last()).copied().unwrap_or(Duration::from_secs(300))}+/// How long a turn about to say nothing can run waits for a second look at Ollama.+pub const SECOND_LOOK: Duration = Duration::from_secs(3);+/// Settings key holding the ids of engines turned off, as a JSON list.pub const DISABLED_SETTING: &str = "engines_disabled";@@ -829,6 +884,68 @@ impl EngineRegistry {self.report(id).status}+ /// When the last stored check of `id` ran (marks from turns don't count).+ fn checked_at(&self, id: EngineId) -> Option<DateTime<Utc>> {+ self.checked.read().unwrap().get(&id).and_then(|r| r.checked_at)+ }++ /// Checks `id` again, within `limit`, and returns its status. A check already running (the+ /// startup check, Re-check, or another caller's look at the same engine) is waited for and+ /// its result used, instead of starting a second one. Past `limit` the status stays as it was.+ pub async fn recheck_joined(&self, id: EngineId, env: &ProbeEnv, limit: Duration) -> EngineStatus {+ if !self.is_enabled(id) {+ return EngineStatus::Disabled;+ }+ let seen = self.checked_at(id);+ let _ = tokio::time::timeout(limit, async {+ drop(self.running.lock().await);+ if self.checked_at(id) != seen {+ return;+ }+ let _one = self.one.lock().await;+ if self.checked_at(id) != seen {+ return;+ }+ let probe = probe_within(id, env, limit).await;+ self.store(vec![(id, probe)]);+ })+ .await;+ self.status(id)+ }++ /// Whether Ollama's last check failed in a way a later look can fix: it errored, or it wasn't+ /// running though the person set it up. Off, ready, or not checked yet ⇒ no.+ pub fn ollama_down(&self, configured: bool) -> bool {+ match self.status(EngineId::Ollama) {+ EngineStatus::Error => true,+ EngineStatus::NotInstalled => configured,+ _ => false,+ }+ }++ /// Runs for the life of the server: after a failed Ollama check, looks again on `delays`+ /// (see [`OLLAMA_BACKOFF`]), so a server that comes up late is ready without anyone pressing+ /// Re-check. Each look is one `/api/tags` call (plus `/api/version` once it answers); nothing+ /// runs while Ollama is ready, off, or not set up.+ pub async fn watch_ollama<F, Fut>(&self, delays: &[Duration], env: F)+ where+ F: Fn() -> Fut,+ Fut: std::future::Future<Output = ProbeEnv>,+ {+ let mut step = 0;+ loop {+ tokio::time::sleep(backoff_delay(delays, step)).await;+ let env = env().await;+ if !self.ollama_down(env.ollama_configured) {+ step = 0;+ continue;+ }+ let status = self.recheck_joined(EngineId::Ollama, &env, PROBE_TIMEOUT).await;+ tracing::debug!(?status, step, "Ollama looked at again after a failed check");+ step = if status == EngineStatus::Ready { 0 } else { step + 1 };+ }+ }+/// Whether a turn may use the engine. Before the first check finishes, `present` (binary/// found, key set) decides, as before checks existed.pub fn usable(&self, id: EngineId, present: bool) -> bool {@@ -1071,6 +1188,45 @@ mod tests {assert_eq!(meta["reason"], "host_off");}+ #[test]+ fn ollama_down_notice_names_the_server_not_an_account() {+ let (text, meta) = ollama_down_notice("House", "http://192.168.1.20:11434");+ assert_eq!(text, "⚠️ [House] Ollama isn't answering at http://192.168.1.20:11434. Start it, then try again.");+ assert!(!text.contains("Accounts") && !text.contains("account"), "{text}");+ assert_eq!(meta, serde_json::json!({ "kind": "setup_needed", "reason": "ollama_down", "url": "http://192.168.1.20:11434" }));+ // A user name or password in the address never reaches the chat+ let (text, meta) = ollama_down_notice("House", "http://me:[email protected]:11434");+ assert!(!text.contains("hunter2") && !text.contains("me:"), "{text}");+ assert_eq!(meta["url"], "http://ollama.lan:11434");+ // Something that isn't a URL is never echoed+ let (text, _) = ollama_down_notice("House", "not a url <script>");+ assert!(text.contains("at the address in Settings") && !text.contains("<script>"), "{text}");+ }++ #[test]+ fn the_ollama_backoff_slows_down_then_repeats_every_five_minutes() {+ let at = |step| backoff_delay(&OLLAMA_BACKOFF, step).as_secs();+ assert_eq!([at(0), at(1), at(2), at(3), at(4), at(40)], [15, 30, 60, 300, 300, 300]);+ assert_eq!(backoff_delay(&[], 0), Duration::from_secs(300));+ }++ #[test]+ fn ollama_counts_as_down_only_when_a_later_look_can_fix_it() {+ let reg = EngineRegistry::default();+ assert!(!reg.ollama_down(true), "not checked yet: the startup check decides");+ reg.store(vec![(EngineId::Ollama, Probe::error("Ollama isn't running at x: run `ollama serve`"))]);+ assert!(reg.ollama_down(false) && reg.ollama_down(true));+ // Not running and never set up (no binary, no address): nothing to wait for+ reg.store(vec![(EngineId::Ollama, Probe::not_installed("Ollama isn't running at x"))]);+ assert!(!reg.ollama_down(false));+ assert!(reg.ollama_down(true), "an address in Settings means it should come up");+ reg.set_enabled(EngineId::Ollama, false);+ assert!(!reg.ollama_down(true), "off in Settings: never looked at");+ reg.set_enabled(EngineId::Ollama, true);+ reg.store(vec![(EngineId::Ollama, Probe::ready("1 model(s) pulled", vec![EngineModel::new("m", "m", true, None)]))]);+ assert!(!reg.ollama_down(true));+ }+#[test]fn versions_parse_from_each_cli() {assert_eq!(parse_version("2.1.296 (Claude Code)\n").as_deref(), Some("2.1.296"));diff --git a/src/server/engine_routes.rs b/src/server/engine_routes.rsindex 25b72308..2d6b4177 100644--- a/src/server/engine_routes.rs+++ b/src/server/engine_routes.rs@@ -88,7 +88,8 @@ pub async fn set_enabled(Ok(Json(EnginesResponse { engines: with_accounts(&state, &space, state.engines.snapshot()).await }))}-/// Checks every engine in the background, so the first turns after startup see real status.+/// Checks every engine in the background, so the first turns after startup see real status, then+/// keeps looking at a failed Ollama on a backoff (see `EngineRegistry::watch_ollama`).pub fn spawn_startup_check(state: AppState) {tokio::spawn(async move {let engines = recheck_all(&state, &SpaceId::default_space()).await;@@ -98,5 +99,8 @@ pub fn spawn_startup_check(state: AppState) {.map(|e| e.name.as_str()).collect();tracing::info!(ready = ?ready, "engine checks finished");+ // An Ollama that came up after this check is found without anyone pressing Re-check+ let engines = state.engines.clone();+ engines.watch_ollama(&crate::drivers::engines::OLLAMA_BACKOFF, || probe_env(&state)).await;});}diff --git a/src/server/missions/autofix.rs b/src/server/missions/autofix.rsindex a6da0b0c..1718f87e 100644--- a/src/server/missions/autofix.rs+++ b/src/server/missions/autofix.rs@@ -97,7 +97,7 @@ const QUOTA: [&str; 13] = ["quota exceeded",];-const TRANSIENT: [&str; 18] = [+const TRANSIENT: [&str; 19] = ["rate limit","rate-limit","rate_limit",@@ -116,6 +116,8 @@ const TRANSIENT: [&str; 18] = ["internal server error","econnreset","etimedout",+ // kwant's own line when a bot pinned to Ollama finds it down (drivers/engines.rs): it comes back+ "ollama isn't answering",];const TRANSIENT_CODES: [&str; 6] = ["429", "500", "502", "503", "504", "529"];@@ -1292,6 +1294,10 @@ mod tests {}// The give-up text has no "401" of its own: the words alone must carry itassert!(!texts[0].contains("401"), "{}", texts[0]);+ // A bot pinned to Ollama that finds it down waits and retries: nothing to sign in to+ let down = crate::drivers::engines::ollama_down_notice("Ann", "http://127.0.0.1:11434").0;+ assert_eq!(classify("turn", "error", &down), "transient", "{down}");+ assert_eq!(strategy_for(classify("turn", "error", &down)), "wait_and_retry");}#[test]diff --git a/src/server/profile_turn.rs b/src/server/profile_turn.rsindex b28b95ab..23b58721 100644--- a/src/server/profile_turn.rs+++ b/src/server/profile_turn.rs@@ -400,22 +400,31 @@ pub async fn with_accounts(state: &AppState, space: &SpaceId, mut reports: Vec<E/// How many of `space`'s enabled accounts could take a turn now: This machine when its/// engine's own login is ready and the engine is on, any other account when it is signed in-/// and its engine is on.+/// and its engine is on, plus each engine that runs with no account at all (Ollama) when it is+/// on and ready, so the space never says "no account yet" while the sidebar says Ollama is ready.pub async fn ready_accounts(state: &AppState, space: &SpaceId) -> usize {+ let reports = state.engines.snapshot();+ let accountless = reports.iter().filter(|r| runs_without_account(r)).count();let Some((profiles, avail)) = accounts(state, space).await else {- return 0;+ return accountless;};- let reports = state.engines.snapshot();let now = chrono::Utc::now();- profiles.iter().filter(|p| p.enabled && is_ready(state, p, &avail, &reports, now)).count()+ accountless + profiles.iter().filter(|p| p.enabled && is_ready(state, p, &avail, &reports, now)).count()+}++/// An engine with no accounts (no model family: Ollama) that is on and passed its check.+fn runs_without_account(r: &EngineReport) -> bool {+ r.id.family().is_none() && r.enabled && r.status == EngineStatus::Ready}/// Whether an enabled account could take a turn now (see [`ready_accounts`]).fn is_ready(state: &AppState, p: &LlmProfile, avail: &Availability, reports: &[EngineReport], now: chrono::DateTime<chrono::Utc>) -> bool {match (p.kind.as_str(), Engine::parse(&p.engine)) {+ // This machine runs on the engine's CLI login or on its API key from Settings, as the+ // sidebar's `readiness` counts either("system", Some(family)) => {- let (cli, _) = EngineId::of_family(family);- reports.iter().any(|r| r.id == cli && r.enabled && r.status == EngineStatus::Ready)+ let (cli, api) = EngineId::of_family(family);+ reports.iter().any(|r| (r.id == cli || r.id == api) && r.enabled && r.status == EngineStatus::Ready)}("system", None) => false,_ => avail.admits(p, now, SignInBar::SignedIn) && profile_engine_on(state, p),diff --git a/src/server/routes.rs b/src/server/routes.rsindex f00532aa..511bbe14 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -2861,16 +2861,39 @@ async fn run_kwant_turn_inner(let space = SpaceId::new(&target_kwant.space_id);let profile_engines = super::profile_turn::profile_engines(state, &space).await;let host_off = super::profile_turn::host_off(state, &space).await;- let available_models =+ let mut available_models =crate::drivers::detect_available_models(&db, &state.engines, &profile_engines, &host_off).await;// A bot pinned to Custom API runs on its account even when that account's last check// failed, so the reply says what is wrong with it (no account, server down, key refused)let pin = opts.pin.as_deref().unwrap_or(&target_kwant.preferred_model);- let pinned_custom = crate::router::parse_pin(pin).family.as_deref()- == Some(crate::profiles::Engine::Custom.as_str());+ let pinned_family = crate::router::parse_pin(pin).family;+ let pinned_custom = pinned_family.as_deref() == Some(crate::profiles::Engine::Custom.as_str());+ let pinned_ollama = pinned_family.as_deref() == Some("local_ollama");+ let mut ollama_root = None;if available_models.is_empty() && !pinned_custom {- // Say why when it's this space's own switch, so nobody hunts for a broken engine- let (text, meta) = crate::drivers::engines::no_engine_notice(&target_kwant.name, !host_off.is_empty());+ // Ollama may have come up after its last check (a restart): look once more, joining a+ // check already running, before saying nothing can run (26c)+ use crate::drivers::engines::{EngineId, EngineStatus, SECOND_LOOK};+ let env = super::engine_routes::probe_env(state).await;+ if (pinned_ollama || env.ollama_configured)+ && !matches!(state.engines.status(EngineId::Ollama), EngineStatus::Ready | EngineStatus::Disabled)+ && state.engines.recheck_joined(EngineId::Ollama, &env, SECOND_LOOK).await == EngineStatus::Ready+ {+ available_models =+ crate::drivers::detect_available_models(&db, &state.engines, &profile_engines, &host_off).await;+ }+ ollama_root = Some(env.ollama_root);+ }+ if available_models.is_empty() && !pinned_custom {+ // Say why when it's this space's own switch, so nobody hunts for a broken engine; a+ // bot pinned to Ollama says Ollama isn't answering, never "add an account"+ let ollama_on = state.engines.is_enabled(crate::drivers::engines::EngineId::Ollama);+ let (text, meta) = match ollama_root.as_deref() {+ Some(root) if pinned_ollama && ollama_on => {+ crate::drivers::engines::ollama_down_notice(&target_kwant.name, root)+ }+ _ => crate::drivers::engines::no_engine_notice(&target_kwant.name, !host_off.is_empty()),+ };event_broadcast.send(RuntimeEvent::TextDelta(text.clone()));event_broadcast.send(RuntimeEvent::TurnComplete {tokens: 0,diff --git a/tests/ollama_ready_after_restart_test.rs b/tests/ollama_ready_after_restart_test.rsnew file mode 100644index 00000000..de59f510--- /dev/null+++ b/tests/ollama_ready_after_restart_test.rs@@ -0,0 +1,450 @@+//! 26c: Ollama that comes up after kwant (a restart) is found without anyone pressing Re-check.+//! A turn that would say "no account" looks at Ollama once more first, a bot pinned to Ollama+//! that still can't reach it says so (not "add an account"), a failed check looks again on its own,+//! and a ready Ollama counts in the space's accounts. Its own test binary: it changes PATH, HOME+//! and the process env.++use axum::{+ body::{to_bytes, Body},+ extract::State,+ http::{Request, StatusCode},+ routing::{get, post},+ Json, Router,+};+use kwnt::{+ broker::PermissionBroker,+ config::Config,+ db::Database,+ drivers::{+ detect_available_models,+ engines::{EngineId, EngineRegistry, EngineStatus, Probe, ProbeEnv},+ RuntimeEvent,+ },+ router::LayaRouter,+ server::{create_router, AppState},+ tools::ToolRunner,+};+use serde_json::{json, Value};+use std::collections::HashSet;+use std::sync::atomic::{AtomicUsize, Ordering};+use std::sync::Arc;+use std::time::{Duration, Instant};+use tower::ServiceExt;++const MODEL: &str = "qwen-home:latest";++/// A fake Ollama: counts `/api/tags` looks and chat calls.+#[derive(Clone, Default)]+struct Ollama {+ tags: Arc<AtomicUsize>,+ chats: Arc<AtomicUsize>,+}++async fn tags(State(o): State<Ollama>) -> Json<Value> {+ o.tags.fetch_add(1, Ordering::SeqCst);+ // Slow enough that two looks at once overlap+ tokio::time::sleep(Duration::from_millis(150)).await;+ Json(json!({ "models": [{ "name": MODEL }] }))+}++async fn chat(State(o): State<Ollama>, Json(_): Json<Value>) -> Json<Value> {+ o.chats.fetch_add(1, Ordering::SeqCst);+ Json(+ json!({ "choices": [{ "message": { "role": "assistant", "content": "lights are off" } }], "usage": { "total_tokens": 7 } }),+ )+}++/// A free port with nothing listening on it yet: Ollama "not started".+async fn closed_port() -> u16 {+ let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ l.local_addr().unwrap().port()+}++/// Starts the fake Ollama on `port` (Ollama "came up").+async fn start_ollama(port: u16) -> Ollama {+ let o = Ollama::default();+ let app = Router::new()+ .route("/api/tags", get(tags))+ .route(+ "/api/version",+ get(|| async { Json(json!({ "version": "0.9.1" })) }),+ )+ .route("/v1/chat/completions", post(chat))+ .with_state(o.clone());+ let listener = tokio::net::TcpListener::bind(("127.0.0.1", port))+ .await+ .unwrap();+ tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });+ o+}++fn env_at(port: u16) -> ProbeEnv {+ ProbeEnv {+ ollama_root: format!("http://127.0.0.1:{port}"),+ ollama_installed: true,+ ollama_configured: true,+ ..ProbeEnv::default()+ }+}++/// What a failed startup check leaves behind.+fn failed() -> Probe {+ Probe {+ status: EngineStatus::Error,+ detail: Some("Ollama isn't running".into()),+ version: None,+ models: Vec::new(),+ }+}++fn offers_ollama(models: &[kwnt::drivers::ModelDescriptor]) -> bool {+ models.iter().any(|m| m.id == "local_ollama")+}++#[tokio::test]+async fn after_a_failed_check_a_second_look_offers_ollama_again_and_shares_one_check() {+ let tmp = tempfile::tempdir().unwrap();+ let db = Database::init(&tmp.path().join("data")).await.unwrap();+ let none = HashSet::new();+ let reg = EngineRegistry::default();+ let port = closed_port().await;+ let env = env_at(port);++ // Down: the look fails and Ollama stays out+ assert_eq!(+ reg.recheck_joined(EngineId::Ollama, &env, Duration::from_secs(3))+ .await,+ EngineStatus::Error+ );+ assert!(!offers_ollama(+ &detect_available_models(&db, ®, &none, &none).await+ ));++ // Up: one look and it is offered again+ let ollama = start_ollama(port).await;+ assert_eq!(+ reg.recheck_joined(EngineId::Ollama, &env, Duration::from_secs(3))+ .await,+ EngineStatus::Ready+ );+ let models = detect_available_models(&db, ®, &none, &none).await;+ assert!(offers_ollama(&models), "{models:?}");+ assert_eq!(ollama.tags.load(Ordering::SeqCst), 1);++ // Three turns at once after a failure share one check+ reg.store(vec![(EngineId::Ollama, failed())]);+ let limit = Duration::from_secs(3);+ let (a, b, c) = tokio::join!(+ reg.recheck_joined(EngineId::Ollama, &env, limit),+ reg.recheck_joined(EngineId::Ollama, &env, limit),+ reg.recheck_joined(EngineId::Ollama, &env, limit),+ );+ assert_eq!(+ (a, b, c),+ (+ EngineStatus::Ready,+ EngineStatus::Ready,+ EngineStatus::Ready+ )+ );+ assert_eq!(+ ollama.tags.load(Ordering::SeqCst),+ 2,+ "one more look, not three"+ );++ // Off in Settings: never looked at+ reg.set_enabled(EngineId::Ollama, false);+ assert_eq!(+ reg.recheck_joined(EngineId::Ollama, &env, limit).await,+ EngineStatus::Disabled+ );+ assert_eq!(ollama.tags.load(Ordering::SeqCst), 2);+}++#[tokio::test]+async fn a_second_look_never_holds_a_turn_past_its_limit() {+ // Accepts connections and never answers: a hung Ollama+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let port = listener.local_addr().unwrap().port();+ tokio::spawn(async move {+ let mut held = Vec::new();+ while let Ok((s, _)) = listener.accept().await {+ held.push(s);+ }+ });+ let reg = EngineRegistry::default();+ reg.store(vec![(EngineId::Ollama, failed())]);+ let started = Instant::now();+ let status = reg+ .recheck_joined(EngineId::Ollama, &env_at(port), Duration::from_millis(400))+ .await;+ assert!(+ started.elapsed() < Duration::from_secs(2),+ "{:?}",+ started.elapsed()+ );+ assert_eq!(+ status,+ EngineStatus::Error,+ "past the limit the old status stands"+ );+}++#[tokio::test]+async fn the_watcher_finds_ollama_once_it_comes_up_with_no_call_from_the_app() {+ let port = closed_port().await;+ let reg = Arc::new(EngineRegistry::default());+ reg.store(vec![(EngineId::Ollama, failed())]);+ let delays = [Duration::from_millis(40)];+ let watcher = {+ let reg = reg.clone();+ tokio::spawn(async move {+ reg.watch_ollama(&delays, || async move { env_at(port) })+ .await+ })+ };+ tokio::time::sleep(Duration::from_millis(200)).await;+ assert_eq!(reg.status(EngineId::Ollama), EngineStatus::Error);++ let ollama = start_ollama(port).await;+ tokio::time::timeout(Duration::from_secs(10), async {+ while reg.status(EngineId::Ollama) != EngineStatus::Ready {+ tokio::time::sleep(Duration::from_millis(20)).await;+ }+ })+ .await+ .expect("the watcher never found Ollama");+ // Ready: no more looks+ let looks = ollama.tags.load(Ordering::SeqCst);+ tokio::time::sleep(Duration::from_millis(300)).await;+ assert_eq!(ollama.tags.load(Ordering::SeqCst), looks);+ watcher.abort();++ // Never set up (no binary, no address) and not running: the watcher leaves it alone+ let reg = Arc::new(EngineRegistry::default());+ reg.store(vec![(+ EngineId::Ollama,+ Probe {+ status: EngineStatus::NotInstalled,+ detail: None,+ version: None,+ models: Vec::new(),+ },+ )]);+ let watcher = {+ let reg = reg.clone();+ let env = ProbeEnv {+ ollama_configured: false,+ ollama_installed: false,+ ..env_at(port)+ };+ tokio::spawn(async move {+ reg.watch_ollama(&delays, || {+ let env = env.clone();+ async move { env }+ })+ .await+ })+ };+ tokio::time::sleep(Duration::from_millis(300)).await;+ watcher.abort();+ assert_eq!(reg.status(EngineId::Ollama), EngineStatus::NotInstalled);+ assert_eq!(ollama.tags.load(Ordering::SeqCst), looks);+}++async fn call(app: &Router, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {+ let resp = app+ .clone()+ .oneshot(+ Request::builder()+ .method(method)+ .uri(uri)+ .header("content-type", "application/json")+ .body(+ body.map(|v| Body::from(v.to_string()))+ .unwrap_or_else(Body::empty),+ )+ .unwrap(),+ )+ .await+ .unwrap();+ let s = resp.status();+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();+ (s, serde_json::from_slice(&bytes).unwrap_or(Value::Null))+}++/// Sends a prompt; the text the turn streamed and how long it took.+async fn turn(app: &Router, state: &AppState, kwant_id: &str) -> (String, Duration) {+ let mut rx = state.event_sender.subscribe();+ let started = Instant::now();+ let (s, v) = call(+ app,+ "POST",+ "/api/chat/send",+ Some(json!({"kwant_id": kwant_id, "prompt": "lights off", "sender_id": "user"})),+ )+ .await;+ assert_eq!(s, StatusCode::OK, "{v}");+ let mut text = String::new();+ tokio::time::timeout(Duration::from_secs(60), async {+ while let Ok(e) = rx.recv().await {+ match e.unscoped() {+ RuntimeEvent::TextDelta(t) => text.push_str(t),+ RuntimeEvent::TurnEnded { kwant_id: k, .. } if k == kwant_id => break,+ _ => {}+ }+ }+ })+ .await+ .expect("turn did not end");+ (text, started.elapsed())+}++/// The newest saved reply of the bot: its text and parsed meta.+async fn last_reply(state: &AppState, kwant_id: &str) -> (String, Value) {+ let msgs = state.db.list_messages(kwant_id, 50).await.unwrap();+ let m = msgs+ .iter()+ .rev()+ .find(|m| m.sender_role == "kwant")+ .expect("a saved reply");+ (+ m.text.clone(),+ m.meta+ .as_deref()+ .and_then(|s| serde_json::from_str(s).ok())+ .unwrap_or(Value::Null),+ )+}++async fn ready_accounts(app: &Router) -> u64 {+ let (s, v) = call(app, "GET", "/api/spaces", None).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ let spaces = v+ .as_array()+ .or_else(|| v["spaces"].as_array())+ .expect("a list of spaces")+ .clone();+ let default = spaces+ .iter()+ .find(|s| s["is_default"] == true)+ .unwrap_or(&spaces[0]);+ default["counts"]["ready_accounts"]+ .as_u64()+ .expect("counts.ready_accounts")+}++#[tokio::test]+async fn a_bot_pinned_to_ollama_runs_once_ollama_is_back_and_the_space_counts_it() {+ let tmp = tempfile::tempdir().unwrap();+ let bin = tmp.path().join("bin");+ std::fs::create_dir_all(&bin).unwrap();+ // No CLI and no key: Ollama is the only engine, as in the tester's Home space+ std::env::set_var("PATH", format!("{}:/usr/bin:/bin", bin.display()));+ std::env::set_var("HOME", tmp.path());+ for var in [+ "ANTHROPIC_API_KEY",+ "OPENAI_API_KEY",+ "XAI_API_KEY",+ "OLLAMA_MODEL",+ "CLAUDE_CONFIG_DIR",+ ] {+ std::env::remove_var(var);+ }+ let port = closed_port().await;+ let root = format!("http://127.0.0.1:{port}");+ std::env::set_var("OLLAMA_URL", &root);++ let data = tmp.path().join("data");+ let db = Database::init(&data).await.unwrap();+ let config = Config {+ data_dir: data.clone(),+ laya_url: "http://127.0.0.1:9".into(),+ browser_cdp_url: Some("http://127.0.0.1:9".into()),+ ..Config::default()+ };+ let state = AppState::new(+ config.clone(),+ db,+ ToolRunner::new(data.join("workspace")),+ PermissionBroker::new(),+ LayaRouter::new(config.laya_url.clone()),+ );+ let app = create_router(state.clone());++ // kwant restarted while Ollama was still down: the startup check failed+ let (s, _) = call(&app, "POST", "/api/engines/recheck", None).await;+ assert_eq!(s, StatusCode::OK);+ assert_eq!(+ state.engines.status(EngineId::Ollama),+ EngineStatus::NotInstalled+ );+ assert_eq!(ready_accounts(&app).await, 0);++ let (_, kwants) = call(&app, "GET", "/api/kwants", None).await;+ let k = kwants[0].clone();+ let kid = k["id"].as_str().unwrap().to_string();+ let mut body = k.clone();+ body.as_object_mut().unwrap().retain(|key, _| {+ ["name", "title", "persona_prompt", "soul", "avatar_sprite"].contains(&key.as_str())+ });+ body["preferred_model"] = json!(format!("ollama/{MODEL}"));+ let (s, r) = call(&app, "PUT", &format!("/api/kwants/{kid}"), Some(body)).await;+ assert_eq!(s, StatusCode::OK, "{r}");++ // Still down: the bot says Ollama isn't answering, with Re-check, never "add an account"+ let (text, took) = turn(&app, &state, &kid).await;+ assert!(+ text.contains(&format!(+ "Ollama isn't answering at {root}. Start it, then try again."+ )),+ "{text}"+ );+ assert!(+ !text.contains("No account can run bots") && !text.contains("Accounts"),+ "{text}"+ );+ assert!(took < Duration::from_secs(10), "{took:?}");+ let (_, meta) = last_reply(&state, &kid).await;+ assert_eq!(+ meta,+ json!({ "kind": "setup_needed", "reason": "ollama_down", "url": root })+ );++ // Ollama comes up. The cache still says it failed, and nobody presses Re-check+ let ollama = start_ollama(port).await;+ state.engines.store(vec![(EngineId::Ollama, failed())]);+ let (text, _) = turn(&app, &state, &kid).await;+ assert!(text.contains("lights are off"), "{text}");+ assert_eq!(ollama.chats.load(Ordering::SeqCst), 1);+ let (reply, meta) = last_reply(&state, &kid).await;+ assert!(+ reply.contains("lights are off") && meta["kind"] != "setup_needed",+ "{reply} {meta}"+ );++ // Ready Ollama counts in the space, as the sidebar footer says+ assert_eq!(state.engines.status(EngineId::Ollama), EngineStatus::Ready);+ assert_eq!(ready_accounts(&app).await, 1);+ // Off in Settings: not counted+ state.engines.set_enabled(EngineId::Ollama, false);+ assert_eq!(ready_accounts(&app).await, 0);+ state.engines.set_enabled(EngineId::Ollama, true);++ // A bot not pinned to Ollama, with Ollama down and nothing else: the usual setup card+ let port2 = closed_port().await;+ std::env::set_var("OLLAMA_URL", format!("http://127.0.0.1:{port2}"));+ state.engines.store(vec![(EngineId::Ollama, failed())]);+ let mut body = k.clone();+ body.as_object_mut().unwrap().retain(|key, _| {+ ["name", "title", "persona_prompt", "soul", "avatar_sprite"].contains(&key.as_str())+ });+ body["preferred_model"] = json!("auto");+ let (s, r) = call(&app, "PUT", &format!("/api/kwants/{kid}"), Some(body)).await;+ assert_eq!(s, StatusCode::OK, "{r}");+ let (text, _) = turn(&app, &state, &kid).await;+ assert!(text.contains("No account can run bots here yet"), "{text}");+ let (_, meta) = last_reply(&state, &kid).await;+ assert_eq!(meta["reason"], "no_account");+}