Files
sorsfonalak/services/frontend/src/app/admin/promptok/PromptTrial.tsx
T
fecoandClaude Opus 5.5 182d71fe65
CI / test (push) Successful in 1m5s
CI / build (push) Successful in 4m56s
CI / deploy (push) Skipped
Questions about an analysis or forecast, answered by the model that wrote it
- 3 questions in every package, +5 questions add-on (1 000 Ft); question units, refund on failure
- The answer sees the chart data, the analysis and earlier questions; at most 250 words
- Editable question prompt (Promptok → Kérdés-válasz); admins regenerate answers
- Package texts and FAQ updated

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-18 18:44:20 +00:00

323 lines
11 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"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 { listName } from "@/lib/synastry";
import type { ChartListItem, ForecastList, ForecastSummary, PromptKind, PromptPreview, SynastryListItem } 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 synastry = kind === "synastry";
const forecastKind = kind === "forecast";
const [chartId, setChartId] = useState(charts.find((c) => c.is_primary)?.id ?? charts[0]?.id ?? "");
const [synastries, setSynastries] = useState<SynastryListItem[]>([]);
const [synastryId, setSynastryId] = useState("");
useEffect(() => {
if (!synastry) return;
api<{ synastries: SynastryListItem[] }>("/synastries")
.then((d) => {
const own = d.synastries.filter((s) => s.owned);
setSynastries(own);
setSynastryId((current) => current || own[0]?.id || "");
})
.catch(() => setSynastries([]));
}, [synastry]);
// A forecast is tried on one of the chosen chart's calculated years.
const [forecasts, setForecasts] = useState<ForecastSummary[] | null>(null);
const [forecastId, setForecastId] = useState("");
const [allForecasts, setAllForecasts] = useState<ForecastSummary[]>([]);
useEffect(() => {
if (!forecastKind || !chartId) return;
setForecasts(null);
api<ForecastList>(`/charts/${chartId}/forecasts`)
.then((d) => {
setForecasts(d.forecasts);
setForecastId(d.forecasts[0]?.id ?? "");
setAllForecasts((all) => [...all.filter((f) => f.chart_id !== chartId), ...d.forecasts]);
})
.catch(() => setForecasts([]));
}, [forecastKind, chartId]);
const targetId = synastry ? synastryId : forecastKind ? forecastId : chartId;
const forecastName = (f: ForecastSummary) => `${f.year}–${f.year + 1} · ${f.place ?? "születési hely"}`;
const comparisonName = (s: SynastryListItem) => `${listName(s.chart1, charts)} és ${listName(s.chart2, charts)}`;
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: synastry
? { system: draft, synastry_id: synastryId }
: forecastKind
? { system: draft, forecast_id: forecastId }
: { 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{" "}
{synastry ? "összevetésedre" : forecastKind ? "előrejelzésedre" : "képletedre"}. Az eredmény nem kerül{" "}
{synastry ? "az összevetéshez" : forecastKind ? "az előrejelzéshez" : "a képlethez"},
csak itt látod. Valódi modellhívás, ezért költsége van.
</p>
</div>
{synastry && synastries.length === 0 ? (
<p className="muted">
Kipróbáláshoz előbb készíts egy összevetést az <a href="/osszevetesek">Összevetések</a> oldalon.
</p>
) : synastry ? (
<div className="prompt-trial-form">
<div className="field">
<label htmlFor={selectId}>Összevetés</label>
<select id={selectId} className="inp" value={synastryId} onChange={(e) => setSynastryId(e.target.value)}>
{synastries.map((s) => (
<option key={s.id} value={s.id}>
{comparisonName(s)}
</option>
))}
</select>
</div>
<button type="button" className="btn btn-primary" onClick={start} disabled={busy || !targetId || !draft.trim()}>
{busy ? "Indítás…" : "Kipróbálás"}
</button>
</div>
) : charts.length === 0 ? (
<p className="muted">Kipróbáláshoz előbb legyen legalább egy képleted.</p>
) : forecastKind ? (
<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>
{forecasts === null ? (
<p className="hint">Betöltés…</p>
) : forecasts.length === 0 ? (
<p className="muted">
Ehhez a képlethez még nincs kiszámolt év. Előbb kérj egyet az{" "}
<a href={`/kepletek/${chartId}/elorejelzes`}>előrejelzés oldalán</a> (a számítás ingyenes).
</p>
) : (
<>
<div className="field">
<label htmlFor={`${selectId}-year`}>Év</label>
<select
id={`${selectId}-year`}
className="inp"
value={forecastId}
onChange={(e) => setForecastId(e.target.value)}
>
{forecasts.map((f) => (
<option key={f.id} value={f.id}>
{forecastName(f)}
</option>
))}
</select>
</div>
<button
type="button"
className="btn btn-primary"
onClick={start}
disabled={busy || !targetId || !draft.trim()}
>
{busy ? "Indítás…" : "Kipróbálás"}
</button>
</>
)}
</div>
) : (
<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={
t.preview.forecast_id
? (() => {
const f = allForecasts.find((x) => x.id === t.preview.forecast_id);
const c = f && charts.find((x) => x.id === f.chart_id);
return f ? `${c?.label ?? "Képlet"}, ${forecastName(f)}` : "Előrejelzés";
})()
: t.preview.synastry_id
? (() => {
const s = synastries.find((x) => x.id === t.preview.synastry_id);
return s ? comparisonName(s) : "Összevetés";
})()
: (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."
: p.kind === "forecast"
? "Készül az előrejelzés, kb. 2–4 perc."
: "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} kind={p.kind === "question" ? "natal" : p.kind} />
)
) : null}
{meta.length > 0 && !waiting && <p className="hint">{meta.join(" · ")}</p>}
</article>
);
}