import { useMutation, useQuery, useQueryClient, type UseQueryOptions } from '@tanstack/react-query'; import { api, ApiError, getJson, unwrap, type Schemas } from './client'; import type { AuditRow, AutonomyRow, CasesView, DataView, Draft, Evidence, Failure, LiveStatus, GatePayload, ControlHeal, GraphSpec, HealedStep, HealProposal, HistoryRow, KillState, LibraryScenario, Metrics, ReadinessView, Scenario, Paged, PatchWatch, Pattern, PodProfile, ReportView, ResearchView, ResultsView, Schedule, ScriptRef, Ticket, } from './types'; const ACTIVE = new Set(['queued', 'running']); export const isActive = (s?: string | null) => !!s && ACTIVE.has(s); type Opts = Omit, 'queryKey' | 'queryFn'>; // ------------------------------------------------------------------ system export const useHealth = () => useQuery({ queryKey: ['health'], queryFn: () => unwrap(api.GET('/api/health')), refetchInterval: 10_000 }); export const useKill = () => useQuery({ queryKey: ['kill'], queryFn: () => getJson('/api/kill-switch'), refetchInterval: 10_000 }); export const useConfig = () => useQuery({ queryKey: ['config'], queryFn: () => getJson>('/api/config') }); export const useGraphSpec = () => useQuery({ queryKey: ['graph'], queryFn: () => getJson('/api/graph'), staleTime: Infinity }); export const usePodProfile = () => useQuery({ queryKey: ['pod'], queryFn: () => getJson('/api/pod/profile') }); // ------------------------------------------------------------------ runs export const useRuns = (limit = 25, offset = 0, status?: string) => useQuery({ queryKey: ['runs', limit, offset, status ?? ''], queryFn: () => unwrap(api.GET('/api/runs', { params: { query: { limit, offset, ...(status ? { status } : {}) } } })), refetchInterval: 4000, }); export const useRun = (id: string, enabled = true) => useQuery({ queryKey: ['run', id], enabled, queryFn: () => unwrap(api.GET('/api/runs/{run_id}', { params: { path: { run_id: id } } })), refetchInterval: (q) => (q.state.data && ['completed', 'failed', 'killed', 'cancelled'].includes(q.state.data.status) ? false : 3000), }); const useRunView = (id: string, part: string, opts?: Opts) => useQuery({ queryKey: ['run', id, part], queryFn: () => getJson(`/api/runs/${encodeURIComponent(id)}/${part}`), ...opts }); export const useGate = (id: string, enabled = true) => useRunView(id, 'gate', { enabled }); export const useResearch = (id: string) => useRunView(id, 'research'); export const useCases = (id: string) => useRunView(id, 'cases'); export const useDataPlan = (id: string) => useRunView(id, 'data-plan'); export const useScripts = (id: string) => useRunView>(id, 'scripts'); export const useResults = (id: string) => useRunView(id, 'results'); export const useReport = (id: string) => useRunView(id, 'report'); export const useEvidence = (id: string, enabled = true) => useRunView(id, 'evidence', { enabled: enabled && !!id }); export const useTemporal = (id: string) => useQuery({ queryKey: ['run', id, 'temporal'], retry: false, refetchInterval: 5000, queryFn: () => getJson<{ status?: string; error?: string; ui?: string; query?: { status: string; step: string | null } | null }>(`/api/runs/${encodeURIComponent(id)}/temporal`) }); export const useCaseYaml = (caseId: string | null) => useQuery({ queryKey: ['yaml', caseId], enabled: !!caseId, queryFn: () => getJson<{ yaml: string; path: string }>(`/api/cases/${caseId}/yaml`) }); export function useStartRun() { const qc = useQueryClient(); return useMutation({ mutationFn: (body: Schemas['RunCreate']) => unwrap(api.POST('/api/runs', { body })), onSuccess: () => qc.invalidateQueries({ queryKey: ['runs'] }), }); } export function useRunAction() { const qc = useQueryClient(); return useMutation({ mutationFn: ({ id, action, reason }: { id: string; action: 'resume' | 'cancel'; reason?: string }) => action === 'resume' ? unwrap(api.POST('/api/runs/{run_id}/resume', { params: { path: { run_id: id } } })) : unwrap(api.POST('/api/runs/{run_id}/cancel', { params: { path: { run_id: id } }, body: { reason: reason ?? '' } })), onSuccess: (_d, v) => { qc.invalidateQueries({ queryKey: ['runs'] }); qc.invalidateQueries({ queryKey: ['run', v.id] }); }, }); } export function useApproveCases(id: string) { const qc = useQueryClient(); return useMutation({ mutationFn: (body: Schemas['ApproveCasesIn']) => unwrap(api.POST('/api/runs/{run_id}/gates/approve_cases', { params: { path: { run_id: id } }, body })), // success, or NOT_AT_GATE (answered elsewhere): either way show where the run is now onSettled: () => qc.invalidateQueries({ queryKey: ['run', id] }), }); } export function useHumanReview(id: string) { const qc = useQueryClient(); return useMutation({ mutationFn: (body: Schemas['HumanReviewIn']) => unwrap(api.POST('/api/runs/{run_id}/gates/human_review', { params: { path: { run_id: id } }, body })), // success, or NOT_AT_GATE (answered elsewhere): either way show where the run is now onSettled: () => qc.invalidateQueries({ queryKey: ['run', id] }), }); } // ------------------------------------------------------------------ review queues export const useHeal = (status?: string) => useQuery({ queryKey: ['heal', status ?? ''], queryFn: () => getJson>(`/api/heal-proposals${status ? `?status=${status}` : ''}`) }); export function useHealDecision() { const qc = useQueryClient(); return useMutation({ mutationFn: ({ id, decision, note }: { id: number; decision: 'approve' | 'reject'; note?: string }) => unwrap(api.POST('/api/heal-proposals/{pid}/decision', { params: { path: { pid: id } }, body: { decision, note: note ?? null } })), onSuccess: () => qc.invalidateQueries({ queryKey: ['heal'] }), }); } export const useControlHeals = (q: { status?: string; run_id?: string }) => { const qs = new URLSearchParams(Object.entries(q).filter(([, v]) => v) as [string, string][]).toString(); return useQuery({ queryKey: ['heals', q], queryFn: () => getJson>(`/api/heals${qs ? `?${qs}` : ''}`) }); }; export const useRunHeals = (id: string) => useQuery({ queryKey: ['heals', 'run', id], enabled: !!id, queryFn: () => getJson<{ healed: HealedStep[] }>(`/api/runs/${encodeURIComponent(id)}/heals`) }); export function useControlHealDecision() { const qc = useQueryClient(); return useMutation({ mutationFn: ({ id, decision }: { id: number; decision: 'approve' | 'reject' }) => unwrap(api.POST('/api/heals/{hid}/decision', { params: { path: { hid: id } }, body: { decision, note: null } })), onSuccess: () => qc.invalidateQueries({ queryKey: ['heals'] }), }); } export const useDrafts = (status?: string) => useQuery({ queryKey: ['drafts', status ?? ''], queryFn: () => getJson>(`/api/drafts${status ? `?status=${status}` : ''}`) }); export function useDraftAction() { const qc = useQueryClient(); return useMutation({ mutationFn: ({ id, action }: { id: number; action: 'promote' | 'discard' }) => action === 'promote' ? unwrap(api.POST('/api/drafts/{did}/promote', { params: { path: { did: id } }, body: { note: null } })) : unwrap(api.POST('/api/drafts/{did}/discard', { params: { path: { did: id } } })), onSuccess: () => qc.invalidateQueries({ queryKey: ['drafts'] }), }); } export const useTickets = (runId?: string) => useQuery({ queryKey: ['tickets', runId ?? ''], queryFn: () => getJson>(`/api/tickets${runId ? `?run_id=${runId}` : ''}`) }); export const useTicket = (id: string | null) => useQuery({ queryKey: ['ticket', id], enabled: !!id, queryFn: () => getJson(`/api/tickets/${id}`) }); // ------------------------------------------------------------------ learner / audit / admin export const useHistory = (module?: string) => useQuery({ queryKey: ['history', module ?? ''], queryFn: () => getJson>(`/api/learner/history?limit=200${module ? `&module=${module}` : ''}`) }); export const usePatterns = (module?: string) => useQuery({ queryKey: ['patterns', module ?? ''], queryFn: () => getJson(`/api/learner/patterns${module ? `?module=${module}` : ''}`) }); export const useMetrics = () => useQuery({ queryKey: ['metrics'], queryFn: () => getJson>('/api/learner/metrics') }); export const useAudit = (q: { kind?: string; run_id?: string; limit: number; offset: number }) => useQuery({ queryKey: ['audit', q], queryFn: () => { const p = new URLSearchParams({ limit: String(q.limit), offset: String(q.offset) }); if (q.kind) p.set('kind', q.kind); if (q.run_id) p.set('run_id', q.run_id); return getJson>(`/api/audit?${p}`); }, }); export const useAutonomy = () => useQuery({ queryKey: ['autonomy'], queryFn: () => getJson>('/api/autonomy') }); export const useSchedules = () => useQuery({ queryKey: ['schedules'], queryFn: () => getJson('/api/schedules') }); export const usePatchWatch = () => useQuery({ queryKey: ['patchwatch'], queryFn: () => getJson('/api/patch-watch') }); export const useUsers = () => useQuery({ queryKey: ['users'], queryFn: () => unwrap(api.GET('/api/users')) }); export const useLibraryLog = () => useQuery({ queryKey: ['library'], queryFn: () => getJson<{ sha: string; author: string; date: string; message: string }[]>('/api/library/log?limit=20') }); // ------------------------------------------------------------------ pods (target test environments) export type Pod = Schemas['PodRow']; export const usePods = () => useQuery({ queryKey: ['pods'], queryFn: () => unwrap(api.GET('/api/pods')), // while a pod's screens are being read (many minutes, in the background), follow its progress refetchInterval: (q) => ((q.state.data ?? []).some((p) => (p.screens as { state?: string } | null | undefined)?.state === 'running') ? 5000 : false), }); // test documents a run left on a Fusion pod that only a person can undo (the "Left on the pod" page) export type LeftDoc = Schemas['LeftOnPodRow']; export type LeftFilters = { pod_id?: number; status?: LeftDoc['status']; kind?: string }; export const useLeftOnPod = (f: LeftFilters) => useQuery({ queryKey: ['left-on-pod', f], queryFn: () => unwrap(api.GET('/api/left-on-pod', { params: { query: { limit: 500, ...(f.pod_id ? { pod_id: f.pod_id } : {}), ...(f.status ? { status: f.status } : {}), ...(f.kind ? { kind: f.kind } : {}) } } })), }); export function useLeftOnPodActions() { const qc = useQueryClient(); const done = () => Promise.all([qc.invalidateQueries({ queryKey: ['left-on-pod'] }), qc.invalidateQueries({ queryKey: ['pods'] })]); return { decide: useMutation({ mutationFn: ({ id, decision, note }: { id: number; decision: 'done' | 'dismiss' | 'reopen'; note?: string }) => unwrap(api.POST('/api/left-on-pod/{row_id}/decision', { params: { path: { row_id: id } }, body: { decision, note: note || null } })), onSuccess: done, }), recheck: useMutation({ mutationFn: (id: number) => unwrap(api.POST('/api/left-on-pod/{row_id}/recheck', { params: { path: { row_id: id } } })), onSuccess: done, }), }; } // how the client uses each business area of a Fusion pod, and which used variants the scenario library covers export const usePodUsage = (id: number, enabled = true) => useQuery({ queryKey: ['pod-usage', id], enabled, queryFn: () => unwrap(api.GET('/api/pods/{pod_id}/usage', { params: { path: { pod_id: id } } })), }); export const usePodCoverage = (id: number, enabled = true) => useQuery({ queryKey: ['pod-coverage', id], enabled, queryFn: () => unwrap(api.GET('/api/pods/{pod_id}/coverage', { params: { path: { pod_id: id } } })), }); export function usePodMutations() { const qc = useQueryClient(); const done = () => qc.invalidateQueries({ queryKey: ['pods'] }); return { create: useMutation({ mutationFn: (body: Schemas['PodIn']) => unwrap(api.POST('/api/pods', { body })), onSuccess: done }), update: useMutation({ mutationFn: ({ id, body }: { id: number; body: Schemas['PodUpdate'] }) => unwrap(api.PATCH('/api/pods/{pod_id}', { params: { path: { pod_id: id } }, body })), onSuccess: done, }), remove: useMutation({ mutationFn: (id: number) => unwrap(api.DELETE('/api/pods/{pod_id}', { params: { path: { pod_id: id } } })), onSuccess: done }), credential: useMutation({ mutationFn: ({ id, body }: { id: number; body: Schemas['PodCredentialIn'] }) => unwrap(api.POST('/api/pods/{pod_id}/credentials', { params: { path: { pod_id: id } }, body })), onSuccess: done, }), test: useMutation({ mutationFn: (id: number) => unwrap(api.POST('/api/pods/{pod_id}/test', { params: { path: { pod_id: id } } })), onSuccess: done }), discover: useMutation({ mutationFn: (id: number) => unwrap(api.POST('/api/pods/{pod_id}/discover', { params: { path: { pod_id: id } } })), onSuccess: done }), readScreens: useMutation({ mutationFn: (id: number) => unwrap(api.POST('/api/pods/{pod_id}/screens/read', { params: { path: { pod_id: id } }, body: { areas: [], max_tasks: 4 } })), onSuccess: done, }), readUsage: useMutation({ mutationFn: (id: number) => unwrap(api.POST('/api/pods/{pod_id}/usage', { params: { path: { pod_id: id } }, body: { days: 90 } })), onSuccess: (_d, id) => Promise.all([done(), qc.invalidateQueries({ queryKey: ['pod-usage', id] }), qc.invalidateQueries({ queryKey: ['pod-coverage', id] })]), }), testData: useMutation({ mutationFn: ({ id, overrides }: { id: number; overrides: Record> }) => unwrap(api.PUT('/api/pods/{pod_id}/test-data', { params: { path: { pod_id: id } }, body: { overrides } })), onSuccess: done, }), navLinks: useMutation({ mutationFn: ({ id, links }: { id: number; links: Record }) => unwrap(api.PUT('/api/pods/{pod_id}/nav-links', { params: { path: { pod_id: id } }, body: { links } })), onSuccess: done, }), }; } // ------------------------------------------------------------------ consultant views export const useReadiness = (podId: number | null | undefined, patch: string | null, modules?: string) => useQuery({ queryKey: ['readiness', podId ?? '', patch ?? '', modules ?? ''], refetchInterval: 8000, queryFn: () => { const p = new URLSearchParams(); if (podId) p.set('pod_id', String(podId)); if (patch) p.set('patch_id', patch); if (modules) p.set('modules', modules); return getJson(`/api/readiness?${p}`); }, }); export const useRunReadiness = (id: string, enabled = true) => useRunView(id, 'readiness', { refetchInterval: 5000, enabled: enabled && !!id }); export const useLive = (id: string, enabled: boolean) => useRunView(id, 'live', { enabled, refetchInterval: 2000 }); export const useRunScenarios = (id: string) => useRunView<{ scenarios: Scenario[]; deferred: { id: string; reason: string }[] }>(id, 'scenarios', { enabled: !!id }); export const useRunFailures = (id: string, enabled = true) => useRunView(id, 'failures', { refetchInterval: 5000, enabled: enabled && !!id }); export const useScenarioLibrary = (q: { module?: string; step?: string; priority?: string; q?: string; limit: number; offset: number }) => useQuery({ queryKey: ['scenarios', q], queryFn: () => { const p = new URLSearchParams({ limit: String(q.limit), offset: String(q.offset) }); for (const k of ['module', 'step', 'priority', 'q'] as const) if (q[k]) p.set(k, q[k]!); return getJson & { steps: string[] }>(`/api/scenarios?${p}`); }, }); export const useScenario = (id: string | null, runId?: string) => useQuery({ queryKey: ['scenario', id, runId ?? ''], enabled: !!id, queryFn: () => getJson(`/api/scenarios/${id}${runId ? `?run_id=${runId}` : ''}`) }); export function useSignOff(id: string) { const qc = useQueryClient(); return useMutation({ mutationFn: (comment: string) => unwrap(api.POST('/api/runs/{run_id}/signoff', { params: { path: { run_id: id } }, body: { comment: comment || null } })), onSuccess: () => qc.invalidateQueries({ queryKey: ['run', id] }), }); } /** Whether the app's data is being saved to backup storage (public /api/ready); refreshed once a minute. */ export type SavedState = { on: boolean; ok: boolean | null; paused?: boolean; paused_reason?: 'restore_failed' | 'fenced' | null; last_saved_at?: string | null }; export const useSavedState = () => useQuery({ queryKey: ['saved-state'], refetchInterval: 60_000, retry: false, queryFn: async () => (await getJson<{ saved_state?: SavedState }>('/api/ready')).saved_state ?? null }); // ------------------------------------------------------------------ product identity (public: also used on the sign-in page) export const useBrand = () => useQuery({ queryKey: ['brand'], staleTime: Infinity, retry: false, queryFn: () => getJson<{ product_name?: string; org_name?: string; version?: string; browser_runs?: boolean }>('/api/ready') }); // ------------------------------------------------------------------ Hermes assistant ("Ask", when an admin switched it on) export type AssistantStatus = Schemas['AssistantStatus']; export type AskOut = Schemas['AskOut']; /** Whether Ask goes to the Hermes assistant: on, configured (and reachable when known). Checked once a minute. */ export const useAssistantStatus = () => useQuery({ queryKey: ['assistant-status'], queryFn: () => unwrap(api.GET('/api/assistant/status')), staleTime: 60_000, refetchInterval: 60_000, retry: false }); /** An ApiError that also carries the Retry-After seconds of a 429. */ export class AskError extends ApiError { retryAfter: number | null; constructor(e: ApiError, retryAfter: number | null) { super(e.status, e.code, e.message, e.body, e.requestId); this.retryAfter = retryAfter; } } /** One question to Hermes; pass the returned conversation_id with the next one to keep the conversation. */ export function useAssistantAsk() { const qc = useQueryClient(); return useMutation({ mutationFn: async (body: Schemas['AskIn']) => { const res = await api.POST('/api/assistant/ask', { body }); try { return await unwrap(Promise.resolve(res)); } catch (e) { const after = Number(res.response.headers.get('Retry-After')); throw e instanceof ApiError ? new AskError(e, Number.isFinite(after) && after > 0 ? after : null) : e; } }, onError: (e) => { if (e instanceof ApiError && [409, 503].includes(e.status)) qc.invalidateQueries({ queryKey: ['assistant-status'] }); }, }); } /** Plain words for a failed Ask: what happened and what to do. Never the raw error. */ export function askErrorWords(e: unknown): string { const err = e as { status?: number; code?: string; retryAfter?: number | null }; switch (err.code) { case 'HERMES_OFF': return 'The Hermes assistant has just been switched off. Ask again and the built-in assistant answers.'; case 'HERMES_NOT_CONFIGURED': return 'The Hermes assistant is not set up yet. Ask an administrator, or ask again later.'; case 'HERMES_BUSY': return 'The Hermes assistant is busy with other questions. Try again in a minute.'; case 'HERMES_TIMEOUT': return 'The Hermes assistant took too long to answer. Try a shorter question, or try again.'; case 'HERMES_UNREACHABLE': return 'The Hermes assistant cannot be reached right now. Try again later.'; case 'HERMES_KEY_REJECTED': return 'The Hermes assistant refused the connection. Ask an administrator to check its key.'; case 'RATE_LIMITED': return `You have asked many questions in a short time. Try again${err.retryAfter ? ` in ${err.retryAfter} seconds` : ' in a minute'}.`; case 'HERMES_ERROR': return 'The Hermes assistant ran into a problem. Try again in a minute.'; case 'HERMES_EMPTY': return 'The Hermes assistant sent an empty answer. Rephrase the question, or try again.'; case 'HERMES_REFUSED': return 'The Hermes assistant did not accept this question. Rephrase it, or ask again later.'; case 'KILL_SWITCH': return 'The emergency stop is on, so no question is sent outside this app.'; case 'BAD_TEXT': return 'A question needs between 1 and 2,000 characters.'; case 'NOT_FOUND': return 'This conversation is no longer available. Ask again to start a new one.'; default: if (err.status === 429) return `You have asked many questions in a short time. Try again${err.retryAfter ? ` in ${err.retryAfter} seconds` : ' in a minute'}.`; if (err.status === 504) return 'The Hermes assistant took too long to answer. Try again.'; if (err.status === 503) return 'The Hermes assistant is busy or not available. Try again in a minute.'; return 'The Hermes assistant could not answer. Try again.'; } }