Files
sorsfonalak/services/frontend/src/app/admin/promptok/PromptTrial.tsx
T

196 lines
6.0 KiB
TypeScript
Raw Normal View History

"use client";
import { useCallback, useEffect, useState } from "react";
import { AnalysisLoading } from "@/components/AnalysisLoading";
import { AnalysisView } from "@/components/AnalysisView";
import { api, errorText } from "@/lib/api";
import { formatDate } from "@/lib/astro";
import type { ChartListItem, PromptKind, PromptPreview } from "@/lib/types";
const POLL_MS = 4000;
const MAX_POLLS = 150; // 10 minutes
interface Trial {
preview: PromptPreview;
/** The draft it was written with, to load it back. */
system: string;
}
/**
* Writes an analysis with the draft in the editor (saved or not) on one of
* the admin's charts. Nothing is stored with the chart.
*/
export function PromptTrial({
kind,
language,
draft,
charts,
onLoad,
}: {
kind: PromptKind;
language: string;
draft: string;
charts: ChartListItem[];
onLoad: (system: string) => void;
}) {
const [chartId, setChartId] = useState(charts.find((c) => c.is_primary)?.id ?? charts[0]?.id ?? "");
const [trials, setTrials] = useState<Trial[]>([]);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const selectId = `trial-chart-${kind}-${language}`;
async function start() {
setBusy(true);
setError(null);
try {
const preview = await api<PromptPreview>(`/admin/prompts/${kind}/${language}/preview`, {
body: { system: draft, chart_id: chartId },
});
setTrials((all) => [{ preview, system: draft }, ...all]);
} catch (e) {
setError(errorText(e));
} finally {
setBusy(false);
}
}
const update = useCallback(
(next: PromptPreview) =>
setTrials((all) => all.map((t) => (t.preview.id === next.id ? { ...t, preview: next } : t))),
[],
);
return (
<section className="prompt-trial" aria-labelledby={`${selectId}-title`}>
<div className="prompt-trial-head">
<h2 id={`${selectId}-title`}>Kipróbálás</h2>
<p className="hint">
A szerkesztőben lévő szöveggel (mentés nélkül is) megírja az elemzést egy saját képletedre. Az eredmény nem
kerül a képlethez, csak itt látod. Valódi modellhívás, ezért költsége van.
</p>
</div>
{charts.length === 0 ? (
<p className="muted">Kipróbáláshoz előbb legyen legalább egy képleted.</p>
) : (
<div className="prompt-trial-form">
<div className="field">
<label htmlFor={selectId}>Képlet</label>
<select id={selectId} className="inp" value={chartId} onChange={(e) => setChartId(e.target.value)}>
{charts.map((c) => (
<option key={c.id} value={c.id}>
{c.is_primary ? `Én (${c.label})` : c.label}
{c.birth.time ? "" : " – idő nélkül"}
</option>
))}
</select>
</div>
<button type="button" className="btn btn-primary" onClick={start} disabled={busy || !chartId || !draft.trim()}>
{busy ? "Indítás…" : "Kipróbálás"}
</button>
</div>
)}
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
{trials.map((t) => (
<TrialResult
key={t.preview.id}
trial={t}
chartLabel={charts.find((c) => c.id === t.preview.chart_id)?.label ?? "Képlet"}
changed={t.system.trim() !== draft.trim()}
onUpdate={update}
onLoad={() => onLoad(t.system)}
/>
))}
</section>
);
}
function TrialResult({
trial,
chartLabel,
changed,
onUpdate,
onLoad,
}: {
trial: Trial;
chartLabel: string;
changed: boolean;
onUpdate: (p: PromptPreview) => void;
onLoad: () => void;
}) {
const p = trial.preview;
const waiting = p.status === "pending" || p.status === "running";
useEffect(() => {
if (!waiting) return;
let polls = 0;
let stopped = false;
let timer: ReturnType<typeof setTimeout> | undefined;
const tick = async () => {
try {
const next = await api<PromptPreview>(`/admin/previews/${p.id}`);
if (stopped) return;
onUpdate(next);
if (next.status === "done" || next.status === "failed") return;
} catch {
// try again on the next tick
}
if (++polls < MAX_POLLS) timer = setTimeout(tick, POLL_MS);
};
timer = setTimeout(tick, POLL_MS);
return () => {
stopped = true;
clearTimeout(timer);
};
}, [waiting, p.id, onUpdate]);
const meta = [
p.model_used ?? p.model,
p.seconds !== null ? `${p.seconds} mp` : null,
p.input_tokens !== null && p.output_tokens !== null
? `${p.input_tokens.toLocaleString("hu-HU")} + ${p.output_tokens.toLocaleString("hu-HU")} token`
: null,
p.cost_usd !== null ? `$${p.cost_usd.toFixed(4)}` : null,
].filter(Boolean);
return (
<article className="trial" aria-busy={waiting}>
<header className="trial-head">
<div>
<strong>{chartLabel}</strong>
<span className="hint"> · {formatDate(p.created_at, true)}</span>
</div>
{changed && (
<button type="button" className="btn btn-sm" onClick={onLoad}>
Ennek a szövegnek a betöltése
</button>
)}
</header>
{waiting ? (
<AnalysisLoading
compact
text={p.kind === "summary" ? "Készül az összefoglaló, kb. 10–30 másodperc." : "Készül az elemzés, kb. 1–3 perc."}
/>
) : p.status === "failed" ? (
<p className="msg msg-error" role="alert">
Nem sikerült: {p.error ?? "ismeretlen hiba"}
</p>
) : p.content ? (
p.kind === "summary" ? (
<div className="trial-summary">
<h3 className="summary-title">{p.content.title}</h3>
<p className="summary-text">{p.content.summary}</p>
</div>
) : (
<AnalysisView content={p.content} />
)
) : null}
{meta.length > 0 && !waiting && <p className="hint">{meta.join(" · ")}</p>}
</article>
);
}