Skip to content

armgit / kwant

Public Imported from GitHub
0

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.

4.7 KB
Raw Blame
// Engine status from GET /api/engines, shared by Settings, the kwant form and the sidebar.
import { useCallback, useEffect, useRef, useState } from 'react';
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. */
  engines: EngineInfo[] | null;
  error: string | null;
  rechecking: boolean;
  recheck: () => Promise<void>;
  /** Reads the cached status again, without re-running the checks. */
  reload: () => Promise<void>;
  /** True once the server took it; false when it said no (the switch is put back and `error` set). */
  setEnabled: (id: EngineInfo['id'], enabled: boolean) => Promise<boolean>;
  /** Shows a list the server already answered with (e.g. after signing out). */
  apply: (engines: EngineInfo[]) => void;
}

/** 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);
  const [rechecking, setRechecking] = useState(false);
  const alive = useRef(true);
  useEffect(() => {
    // Set again on mount: StrictMode mounts twice.
    alive.current = true;
    return () => void (alive.current = false);
  }, []);

  const load = useCallback(async () => {
    try {
      const r = await fetch('/api/engines');
      if (r.status === 404) {
        if (alive.current) setEngines([]);
        return;
      }
      if (!r.ok) throw new Error(`HTTP ${r.status}`);
      const d = await r.json();
      if (alive.current && Array.isArray(d?.engines)) {
        setEngines(d.engines);
        setError(null);
      }
    } catch {
      if (alive.current) setError('Could not load engine status.');
    }
  }, []);

  useEffect(() => {
    if (active) load();
  }, [active, load]);

  // Startup checks take a moment; look again until none is "checking" (each check caps at 10s).
  const anyChecking = !!engines?.some((e) => e.status === 'checking');
  useEffect(() => {
    if (!active || !anyChecking) return;
    const t = window.setTimeout(load, 1500);
    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);
    try {
      const r = await fetch('/api/engines/recheck', { method: 'POST' });
      if (!r.ok) throw new Error(`HTTP ${r.status}`);
      const d = await r.json();
      if (alive.current && Array.isArray(d?.engines)) setEngines(d.engines);
    } catch {
      if (alive.current) setError('Re-check failed. Is the server running?');
    } finally {
      if (alive.current) setRechecking(false);
    }
  }, []);

  const setEnabled = useCallback(
    async (id: EngineInfo['id'], enabled: boolean): Promise<boolean> => {
      // Shown at once; put back if the server says no.
      setEngines((list) => list?.map((e) => (e.id === id ? { ...e, enabled } : e)) ?? list);
      try {
        const r = await fetch(`/api/engines/${id}`, {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ enabled }),
        });
        if (!r.ok) throw new Error(`HTTP ${r.status}`);
        const d = await r.json().catch(() => null);
        if (alive.current && Array.isArray(d?.engines)) setEngines(d.engines);
        else await load();
        return true;
      } catch {
        if (!alive.current) return false;
        setEngines((list) => list?.map((e) => (e.id === id ? { ...e, enabled: !enabled } : e)) ?? list);
        setError(`Couldn't switch ${enabled ? 'on' : 'off'} that engine.`);
        return false;
      }
    },
    [load],
  );

  const apply = useCallback((list: EngineInfo[]) => {
    setEngines(list);
    setError(null);
  }, []);

  return { engines, error, rechecking, recheck, reload: load, setEnabled, apply };
}