File size: 18,134 Bytes
a289b2a
33ce28f
a289b2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9c7101
a289b2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4545bb3
 
a289b2a
 
 
 
 
 
 
4545bb3
 
a289b2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
597e00d
 
 
 
 
a289b2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3810843
597e00d
 
 
 
3810843
 
 
 
 
a289b2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9c7101
a289b2a
f9c7101
a73107f
a289b2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33ce28f
 
 
 
 
 
a289b2a
 
 
 
33ce28f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
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, GraphSpec, 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<T> = Omit<UseQueryOptions<T>, '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<KillState>('/api/kill-switch'), refetchInterval: 10_000 });
export const useConfig = () => useQuery({ queryKey: ['config'], queryFn: () => getJson<Record<string, unknown>>('/api/config') });
export const useGraphSpec = () => useQuery({ queryKey: ['graph'], queryFn: () => getJson<GraphSpec>('/api/graph'), staleTime: Infinity });
export const usePodProfile = () => useQuery({ queryKey: ['pod'], queryFn: () => getJson<PodProfile>('/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 = <T,>(id: string, part: string, opts?: Opts<T>) =>
  useQuery<T>({ queryKey: ['run', id, part], queryFn: () => getJson<T>(`/api/runs/${encodeURIComponent(id)}/${part}`), ...opts });

export const useGate = (id: string, enabled = true) => useRunView<GatePayload | null>(id, 'gate', { enabled });
export const useResearch = (id: string) => useRunView<ResearchView>(id, 'research');
export const useCases = (id: string) => useRunView<CasesView>(id, 'cases');
export const useDataPlan = (id: string) => useRunView<DataView>(id, 'data-plan');
export const useScripts = (id: string) => useRunView<Record<string, ScriptRef>>(id, 'scripts');
export const useResults = (id: string) => useRunView<ResultsView>(id, 'results');
export const useReport = (id: string) => useRunView<ReportView>(id, 'report');
export const useEvidence = (id: string, enabled = true) => useRunView<Evidence[]>(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<Paged<HealProposal>>(`/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 useDrafts = (status?: string) =>
  useQuery({ queryKey: ['drafts', status ?? ''], queryFn: () => getJson<Paged<Draft>>(`/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<Paged<Ticket>>(`/api/tickets${runId ? `?run_id=${runId}` : ''}`) });
export const useTicket = (id: string | null) =>
  useQuery({ queryKey: ['ticket', id], enabled: !!id, queryFn: () => getJson<Ticket>(`/api/tickets/${id}`) });

// ------------------------------------------------------------------ learner / audit / admin
export const useHistory = (module?: string) =>
  useQuery({ queryKey: ['history', module ?? ''], queryFn: () => getJson<Paged<HistoryRow>>(`/api/learner/history?limit=200${module ? `&module=${module}` : ''}`) });
export const usePatterns = (module?: string) =>
  useQuery({ queryKey: ['patterns', module ?? ''], queryFn: () => getJson<Pattern[]>(`/api/learner/patterns${module ? `?module=${module}` : ''}`) });
export const useMetrics = () => useQuery({ queryKey: ['metrics'], queryFn: () => getJson<Record<string, Metrics>>('/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<Paged<AuditRow>>(`/api/audit?${p}`);
    },
  });
export const useAutonomy = () => useQuery({ queryKey: ['autonomy'], queryFn: () => getJson<Record<string, AutonomyRow>>('/api/autonomy') });
export const useSchedules = () => useQuery({ queryKey: ['schedules'], queryFn: () => getJson<Schedule[]>('/api/schedules') });
export const usePatchWatch = () => useQuery({ queryKey: ['patchwatch'], queryFn: () => getJson<PatchWatch>('/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),
});

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,
    }),
    testData: useMutation({
      mutationFn: ({ id, overrides }: { id: number; overrides: Record<string, Record<string, string | null>> }) =>
        unwrap(api.PUT('/api/pods/{pod_id}/test-data', { params: { path: { pod_id: id } }, body: { overrides } })),
      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<ReadinessView>(`/api/readiness?${p}`);
    },
  });
export const useRunReadiness = (id: string, enabled = true) => useRunView<ReadinessView>(id, 'readiness', { refetchInterval: 5000, enabled: enabled && !!id });
export const useLive = (id: string, enabled: boolean) => useRunView<LiveStatus>(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<Failure[]>(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<Paged<LibraryScenario> & { steps: string[] }>(`/api/scenarios?${p}`);
    },
  });
export const useScenario = (id: string | null, runId?: string) =>
  useQuery({ queryKey: ['scenario', id, runId ?? ''], enabled: !!id, queryFn: () => getJson<Scenario>(`/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; 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.';
  }
}