import { useCallback, useEffect, useState } from 'react' import { api } from './api.js' // The server owns the job. Closing this tab only stops polling, not inference. export function useInferenceJob(sessionId, enabled) { const [job, setJob] = useState(null) const [error, setError] = useState('') const [revision, setRevision] = useState(0) const refresh = useCallback(() => setRevision(value => value + 1), []) useEffect(() => { if (!enabled) return const controller = new AbortController() let timer async function poll() { try { const jobs = await api(`/sessions/${sessionId}/jobs`, { signal: controller.signal }) if (controller.signal.aborted) return const latest = Array.isArray(jobs) ? jobs[0] : null setJob(latest || null) setError('') if (latest && ['queued', 'running'].includes(latest.state)) timer = setTimeout(poll, 1500) } catch (failure) { if (!controller.signal.aborted) { setError(failure.message) timer = setTimeout(poll, 4000) } } } poll() return () => { controller.abort(); clearTimeout(timer) } }, [sessionId, enabled, revision]) async function command(path) { setError('') try { const next = await api(path, { method: 'POST' }) setJob(next) refresh() return next } catch (failure) { setError(failure.message); throw failure } } return { job, error, refresh, start: () => command(`/sessions/${sessionId}/jobs`), cancel: () => command(`/jobs/${job.id}/cancel`), retry: () => command(`/jobs/${job.id}/retry`) } }