Spaces:
Runtime error
Runtime error
File size: 1,759 Bytes
cd8bd0a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | "use client";
import { useCallback, useEffect, useRef, useState } from "react";
import type { MemoryEngineStatus } from "@/shared/schemas/memory";
export interface UseEngineStatusResult {
status: MemoryEngineStatus | null;
isLoading: boolean;
isError: boolean;
mutate: () => Promise<void>;
}
/**
* Lightweight engine-status fetcher with periodic polling.
* Avoids the swr dependency (not installed in this project) while keeping a
* compatible mutate()/loading/error surface for callers.
*/
export function useEngineStatus(refreshIntervalMs = 5000): UseEngineStatusResult {
const [status, setStatus] = useState<MemoryEngineStatus | null>(null);
const [isLoading, setIsLoading] = useState<boolean>(true);
const [isError, setIsError] = useState<boolean>(false);
const mounted = useRef(true);
const fetchOnce = useCallback(async (): Promise<void> => {
try {
const res = await fetch("/api/memory/engine-status");
if (!res.ok) throw new Error(`status_${res.status}`);
const data = (await res.json()) as MemoryEngineStatus;
if (mounted.current) {
setStatus(data);
setIsError(false);
}
} catch {
if (mounted.current) setIsError(true);
} finally {
if (mounted.current) setIsLoading(false);
}
}, []);
useEffect(() => {
mounted.current = true;
void fetchOnce();
if (!refreshIntervalMs || refreshIntervalMs <= 0) {
return () => {
mounted.current = false;
};
}
const id = setInterval(() => {
void fetchOnce();
}, refreshIntervalMs);
return () => {
mounted.current = false;
clearInterval(id);
};
}, [fetchOnce, refreshIntervalMs]);
return { status, isLoading, isError, mutate: fetchOnce };
}
|