+ )}
+ {errors && errors.length < total && (
+
+ )}
+
+ );
+}
diff --git a/services/frontend/src/app/admin/hibak/page.tsx b/services/frontend/src/app/admin/hibak/page.tsx
new file mode 100644
index 0000000..021fae9
--- /dev/null
+++ b/services/frontend/src/app/admin/hibak/page.tsx
@@ -0,0 +1,27 @@
+import type { Metadata } from "next";
+import { notFound } from "next/navigation";
+
+import { AdminNav } from "@/components/AdminNav";
+import { requireMe } from "@/lib/server";
+
+import { ErrorLog } from "./ErrorLog";
+
+export const metadata: Metadata = { title: "Hibanapló" };
+
+export default async function AdminErrorsPage() {
+ const me = await requireMe("/admin/hibak");
+ if (!me.user.roles.includes("admin")) notFound();
+ return (
+
+
+
+
Hibanapló
+
+ Az elemzések, válaszok és prompt-próbák minden sikertelen próbálkozása, a legújabb elöl. A worker írja; 90 napig
+ őrizzük.
+
+
+
+
+ );
+}
diff --git a/services/frontend/src/app/globals.css b/services/frontend/src/app/globals.css
index 138d7f3..ccd3e72 100644
--- a/services/frontend/src/app/globals.css
+++ b/services/frontend/src/app/globals.css
@@ -647,3 +647,13 @@ a.pair-row:hover strong { color: var(--gold); }
.job-row { display: grid; grid-template-columns: minmax(0, 1fr) auto auto; gap: 12px; align-items: center; padding: 8px 12px; border: 1px solid var(--line); border-radius: 8px; }
.job-row > span:first-child { display: flex; flex-direction: column; min-width: 0; }
@media (max-width: 640px) { .job-row { grid-template-columns: minmax(0, 1fr) auto; } .job-row .model-price { grid-column: 1 / -1; align-items: flex-start; } }
+.retry-notice { display: flex; flex-direction: column; gap: 4px; }
+.retry-notice p { margin: 0; }
+
+/* admin: error log */
+.error-log { width: 100%; border-collapse: collapse; font-size: 14px; }
+.error-log th, .error-log td { text-align: left; vertical-align: top; padding: 8px 10px; border-bottom: 1px solid var(--line); }
+.error-log td > .hint, .error-log td > code { display: block; }
+.error-log .error-text { overflow-wrap: anywhere; max-width: 460px; }
+.error-log .outcome { white-space: nowrap; }
+.error-log .outcome.tone-tense { color: var(--tense); font-weight: 600; }
diff --git a/services/frontend/src/components/AdminNav.tsx b/services/frontend/src/components/AdminNav.tsx
index d87aa0c..7d646fd 100644
--- a/services/frontend/src/components/AdminNav.tsx
+++ b/services/frontend/src/components/AdminNav.tsx
@@ -5,6 +5,7 @@ const PAGES = [
{ href: "/admin/meghivok", label: "Meghívók" },
{ href: "/admin/promptok", label: "Promptok" },
{ href: "/admin/modellek", label: "Modellek" },
+ { href: "/admin/hibak", label: "Hibanapló" },
];
/** Switches between the admin pages. */
diff --git a/services/frontend/src/components/AnalysisLoading.tsx b/services/frontend/src/components/AnalysisLoading.tsx
index 6e97a39..427e656 100644
--- a/services/frontend/src/components/AnalysisLoading.tsx
+++ b/services/frontend/src/components/AnalysisLoading.tsx
@@ -4,13 +4,31 @@ import { useEffect, useState } from "react";
import { ZodiacWheel } from "./ZodiacWheel";
-/** Slowly turning wheel with the elapsed time, while the LLM writes. */
-export function AnalysisLoading({ title, text, compact = false }: { title?: string; text: string; compact?: boolean }) {
- const [seconds, setSeconds] = useState(0);
+/**
+ * Slowly turning wheel with the elapsed time, while the LLM writes. The time
+ * counts from `since` (when the text was asked for), so it does not start
+ * again from zero after a reload; without it, from when the wheel appeared.
+ */
+export function AnalysisLoading({
+ title,
+ text,
+ compact = false,
+ since,
+}: {
+ title?: string;
+ text: string;
+ compact?: boolean;
+ since?: string;
+}) {
+ const [start] = useState(() => {
+ const t = since ? Date.parse(since) : NaN;
+ return Number.isNaN(t) ? Date.now() : Math.min(t, Date.now());
+ });
+ const [seconds, setSeconds] = useState(() => Math.floor((Date.now() - start) / 1000));
useEffect(() => {
- const t = setInterval(() => setSeconds((s) => s + 1), 1000);
+ const t = setInterval(() => setSeconds(Math.floor((Date.now() - start) / 1000)), 1000);
return () => clearInterval(t);
- }, []);
+ }, [start]);
const elapsed = `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;
return (
@@ -21,7 +39,7 @@ export function AnalysisLoading({ title, text, compact = false }: { title?: stri
{text}
-
+
{elapsed}
diff --git a/services/frontend/src/components/AnalysisQuestions.tsx b/services/frontend/src/components/AnalysisQuestions.tsx
index 0db7bd6..18108bb 100644
--- a/services/frontend/src/components/AnalysisQuestions.tsx
+++ b/services/frontend/src/components/AnalysisQuestions.tsx
@@ -8,6 +8,7 @@ import type { Question, UnitBalance } from "@/lib/types";
import { AnalysisLoading } from "./AnalysisLoading";
import { PackageChooser } from "./PackageCards";
import { RegenerateButton } from "./RegenerateButton";
+import { RetryNotice } from "./RetryNotice";
import { Paragraphs } from "./Rich";
const MAX_CHARS = 600;
@@ -139,12 +140,21 @@ export function AnalysisQuestions({
url={`/admin/questions/${q.id}/regenerate`} onStarted={replace} />
)}
- Erre most nem sikerült válaszolni{q.credits_charged > 0 ? ", a kérdést visszaadtuk" : ""}. Kérdezz újra
- egy kicsit később.
+ Erre többszöri próbálkozás után sem sikerült válaszolni
+ {q.credits_charged > 0 ? ". A kérdést visszaadtuk, így ingyen újra felteheted" : ""}. Kérdezz újra egy
+ kicsit később.
+ {isAdmin && q.error &&
Hiba: {q.error}
}
) : (
-
+ <>
+
+
+ >
)}
))}
diff --git a/services/frontend/src/components/ChartSummary.tsx b/services/frontend/src/components/ChartSummary.tsx
index 55d46e3..4ef1d37 100644
--- a/services/frontend/src/components/ChartSummary.tsx
+++ b/services/frontend/src/components/ChartSummary.tsx
@@ -7,6 +7,7 @@ import type { Analysis } from "@/lib/types";
import { AnalysisLoading } from "./AnalysisLoading";
import { RegenerateButton } from "./RegenerateButton";
+import { RetryNotice } from "./RetryNotice";
import { Rich } from "./Rich";
import { openTab } from "./Tabs";
@@ -102,7 +103,21 @@ export function ChartSummary({
Az összefoglaló most nem készült el. Töltsd újra az oldalt egy kicsit később.
- Az előző kérés nem sikerült{isAdmin ? "" : ", az elemzést visszaadtuk a keretedbe"}. Próbáld újra.
-
+
+
+ Az elemzés többszöri próbálkozás után sem készült el.
+ {isAdmin || analysis.credits_charged === 0
+ ? " Próbáld újra."
+ : " A felhasznált egységet visszaadtuk, így ingyen újra kérheted."}
+
+ {isAdmin && analysis.error &&
Hiba: {analysis.error}
}
+
)}
{error && (
diff --git a/services/frontend/src/components/RetryNotice.tsx b/services/frontend/src/components/RetryNotice.tsx
new file mode 100644
index 0000000..2298544
--- /dev/null
+++ b/services/frontend/src/components/RetryNotice.tsx
@@ -0,0 +1,28 @@
+/**
+ * Shown while a text is being written again after a failed attempt: it is
+ * retried on its own, nothing to do. Admins also see the error.
+ */
+export function RetryNotice({
+ status,
+ error,
+ nextAttemptAt,
+ isAdmin = false,
+}: {
+ status: string;
+ error?: string | null;
+ nextAttemptAt?: string;
+ isAdmin?: boolean;
+}) {
+ if (!error || (status !== "pending" && status !== "running")) return null;
+ const wait = nextAttemptAt ? Math.round((Date.parse(nextAttemptAt) - Date.now()) / 60_000) : 0;
+ return (
+
+
+ Az előző próbálkozás nem sikerült, ezért automatikusan újrapróbáljuk. Nem kell újra kérned, és nem kerül
+ többe.
+ {status === "pending" && wait >= 1 ? ` A következő próbálkozás kb. ${wait} perc múlva indul.` : ""}
+
+ {isAdmin &&
Hiba: {error}
}
+
+ );
+}
diff --git a/services/frontend/src/lib/types.ts b/services/frontend/src/lib/types.ts
index abb550c..c775533 100644
--- a/services/frontend/src/lib/types.ts
+++ b/services/frontend/src/lib/types.ts
@@ -77,6 +77,9 @@ export interface Question {
credits_charged: number;
created_at: string;
completed_at: string | null;
+ attempts?: number;
+ next_attempt_at?: string;
+ requested_at?: string;
}
export interface PublicConfig {
@@ -232,6 +235,26 @@ export interface Analysis {
credits_charged: number;
created_at: string;
completed_at: string | null;
+ /** Attempts so far, and when the next one starts (while it is retried). */
+ attempts?: number;
+ next_attempt_at?: string;
+ /** When the current text was asked for: the waiting page counts from here. */
+ requested_at?: string;
+}
+
+/** Admin: one failed attempt in the error log. */
+export interface GenerationError {
+ id: number;
+ created_at: string;
+ source: "analysis" | "question" | "preview";
+ item_id: string;
+ kind: string;
+ model: string;
+ attempt: number;
+ outcome: "retry" | "fallback" | "failed";
+ error: string;
+ seconds: number | null;
+ user: string | null;
}
export interface AdminUser {
diff --git a/services/worker/src/analysis/mod.rs b/services/worker/src/analysis/mod.rs
index e366c05..170e1ff 100644
--- a/services/worker/src/analysis/mod.rs
+++ b/services/worker/src/analysis/mod.rs
@@ -253,6 +253,8 @@ impl Analyzer {
.await
}
Err(e) => {
+ self.log_error("preview", job.id, &job.kind, &job.model, 1, "failed", e.message(), started.elapsed())
+ .await;
sqlx::query(
"UPDATE prompt_previews SET status = 'failed', error = $2, completed_at = now() \
WHERE id = $1 AND status = 'running'",
@@ -322,7 +324,24 @@ impl Analyzer {
}
Err(e) => {
let can_fall_back = !job.on_fallback && job.fallback_model.is_some();
- match next_step(&e, job.attempts, self.max_attempts, can_fall_back) {
+ let next = next_step(&e, job.attempts, self.max_attempts, can_fall_back);
+ let outcome = match next {
+ Next::Retry(_) => "retry",
+ Next::Fallback => "fallback",
+ Next::Fail => "failed",
+ };
+ self.log_error(
+ "analysis",
+ job.id,
+ &job.kind,
+ job.active_model(),
+ job.attempts,
+ outcome,
+ e.message(),
+ took,
+ )
+ .await;
+ match next {
Next::Retry(wait) => {
sqlx::query(
"UPDATE analyses SET status = 'pending', error = $2, \
@@ -424,6 +443,38 @@ impl Analyzer {
Ok(result.rows_affected())
}
+ /// Records a failed attempt in the admin error log (a failure here is only logged).
+ #[allow(clippy::too_many_arguments)]
+ pub(crate) async fn log_error(
+ &self,
+ source: &str,
+ item_id: Uuid,
+ kind: &str,
+ model: &str,
+ attempt: i32,
+ outcome: &str,
+ error: &str,
+ took: Duration,
+ ) {
+ let result = sqlx::query(
+ "INSERT INTO generation_errors (source, item_id, kind, model, attempt, outcome, error, seconds) \
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
+ )
+ .bind(source)
+ .bind(item_id)
+ .bind(kind)
+ .bind(model)
+ .bind(attempt)
+ .bind(outcome)
+ .bind(error.chars().take(2000).collect::())
+ .bind(i32::try_from(took.as_secs()).unwrap_or(i32::MAX))
+ .execute(&self.db)
+ .await;
+ if let Err(e) = result {
+ tracing::error!(error = %e, "writing the error log");
+ }
+ }
+
/// Resolves when this attempt is no longer the current one (an admin
/// restarted it); checked every 10 seconds, never on a database error.
async fn superseded(&self, table: &str, id: Uuid, started_at: time::OffsetDateTime) {
diff --git a/services/worker/src/analysis/questions.rs b/services/worker/src/analysis/questions.rs
index d5a7541..93caf15 100644
--- a/services/worker/src/analysis/questions.rs
+++ b/services/worker/src/analysis/questions.rs
@@ -148,7 +148,15 @@ impl Analyzer {
}
Err(e) => {
let can_fall_back = !job.on_fallback && job.fallback_model.is_some();
- match next_step(&e, job.attempts, self.max_attempts, can_fall_back) {
+ let next = next_step(&e, job.attempts, self.max_attempts, can_fall_back);
+ let outcome = match next {
+ Next::Retry(_) => "retry",
+ Next::Fallback => "fallback",
+ Next::Fail => "failed",
+ };
+ let model = active_model(&job.model, job.fallback_model.as_deref(), job.on_fallback);
+ self.log_error("question", job.id, "question", model, job.attempts, outcome, e.message(), took).await;
+ match next {
Next::Retry(wait) => {
sqlx::query(
"UPDATE questions SET status = 'pending', error = $2, \
diff --git a/services/worker/src/cleanup.rs b/services/worker/src/cleanup.rs
index 76d4e9a..fc8e3e0 100644
--- a/services/worker/src/cleanup.rs
+++ b/services/worker/src/cleanup.rs
@@ -8,7 +8,7 @@ use tokio::sync::watch;
const INTERVAL: Duration = Duration::from_secs(3600);
/// (what, statement) pairs; each returns the number of deleted rows.
-const STATEMENTS: [(&str, &str); 6] = [
+const STATEMENTS: [(&str, &str); 7] = [
("sessions", "DELETE FROM sessions WHERE expires_at < now()"),
("auth_tokens", "DELETE FROM auth_tokens WHERE expires_at < now()"),
// Sent e-mails contain links with tokens; keep them a week for support.
@@ -26,6 +26,7 @@ const STATEMENTS: [(&str, &str); 6] = [
OR (accepted_at IS NOT NULL AND accepted_by IS NULL)",
),
("prompt_previews", "DELETE FROM prompt_previews WHERE created_at < now() - interval '30 days'"),
+ ("generation_errors", "DELETE FROM generation_errors WHERE created_at < now() - interval '90 days'"),
];
pub async fn run_once(db: &PgPool) -> Result, sqlx::Error> {
diff --git a/services/worker/src/tests.rs b/services/worker/src/tests.rs
index 391c85d..0530c77 100644
--- a/services/worker/src/tests.rs
+++ b/services/worker/src/tests.rs
@@ -212,7 +212,8 @@ async fn cleanup_removes_only_expired_data(db: PgPool) {
("emails", 1),
("invites", 0),
("invitations", 0),
- ("prompt_previews", 0)
+ ("prompt_previews", 0),
+ ("generation_errors", 0)
]
);
let (left,): (Vec,) =
@@ -533,6 +534,18 @@ mod analyses {
let (status, attempts, ..) = row(&db, id).await;
assert_eq!((status.as_str(), attempts), ("failed", 3));
assert_eq!(refunds(&db, s.user).await, vec![1]);
+ // every failed attempt is in the admin error log
+ let log: Vec<(String, i32, String, String)> = sqlx::query_as(
+ "SELECT source, attempt, outcome, model FROM generation_errors WHERE item_id = $1 ORDER BY id",
+ )
+ .bind(id)
+ .fetch_all(&db)
+ .await
+ .unwrap();
+ let expected = |attempt: i32, outcome: &str| {
+ ("analysis".to_string(), attempt, outcome.to_string(), "test/model".to_string())
+ };
+ assert_eq!(log, vec![expected(1, "retry"), expected(2, "retry"), expected(3, "failed")]);
}
#[sqlx::test(migrator = "db::MIGRATOR")]
@@ -780,6 +793,16 @@ mod analyses {
let models: Vec =
fake.requests.lock().unwrap().iter().map(|b| b["model"].as_str().unwrap().to_string()).collect();
assert_eq!(models, ["cheap/model", "cheap/model", "test/model"]);
+ let outcomes: Vec<(String, String)> =
+ sqlx::query_as("SELECT outcome, model FROM generation_errors WHERE item_id = $1 ORDER BY id")
+ .bind(id)
+ .fetch_all(&db)
+ .await
+ .unwrap();
+ assert_eq!(
+ outcomes,
+ [("retry".to_string(), "cheap/model".to_string()), ("fallback".to_string(), "cheap/model".to_string())]
+ );
}
#[sqlx::test(migrator = "db::MIGRATOR")]