SPB Git

Repository Public

job.tsx 4.6 KB 65 lines tsx

1"use client";2import { useEffect, useRef, useState } from "react";3import { useLocale } from "@/i18n/client";4import { api } from "@/lib/client-api";5import type { JobView } from "@/server/jobs";6import { money, Spinner } from "./ui";78const STAGES: Record<string, [string, string]> = {9  queued: ["En file d’attente", "Queued"], starting: ["Démarrage", "Starting"], extract: ["Lecture des documents fournis", "Reading the supplied material"],10  outline: ["Claude prépare le plan", "Claude is planning"], "outline.repair": ["Correction du plan", "Fixing the plan"],11  generate: ["Claude rédige la fiche", "Claude is writing the sheet"], "generate.repair": ["Correction du document (validation du schéma)", "Fixing the document (schema validation)"],12  edit: ["Claude prépare la modification", "Claude is preparing the change"], "edit.repair": ["Correction de la modification", "Fixing the change"],13  translate: ["Traduction en cours", "Translating"], "translate.repair": ["Correction de la traduction", "Fixing the translation"],14  verify_sources: ["Vérification des sources", "Checking the sources"], validate: ["Contrôle qualité", "Quality checks"], save: ["Enregistrement du brouillon", "Saving the draft"],15  waiting_retry: ["Nouvel essai dans un instant", "Retrying shortly"], done: ["Terminé", "Done"], failed: ["Échec", "Failed"], cancelled: ["Annulé", "Cancelled"],16};17const finished = (j: JobView) => j.status === "succeeded" || j.status === "failed" || j.status === "cancelled";1819/**20 * Follows a job through server-sent events (falls back to polling if the stream drops) and reports each state.21 * The job itself lives on the server: closing the page does not stop it, and reopening it resumes the display.22 */23export function useJob(jobId: string | null, onDone?: (job: JobView) => void) {24  const [job, setJob] = useState<JobView | null>(null);25  const done = useRef(onDone); done.current = onDone;26  useEffect(() => {27    if (!jobId) { setJob(null); return; }28    let closed = false, poll: ReturnType<typeof setInterval> | null = null, notified = false;29    const take = (j: JobView) => { if (closed) return; setJob(j); if (finished(j) && !notified) { notified = true; done.current?.(j); } };30    const startPolling = () => { if (poll || closed) return; poll = setInterval(() => { void api<JobView>(`/api/admin/generations/${jobId}`).then((j) => { take(j); if (finished(j) && poll) clearInterval(poll); }).catch(() => {}); }, 1500); };31    const es = new EventSource(`/api/admin/generations/${jobId}/events`);32    es.addEventListener("job", (e) => { const j = JSON.parse((e as MessageEvent<string>).data) as JobView; take(j); if (finished(j)) es.close(); });33    es.onerror = () => { es.close(); if (!notified) startPolling(); };34    return () => { closed = true; es.close(); if (poll) clearInterval(poll); };35  }, [jobId]);36  return job;37}3839export function JobProgress({ job, onCancel }: { job: JobView; onCancel?: () => void }) {40  const fr = useLocale() === "fr";41  const [cancelling, setCancelling] = useState(false);42  const p = (job.progress ?? {}) as { chars?: number; done?: number; total?: number };43  const label = STAGES[job.stage]?.[fr ? 0 : 1] ?? job.stage;44  const active = job.status === "queued" || job.status === "running";45  const cancel = async () => { setCancelling(true); try { await api(`/api/admin/generations/${job.id}/cancel`, { method: "POST", body: {} }); onCancel?.(); } catch { setCancelling(false); } };46  return (47    <div className="card px-4 py-3" role="status" aria-live="polite">48      <div className="flex items-center gap-3">49        {active && <Spinner />}50        <div className="min-w-0 flex-1">51          <p className="font-semibold">{label}</p>52          <p className="text-sm text-faint">53            {p.chars ? `${p.chars.toLocaleString(fr ? "fr-CA" : "en-CA")} ${fr ? "caractères reçus" : "characters received"} · ` : ""}54            {p.total ? `${p.done ?? 0}/${p.total} · ` : ""}55            {job.model ? `${job.model} · ` : ""}{job.usage.costUsd > 0 ? `${fr ? "coût réel" : "actual cost"} ${money(job.usage.costUsd)}` : fr ? "aucun coût pour l’instant" : "no cost so far"}56            {job.attempts > 1 ? ` · ${fr ? "essai" : "attempt"} ${job.attempts}` : ""}57          </p>58        </div>59        {active && <button type="button" className="btn btn-sm" onClick={cancel} disabled={cancelling || job.cancelRequested}>{cancelling || job.cancelRequested ? (fr ? "Annulation…" : "Cancelling…") : fr ? "Annuler" : "Cancel"}</button>}60      </div>61      {job.status === "failed" && job.error && <p className="mt-2 rounded-lg border border-bad/40 bg-bad/10 px-3 py-2 text-sm" role="alert">{job.error.message}</p>}62    </div>63  );64}65
Files main
Menu

Theme