diff --git a/crates/db/migrations/0005_chart_summaries.sql b/crates/db/migrations/0005_chart_summaries.sql new file mode 100644 index 0000000..dd1bd11 --- /dev/null +++ b/crates/db/migrations/0005_chart_summaries.sql @@ -0,0 +1,14 @@ +-- Free short summaries: a few sentences about a natal chart, written by a +-- cheap model when the chart is saved. The detailed analyses stay paid. + +ALTER TABLE analyses DROP CONSTRAINT analyses_kind_check; +ALTER TABLE analyses ADD CONSTRAINT analyses_kind_check CHECK (kind IN ('natal', 'synastry', 'summary')); + +ALTER TABLE analyses DROP CONSTRAINT analyses_target; +ALTER TABLE analyses ADD CONSTRAINT analyses_target CHECK ( + (kind IN ('natal', 'summary') AND chart_id IS NOT NULL AND synastry_id IS NULL) + OR (kind = 'synastry' AND synastry_id IS NOT NULL AND chart_id IS NULL) +); + +COMMENT ON COLUMN analyses.content IS + 'Structured result. natal/synastry: {title, summary, sections: {key: {title, body}}, strengths: [], challenges: [], advice}; summary: {title, summary}'; diff --git a/docker-compose.yml b/docker-compose.yml index 3516ab0..d666c72 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -49,6 +49,10 @@ services: BOOTSTRAP_ADMIN_EMAILS: ${BOOTSTRAP_ADMIN_EMAILS:-} # Empty: the backend's default tiers (see services/backend/README.md). LLM_MODELS: ${LLM_MODELS:-} + # Free short summary of every saved chart (empty: anthropic/claude-sonnet-5.5). + SUMMARY_MODEL: ${SUMMARY_MODEL:-} + # E-mail + password login; off by default (Google, Apple and Facebook only). + PASSWORD_LOGIN: ${PASSWORD_LOGIN:-false} depends_on: postgres: condition: service_healthy diff --git a/services/backend/README.md b/services/backend/README.md index bb6b953..bf60ce7 100644 --- a/services/backend/README.md +++ b/services/backend/README.md @@ -13,20 +13,22 @@ Felhasználók, belépés, mentett születési képletek, szinasztriák és megh | `COOKIE_SECURE` | `true` | csak helyi, sima HTTP-s fejlesztéshez legyen `false` | | `COOKIE_DOMAIN` | – | pl. `.sorsfonalak.hu`, ha a frontend és az API más aldomainen fut | | `SESSION_TTL_DAYS` | `30` | a munkamenet élettartama | +| `PASSWORD_LOGIN` | `false` | e-mail + jelszó regisztráció és belépés; élesben ki van kapcsolva (csak Google, Apple, Facebook), a jelszavas végpontok ilyenkor 403-at adnak | | `GOOGLE_CLIENT_IDS` | – | Google OAuth kliens-azonosító(k); üresen a Google-belépés ki van kapcsolva | | `BOOTSTRAP_ADMIN_EMAILS` | – | ezek a címek regisztrációkor vagy belépéskor admin szerepet kapnak (így lesz meg az első admin) | | `SUPPORTED_LOCALES` | `hu,en` | felület- és elemzésnyelvek; az első az alapértelmezett | | `MONTHLY_FREE_CREDITS` | `10` | havi ingyenes kreditkeret | | `ANALYSIS_COST` | `1` | egy új elemzés ára kreditben azoknál a modelleknél, amelyeknél az `LLM_MODELS` nem ad meg árat | | `LLM_MODELS` | lásd lent | választható modellek `modell[=kredit][@szerep]` alakban, vesszővel elválasztva; az első az alapértelmezett, és ahhoz nem kellhet szerep | -| `ANALYSIS_PROMPT_VERSION` | `v1` | a prompt verziója (az elemzés-gyorsítótár kulcsának része) | +| `SUMMARY_MODEL` | `anthropic/claude-sonnet-5.5` | ez írja minden mentett képlet ingyenes rövid összefoglalóját (kb. 1 cent darabonként) | +| `ANALYSIS_PROMPT_VERSION` | `v2` | a prompt verziója (az elemzés-gyorsítótár kulcsának része) | | `MAX_CHARTS_PER_USER` | `50` | ennyi képletet menthet egy felhasználó | | `BIND_ADDR`, `LOG_FORMAT`, `RUST_LOG` | `0.0.0.0:8081`, `text`, `info` | | ## Belépés és jogosultság - **Munkamenet:** véletlen token, HttpOnly + SameSite=Lax sütiben (`sf_session`). A belépési válasz törzsében is ott van, hogy nem böngészős kliens `Authorization: Bearer ` fejléccel küldhesse vissza. Az adatbázis csak a token SHA-256 hash-ét tárolja, így a munkamenet visszavonható (kijelentkezés, jelszócsere, fióktörlés). -- **E-mail + jelszó:** +- **E-mail + jelszó** (csak `PASSWORD_LOGIN=true` mellett; élesben csak közösségi belépés lesz, hogy ne lehessen tömegesen ingyenes fiókokat nyitni): - a jelszó legalább 10 karakter, Argon2id hash-sel tárolva; - címenként 15 percen belül 10 hibás próbálkozás után átmenetileg tiltás jár; - ismeretlen címnél is ugyanannyi ideig tart a válasz. @@ -44,7 +46,7 @@ Felhasználók, belépés, mentett születési képletek, szinasztriák és megh | Végpont | Guard | Leírás | |---|---|---| -| `GET /v1/config` | – | Google kliens-azonosító, nyelvek, modellek, kreditárak | +| `GET /v1/config` | – | Google kliens-azonosító, `password_login`, nyelvek, modellek, kreditárak | | `POST /v1/auth/register` | – | `{email, password, display_name?, locale?}` → munkamenet; megerősítő e-mailt küld | | `POST /v1/auth/login` | – | `{email, password}` | | `POST /v1/auth/google` | – | `{id_token}`; `created: true`, ha most jött létre a fiók | @@ -58,7 +60,8 @@ Felhasználók, belépés, mentett születési képletek, szinasztriák és megh | `GET /v1/me/export` | user | GDPR: minden adat egy JSON-ban | | `GET /v1/credits` | user | egyenleg és kreditmozgások | | `GET`/`POST /v1/charts` | user | képletek listája; új képlet: `{label, is_primary, birth}`, ahol a `birth` a horoscope-api `/v1/natal` kérésformátuma | -| `GET`/`PATCH`/`DELETE /v1/charts/{id}` | tulajdonos | a születési adat nem módosítható: a javított képlet új képlet | +| `GET`/`PATCH`/`DELETE /v1/charts/{id}` | tulajdonos | a születési adat nem módosítható: a javított képlet új képlet. Ugyanarra a születési adatra a `POST /v1/charts` a meglévő képletet adja vissza (200), nem számol újat | +| `POST /v1/charts/{id}/summary` | tulajdonos | az ingyenes rövid összefoglaló (`kind: summary`, `{title, summary}`); mentéskor magától sorba áll, ez visszaadja, és ha elbukott, újra sorba állítja | | `GET`/`POST /v1/synastries` | user | `{chart1_id, chart2_id}`, mindkét képlet a sajátod | | `GET`/`DELETE /v1/synastries/{id}` | résztvevő | | | `GET`/`POST /v1/invites` | user | „Mennyire illünk össze?” link; alapból a saját (primary) képlettel | diff --git a/services/backend/src/config.rs b/services/backend/src/config.rs index 769e4ea..78c2eab 100644 --- a/services/backend/src/config.rs +++ b/services/backend/src/config.rs @@ -72,6 +72,9 @@ pub struct Config { pub cookie_domain: Option, /// `SESSION_TTL_DAYS` (default 30). pub session_ttl_days: i64, + /// `PASSWORD_LOGIN` (default `false`): e-mail and password registration and + /// login. Off in production, where only Google, Apple and Facebook are offered. + pub password_login: bool, /// `GOOGLE_CLIENT_IDS`: comma-separated OAuth client ids accepted as the /// ID token audience; empty disables Google login. pub google_client_ids: Vec, @@ -89,7 +92,10 @@ pub struct Config { /// Credits default to `ANALYSIS_COST` (default 1). Default: /// [`DEFAULT_LLM_MODELS`]. pub llm_models: Vec, - /// `ANALYSIS_PROMPT_VERSION` (default `v1`); part of the analysis cache key. + /// `SUMMARY_MODEL`: writes the free short summary of every saved chart + /// (default `anthropic/claude-sonnet-5.5`, about 1 US cent each). + pub summary_model: String, + /// `ANALYSIS_PROMPT_VERSION` (default `v2`); part of the analysis cache key. pub prompt_version: String, /// `MAX_CHARTS_PER_USER` (default 50). pub max_charts_per_user: i64, @@ -147,6 +153,7 @@ impl Config { cookie_secure: parsed("COOKIE_SECURE", true)?, cookie_domain: var("COOKIE_DOMAIN"), session_ttl_days: parsed("SESSION_TTL_DAYS", 30)?, + password_login: parsed("PASSWORD_LOGIN", false)?, google_client_ids: list("GOOGLE_CLIENT_IDS"), google_jwks_url: var("GOOGLE_JWKS_URL") .unwrap_or_else(|| "https://www.googleapis.com/oauth2/v3/certs".into()), @@ -154,7 +161,8 @@ impl Config { supported_locales, monthly_free_credits: parsed("MONTHLY_FREE_CREDITS", 10)?, llm_models, - prompt_version: var("ANALYSIS_PROMPT_VERSION").unwrap_or_else(|| "v1".into()), + summary_model: var("SUMMARY_MODEL").unwrap_or_else(|| "anthropic/claude-sonnet-5.5".into()), + prompt_version: var("ANALYSIS_PROMPT_VERSION").unwrap_or_else(|| "v2".into()), max_charts_per_user: parsed("MAX_CHARTS_PER_USER", 50)?, }; if config.session_ttl_days < 1 { @@ -177,6 +185,7 @@ impl Config { cookie_secure: true, cookie_domain: None, session_ttl_days: 30, + password_login: true, google_client_ids: vec!["test-client.apps.googleusercontent.com".into()], google_jwks_url, bootstrap_admin_emails: vec!["admin@example.com".into()], @@ -187,6 +196,7 @@ impl Config { 1, ) .unwrap(), + summary_model: "anthropic/claude-summary".into(), prompt_version: "v1".into(), max_charts_per_user: 50, } diff --git a/services/backend/src/routes/account.rs b/services/backend/src/routes/account.rs index 95cd8c9..0905a10 100644 --- a/services/backend/src/routes/account.rs +++ b/services/backend/src/routes/account.rs @@ -85,6 +85,7 @@ pub async fn change_password( auth: AuthUser, WithRejection(Json(req), _): Body, ) -> ApiResult { + super::auth::password_login_enabled(&state)?; validate_password(&req.new_password)?; let existing: Option<(String,)> = sqlx::query_as("SELECT password_hash FROM auth_identities WHERE user_id = $1 AND provider = 'password'") diff --git a/services/backend/src/routes/analyses.rs b/services/backend/src/routes/analyses.rs index 1bd181f..5673d1b 100644 --- a/services/backend/src/routes/analyses.rs +++ b/services/backend/src/routes/analyses.rs @@ -4,6 +4,9 @@ //! writes the text later. A finished analysis with the same cache key (same //! chart or synastry hash, prompt version, model and language) is copied //! instead, free of charge, so the same chart is never paid for twice. +//! +//! Every saved chart also gets a free short summary (`summary` kind, written +//! by `SUMMARY_MODEL`); the detailed analyses are paid. use axum::Json; use axum::body::Bytes; @@ -17,7 +20,7 @@ use time::OffsetDateTime; use uuid::Uuid; use super::auth::validate_locale; -use super::charts::{find_chart, owned_chart}; +use super::charts::{ChartRow, find_chart, owned_chart}; use super::synastries::{load_synastry, visible_synastry}; use super::{IdPath, St}; use crate::AppState; @@ -104,6 +107,7 @@ fn optional_body(body: &[u8]) -> Result { enum Target { Natal { chart_id: Uuid, hash: String }, + Summary { chart_id: Uuid, hash: String }, Synastry { synastry_id: Uuid, hash: String }, } @@ -127,9 +131,25 @@ async fn request( { return Err(ApiError::Forbidden(format!("the model '{}' needs the '{}' role", chosen.id, role.as_str()))); } - let model = chosen.id.clone(); - let (kind, hash, chart_id, synastry_id) = match &target { + let cost = chosen.credits; + let (status, row) = queue(state, auth.id(), &target, &language, &chosen.id, cost).await?; + Ok((status, Json(row.view()))) +} + +/// Returns the existing analysis with the same cache key for this target, +/// copies a finished one from another chart with the same data, or queues a +/// new one (spending `cost` credits). 200, 201 and 202 respectively. +async fn queue( + state: &AppState, + user: Uuid, + target: &Target, + language: &str, + model: &str, + cost: i32, +) -> Result<(StatusCode, AnalysisRow), ApiError> { + let (kind, hash, chart_id, synastry_id) = match target { Target::Natal { chart_id, hash } => ("natal", hash, Some(*chart_id), None), + Target::Summary { chart_id, hash } => ("summary", hash, Some(*chart_id), None), Target::Synastry { synastry_id, hash } => ("synastry", hash, None, Some(*synastry_id)), }; let prompt_version = &state.config.prompt_version; @@ -147,7 +167,7 @@ async fn request( .fetch_optional(&state.db) .await?; if let Some(row) = existing { - return Ok((StatusCode::OK, Json(row.view()))); + return Ok((StatusCode::OK, row)); } let insert = format!( @@ -170,9 +190,9 @@ async fn request( .bind(kind) .bind(chart_id) .bind(synastry_id) - .bind(auth.id()) - .bind(&language) - .bind(&model) + .bind(user) + .bind(language) + .bind(model) .bind(prompt_version) .bind(&cache_key) .bind("done") @@ -183,20 +203,19 @@ async fn request( .bind(OffsetDateTime::now_utc()) .fetch_one(&state.db) .await?; - return Ok((StatusCode::CREATED, Json(row.view()))); + return Ok((StatusCode::CREATED, row)); } // New analysis: spend credits and queue it for the worker. - let cost = chosen.credits; let mut tx = state.db.begin().await?; let row: AnalysisRow = sqlx::query_as(&insert) .bind(id) .bind(kind) .bind(chart_id) .bind(synastry_id) - .bind(auth.id()) - .bind(&language) - .bind(&model) + .bind(user) + .bind(language) + .bind(model) .bind(prompt_version) .bind(&cache_key) .bind("pending") @@ -207,9 +226,28 @@ async fn request( .bind(None::) .fetch_one(&mut *tx) .await?; - credits::spend(&mut tx, auth.id(), cost, state.config.monthly_free_credits, "analysis", Some(id)).await?; + if cost > 0 { + credits::spend(&mut tx, user, cost, state.config.monthly_free_credits, "analysis", Some(id)).await?; + } tx.commit().await?; - Ok((StatusCode::ACCEPTED, Json(row.view()))) + Ok((StatusCode::ACCEPTED, row)) +} + +/// The free short summary of a chart (in the owner's language): queued if +/// it does not exist yet or the last attempt failed. +pub async fn ensure_summary(state: &AppState, owner: &AuthUser, chart: &ChartRow) -> Result { + let target = Target::Summary { chart_id: chart.id, hash: chart.chart_hash.clone() }; + let model = state.config.summary_model.clone(); + Ok(queue(state, owner.id(), &target, &owner.user.locale, &model, 0).await?.1) +} + +pub async fn summary_for_chart( + State(state): St, + auth: AuthUser, + WithRejection(Path(id), _): IdPath, +) -> ApiResult> { + let chart = owned_chart(&state.db, id, auth.id()).await?; + Ok(Json(ensure_summary(&state, &auth, &chart).await?.view())) } async fn list_where(db: &PgPool, column: &str, id: Uuid) -> Result, ApiError> { diff --git a/services/backend/src/routes/auth.rs b/services/backend/src/routes/auth.rs index 60f1fea..d5e2225 100644 --- a/services/backend/src/routes/auth.rs +++ b/services/backend/src/routes/auth.rs @@ -158,12 +158,22 @@ pub struct RegisterRequest { locale: Option, } +/// Password endpoints answer 403 while `PASSWORD_LOGIN` is off. +pub fn password_login_enabled(state: &crate::AppState) -> Result<(), ApiError> { + if state.config.password_login { + Ok(()) + } else { + Err(ApiError::Forbidden("e-mail and password login is disabled; use Google, Apple or Facebook".into())) + } +} + pub async fn register( State(state): St, headers: HeaderMap, jar: CookieJar, WithRejection(Json(req), _): Body, ) -> ApiResult { + password_login_enabled(&state)?; let email = normalize_email(&req.email)?; validate_password(&req.password)?; let locale = validate_locale(&state, req.locale.as_deref())?; @@ -213,6 +223,7 @@ pub async fn login( jar: CookieJar, WithRejection(Json(req), _): Body, ) -> ApiResult { + password_login_enabled(&state)?; let invalid = || ApiError::InvalidCredentials("wrong e-mail address or password".into()); let email = normalize_email(&req.email).map_err(|_| invalid())?; state.login_limiter.check(&email)?; @@ -394,6 +405,7 @@ pub async fn request_password_reset( State(state): St, WithRejection(Json(req), _): Body, ) -> ApiResult { + password_login_enabled(&state)?; let Ok(email) = normalize_email(&req.email) else { return Ok(StatusCode::ACCEPTED) }; let mut tx = state.db.begin().await?; let user: Option = sqlx::query_as(&format!("SELECT {USER_COLUMNS} FROM users WHERE email = $1")) @@ -422,6 +434,7 @@ pub async fn confirm_password_reset( State(state): St, WithRejection(Json(req), _): Body, ) -> ApiResult { + password_login_enabled(&state)?; validate_password(&req.password)?; let hash = hash_password(req.password).await?; let mut tx = state.db.begin().await?; diff --git a/services/backend/src/routes/charts.rs b/services/backend/src/routes/charts.rs index 135154b..86a496c 100644 --- a/services/backend/src/routes/charts.rs +++ b/services/backend/src/routes/charts.rs @@ -112,6 +112,14 @@ pub async fn calculate(state: &AppState, birth: Value) -> Result<(Value, Value, Ok((birth, result, hash)) } +/// Queues the free short summary; a failure here does not fail the save +/// (the chart page asks for the summary again). +async fn queue_summary(state: &AppState, auth: &AuthUser, chart: &ChartRow) { + if let Err(e) = super::analyses::ensure_summary(state, auth, chart).await { + tracing::warn!(chart = %chart.id, error = %e, "queueing the chart summary failed"); + } +} + fn clean_birth(birth: Value) -> Result { let Value::Object(mut birth) = birth else { return Err(ApiError::BadRequest("birth must be an object".into())); @@ -150,8 +158,10 @@ pub async fn create( .fetch_one(&mut *tx) .await?; tx.commit().await?; + queue_summary(&state, &auth, &row).await; return Ok((StatusCode::OK, Json(row.owner_view()))); } + queue_summary(&state, &auth, &chart).await; return Ok((StatusCode::OK, Json(chart.owner_view()))); } let (count,): (i64,) = @@ -185,6 +195,7 @@ pub async fn create( .fetch_one(&mut *tx) .await?; tx.commit().await?; + queue_summary(&state, &auth, &row).await; Ok((StatusCode::CREATED, Json(row.owner_view()))) } diff --git a/services/backend/src/routes/mod.rs b/services/backend/src/routes/mod.rs index 85ad279..5266501 100644 --- a/services/backend/src/routes/mod.rs +++ b/services/backend/src/routes/mod.rs @@ -67,6 +67,7 @@ pub fn router(state: Arc) -> Router { .route("/v1/charts", get(charts::list).post(charts::create)) .route("/v1/charts/{id}", get(charts::get_one).patch(charts::update).delete(charts::remove)) .route("/v1/charts/{id}/analyses", get(analyses::list_for_chart).post(analyses::request_for_chart)) + .route("/v1/charts/{id}/summary", post(analyses::summary_for_chart)) // synastries and invitations .route("/v1/synastries", get(synastries::list).post(synastries::create)) .route("/v1/synastries/{id}", get(synastries::get_one).delete(synastries::remove)) @@ -118,6 +119,7 @@ async fn public_config(State(state): St) -> Json { "llm_models": c.llm_models, "default_model": c.llm_models[0].id, "monthly_free_credits": c.monthly_free_credits, + "password_login": c.password_login, "password_min_length": crate::auth::MIN_PASSWORD_LEN, })) } diff --git a/services/backend/src/tests.rs b/services/backend/src/tests.rs index 94612d6..b3ee8bf 100644 --- a/services/backend/src/tests.rs +++ b/services/backend/src/tests.rs @@ -115,8 +115,13 @@ struct Response { impl TestApp { async fn new(pool: PgPool) -> Self { + Self::with_config(pool, |_| {}).await + } + + async fn with_config(pool: PgPool, change: impl FnOnce(&mut Config)) -> Self { let fake = fake_services().await; - let config = Config::for_tests(String::new(), fake.clone(), format!("{fake}/jwks")); + let mut config = Config::for_tests(String::new(), fake.clone(), format!("{fake}/jwks")); + change(&mut config); Self { router: routes::router(Arc::new(AppState::new(pool.clone(), config))), pool } } @@ -458,6 +463,17 @@ async fn analyses_spend_credits_and_reuse_results(pool: PgPool) { let chart = app.chart(&anna, "Saját", true, "1990-03-15").await; let uri = format!("/v1/charts/{}/analyses", chart["id"].as_str().unwrap()); + // saving the chart queued the free short summary + let list = app.get(&uri, Some(&anna)).await.body; + let summary = &list["analyses"][0]; + assert_eq!( + (summary["kind"].as_str(), summary["status"].as_str(), summary["model"].as_str(), &summary["credits_charged"]), + (Some("summary"), Some("pending"), Some("anthropic/claude-summary"), &json!(0)) + ); + let r = app.call("POST", &format!("/v1/charts/{}/summary", chart["id"].as_str().unwrap()), Some(&anna), None).await; + assert_eq!((r.status, &r.body["id"]), (StatusCode::OK, &summary["id"])); + assert_eq!(app.get("/v1/credits", Some(&anna)).await.body["balance"], 2); + let r = app.call("POST", &uri, Some(&anna), None).await; assert_eq!(r.status, StatusCode::ACCEPTED, "{}", r.body); assert_eq!((r.body["status"].as_str(), r.body["language"].as_str()), (Some("pending"), Some("hu"))); @@ -493,7 +509,22 @@ async fn analyses_spend_credits_and_reuse_results(pool: PgPool) { assert_eq!(app.get("/v1/credits", Some(&bela)).await.body["balance"], 2); assert_eq!(app.get(&format!("/v1/analyses/{first}"), Some(&bela)).await.status, StatusCode::NOT_FOUND); - assert_eq!(app.get(&uri, Some(&anna)).await.body["analyses"].as_array().unwrap().len(), 2); + assert_eq!(app.get(&uri, Some(&anna)).await.body["analyses"].as_array().unwrap().len(), 3); // 2 + summary +} + +#[sqlx::test(migrator = "db::MIGRATOR")] +async fn password_login_can_be_disabled(pool: PgPool) { + let app = TestApp::with_config(pool, |c| c.password_login = false).await; + assert_eq!(app.get("/v1/config", None).await.body["password_login"], false); + let r = app + .post("/v1/auth/register", None, json!({"email": "anna@example.com", "password": "titkos-jelszo-123"})) + .await; + assert_eq!(r.status, StatusCode::FORBIDDEN); + let r = + app.post("/v1/auth/login", None, json!({"email": "anna@example.com", "password": "titkos-jelszo-123"})).await; + assert_eq!(r.status, StatusCode::FORBIDDEN); + let r = app.post("/v1/auth/password-reset", None, json!({"email": "anna@example.com"})).await; + assert_eq!(r.status, StatusCode::FORBIDDEN); } #[sqlx::test(migrator = "db::MIGRATOR")] diff --git a/services/frontend/src/app/globals.css b/services/frontend/src/app/globals.css index 48bb79b..9c03192 100644 --- a/services/frontend/src/app/globals.css +++ b/services/frontend/src/app/globals.css @@ -148,6 +148,16 @@ td.num { font-variant-numeric: tabular-nums; white-space: nowrap; } .gsi-slot { min-height: 44px; display: flex; justify-content: center; } /* Chart page */ +.summary-card { gap: 10px; border-color: rgba(217, 180, 106, 0.35); } +.eyebrow { font-size: 12px; font-weight: 600; letter-spacing: 1.2px; text-transform: uppercase; color: var(--gold); } +.summary-title { font-size: 26px; } +.summary-text { font-size: 16px; line-height: 1.65; color: var(--ink-2); } +.summary-text strong { color: var(--ink); font-weight: 600; } +.skeleton { display: flex; flex-direction: column; gap: 8px; } +.skeleton span { height: 12px; border-radius: 6px; background: var(--line); animation: pulse 1.4s ease-in-out infinite; } +.skeleton span:last-child { width: 60%; } +@keyframes pulse { 50% { opacity: 0.45; } } +@media (prefers-reduced-motion: reduce) { .skeleton span { animation: none; } } .chart-layout { display: grid; grid-template-columns: minmax(0, 1.35fr) minmax(280px, 1fr); gap: 24px; align-items: start; } .chart-wheel-card { padding: 16px; gap: 10px; } .chart-wheel { width: 100%; height: auto; display: block; max-width: 680px; margin: 0 auto; } diff --git a/services/frontend/src/app/kepletek/[id]/page.tsx b/services/frontend/src/app/kepletek/[id]/page.tsx index 3033bd0..b12f6ce 100644 --- a/services/frontend/src/app/kepletek/[id]/page.tsx +++ b/services/frontend/src/app/kepletek/[id]/page.tsx @@ -3,10 +3,11 @@ import Link from "next/link"; import { notFound } from "next/navigation"; import { BigThree, ChartTables } from "@/components/ChartTables"; +import { ChartSummary } from "@/components/ChartSummary"; import { ChartWheel } from "@/components/ChartWheel"; import { ELEMENTS, MODALITIES, MOON_PHASES, countryName, formatBirthDate, pointName } from "@/lib/astro"; import { backendGet, requireMe } from "@/lib/server"; -import type { Chart } from "@/lib/types"; +import type { Analysis, Chart } from "@/lib/types"; export const metadata: Metadata = { title: "Képlet" }; @@ -17,8 +18,12 @@ export default async function ChartPage({ params }: { params: Promise<{ id: stri const { id } = await params; await requireMe(`/kepletek/${id}`); if (!UUID.test(id)) notFound(); - const chart = await backendGet(`/v1/charts/${id}`); + const [chart, analyses] = await Promise.all([ + backendGet(`/v1/charts/${id}`), + backendGet<{ analyses: Analysis[] }>(`/v1/charts/${id}/analyses`), + ]); if (!chart) notFound(); + const summary = analyses?.analyses.find((a) => a.kind === "summary" && a.status !== "failed") ?? null; const result = chart.chart; const timeKnown = chart.highlights.time_known; @@ -56,6 +61,7 @@ export default async function ChartPage({ params }: { params: Promise<{ id: stri

+ {(elements || modalities || phase) && (
diff --git a/services/frontend/src/components/ChartSummary.tsx b/services/frontend/src/components/ChartSummary.tsx new file mode 100644 index 0000000..3ebdc0a --- /dev/null +++ b/services/frontend/src/components/ChartSummary.tsx @@ -0,0 +1,90 @@ +"use client"; + +import { useEffect, useState } from "react"; + +import { api } from "@/lib/api"; +import type { Analysis } from "@/lib/types"; + +const POLL_MS = 3000; +const MAX_POLLS = 60; + +/** `**bold**` → ; the rest is plain text. */ +function Rich({ text }: { text: string }) { + return ( + <> + {text.split(/(\*\*[^*]+\*\*)/g).map((part, i) => + part.startsWith("**") && part.endsWith("**") ? {part.slice(2, -2)} : part, + )} + + ); +} + +/** + * The free short summary of a chart. The backend queues it when the chart is + * saved; this asks for it (queueing it again if it failed) and polls until the + * worker has written it. + */ +export function ChartSummary({ chartId, initial }: { chartId: string; initial: Analysis | null }) { + const [summary, setSummary] = useState(initial); + const [gaveUp, setGaveUp] = useState(false); + const done = summary?.status === "done"; + + useEffect(() => { + if (done) return; + let polls = 0; + let stopped = false; + let timer: ReturnType | undefined; + const tick = async () => { + try { + const next = await api(`/charts/${chartId}/summary`, { method: "POST" }); + if (stopped) return; + setSummary(next); + if (next.status === "done") return; + } catch { + // try again on the next tick + } + if (++polls >= MAX_POLLS) return setGaveUp(true); + timer = setTimeout(tick, POLL_MS); + }; + tick(); + return () => { + stopped = true; + clearTimeout(timer); + }; + }, [chartId, done]); + + const content = done ? summary?.content : null; + return ( +
+ Röviden + {content ? ( + <> +

+ {content.title} +

+

+ +

+ + ) : ( + <> +

+ Rövid összefoglaló +

+

+ {gaveUp || summary?.status === "failed" + ? "Az összefoglaló most nem készült el. Töltsd újra az oldalt egy kicsit később." + : "Az összefoglalód készül, ez néhány másodperc…"} +

+ {!gaveUp && summary?.status !== "failed" && ( + + )} + + )} +
+ ); +} diff --git a/services/frontend/src/lib/types.ts b/services/frontend/src/lib/types.ts index 1924a09..83392ca 100644 --- a/services/frontend/src/lib/types.ts +++ b/services/frontend/src/lib/types.ts @@ -82,6 +82,18 @@ export interface Chart { created_at: string; } +export interface Analysis { + id: string; + kind: "natal" | "synastry" | "summary"; + status: "pending" | "running" | "done" | "failed"; + model: string; + language: string; + content: { title?: string; summary?: string } & Record | null; + credits_charged: number; + created_at: string; + completed_at: string | null; +} + export interface AdminUser { id: string; email: string; diff --git a/services/worker/README.md b/services/worker/README.md index 9e524be..db5dd8c 100644 --- a/services/worker/README.md +++ b/services/worker/README.md @@ -20,10 +20,11 @@ Háttérmunkák a közös PostgreSQL-adatbázis fölött: e-mail-küldés, szöv **Szöveges elemzések** (`analyses`, `pending` → `running` → `done`/`failed`) - A backend létrehozza a `pending` sort, és levonja a kreditet. Egy trigger (`NOTIFY analyses`) felébreszti a workert; egyszerre `ANALYSIS_CONCURRENCY` elemzés készül. - A prompt a tárolt képletből készül (`src/analysis/compact.rs`). Ez egy tömör szöveg, amely csak a pozíciókat tartalmazza: jegyek, fokok, házak, fényszögek, elemek. **Név, születési dátum, idő, hely és koordináta nem megy ki.** Ismeretlen születési időnél nincsenek házak, Aszcendens és MC. -- A modell OpenRouteren keresztül válaszol, azzal a modellel, amely a sor `model` mezőjében áll. A válasznak kötött JSON-sémát kell követnie (`src/analysis/prompt.rs`, `PROMPT_VERSION = v1`): +- A modell OpenRouteren keresztül válaszol, azzal a modellel, amely a sor `model` mezőjében áll. A válasznak kötött JSON-sémát kell követnie (`src/analysis/prompt.rs`, `PROMPT_VERSION = v2`): - `title`, `summary`; - `sections`, radixnál: `personality`, `emotions`, `mind`, `love`, `work`, `growth`; szinasztriánál: `attraction`, `communication`, `emotional_bond`, `friction`, `long_term`; - - `strengths`, `challenges`, `advice`. + - `strengths`, `challenges`, `advice`; + - a rövid összefoglalónál (`summary`) csak `title` és egy 3–4 mondatos `summary`. A worker a választ maga is ellenőrzi a sémán. Magyar szövegben az egyenes idézőjelpárokat („…”) alakra cseréli. - Eltárolja a ténylegesen válaszoló modellt (`model_used`; az `openrouter/auto` mögött ez más lehet), a tokenszámot és a költséget (`cost_usd`). @@ -43,6 +44,8 @@ A 2026-11-15-i összevetésen két képletet hét modell írt meg; az egyiket a A MiniMax M3 olcsó, de az asztrológus szerint többször felcserélt dolgokat. +Az ingyenes rövid összefoglalót (2026-11-16) a Haiku és a Sonnet négy képleten írta meg. Mindkettő tényszerűen helyes volt, de a Sonnet jobban válogat és fogalmaz, ezért ez az alapértelmezett (`SUMMARY_MODEL`, kb. 0,009 dollár, a Haiku kb. 0,001). A fizetős részletes elemzés az Opus 5.5-tel készül. + ```bash OPENROUTER_API_KEY=... worker compare-models --chart natal.json \ --models minimax/minimax-m3,anthropic/claude-sonnet-5.5 --language hu --out exports/model-compare @@ -51,7 +54,8 @@ OPENROUTER_API_KEY=... worker compare-models --chart natal.json \ Ugyanazt a radix-elemzést több modellel is megírja, véletlenszerű betűkkel (`A.md`, `B.md`, …). - A `key.json` mondja meg, melyik betű melyik modell, a tokenszámmal, a költséggel és az idővel együtt. - A `prompt.md` a teljes promptot tartalmazza. -- A `--chart` a horoscope-api `/v1/natal` válasza. +- A `--chart` a horoscope-api `/v1/natal` válasza; `--summary` mellett a rövid összefoglalót írja meg. +- A `--synastry FILE` (a `--chart` helyett) a horoscope-api `/v1/synastry` válasza, és szinasztria-elemzést ír. ## Konfiguráció diff --git a/services/worker/src/analysis/mod.rs b/services/worker/src/analysis/mod.rs index 58d8780..1c60de1 100644 --- a/services/worker/src/analysis/mod.rs +++ b/services/worker/src/analysis/mod.rs @@ -79,7 +79,7 @@ impl Analyzer { let db_err = |e: sqlx::Error| LlmError::Transient(format!("database: {e}")); let gone = || LlmError::Permanent("the chart was deleted".into()); let text = match kind { - Kind::Natal => { + Kind::Natal | Kind::Summary => { let (chart,): (Value,) = sqlx::query_as("SELECT result FROM charts WHERE id = $1") .bind(job.chart_id) .fetch_optional(&self.db) diff --git a/services/worker/src/analysis/prompt.rs b/services/worker/src/analysis/prompt.rs index 55bd88d..238d4fc 100644 --- a/services/worker/src/analysis/prompt.rs +++ b/services/worker/src/analysis/prompt.rs @@ -6,12 +6,14 @@ use serde_json::{Value, json}; /// Matches the backend's `ANALYSIS_PROMPT_VERSION` (part of the cache key). -pub const PROMPT_VERSION: &str = "v1"; +pub const PROMPT_VERSION: &str = "v2"; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Kind { Natal, Synastry, + /// A free teaser of a natal chart: a title and a few sentences. + Summary, } impl Kind { @@ -19,6 +21,7 @@ impl Kind { match s { "natal" => Some(Kind::Natal), "synastry" => Some(Kind::Synastry), + "summary" => Some(Kind::Summary), _ => None, } } @@ -56,11 +59,23 @@ fn sections(kind: Kind) -> &'static [(&'static str, &'static str)] { match kind { Kind::Natal => &NATAL_SECTIONS, Kind::Synastry => &SYNASTRY_SECTIONS, + Kind::Summary => &[], } } /// The JSON schema of the answer (strict mode: every property required). pub fn schema(kind: Kind) -> Value { + if kind == Kind::Summary { + return json!({ + "type": "object", + "additionalProperties": false, + "required": ["title", "summary"], + "properties": { + "title": {"type": "string", "description": "Short, evocative title for this chart (at most 6 words)"}, + "summary": {"type": "string", "description": "3-4 sentences, 60-100 words, one paragraph"} + } + }); + } let mut props = serde_json::Map::new(); for (key, about) in sections(kind) { props.insert( @@ -101,6 +116,8 @@ Use the usual Hungarian astrological terms: - planets and points: Nap, Hold, Merkúr, Vénusz, Mars, Jupiter, Szaturnusz, Uránusz, Neptunusz, Plútó, Chiron (Kiron), \ Észak-Holdcsomópont, Dél-Holdcsomópont, Lilith (Fekete Hold), Aszcendens, Descendens, Medium Coeli (MC), Imum Coeli (IC), Szerencsepont; - aspects: együttállás (konjunkció), szextil, kvadrát (négyzet), trigon, szembenállás (oppozíció); +- elements and modalities: tűz, föld, levegő, víz (\"tűz elem\", \"a föld hiánya\"); kardinális, fix, változó; +Never leave English words (e.g. fire, earth, air, water) in the Hungarian text. - other: \"a 3. házban\", \"a horoszkóp uralkodója\", retrográd, uralom (domicilium), száműzetés, exaltáció, esés, nappali/éjszakai horoszkóp."; fn language_name(language: &str) -> &'static str { @@ -116,6 +133,10 @@ fn rules(kind: Kind, language: &str) -> String { "a personal natal chart interpretation", "Speak to the owner of the chart directly, in the informal second person singular (in Hungarian: tegező forma, \"te\").", ), + Kind::Summary => ( + "a short free summary of a natal chart (a teaser shown before the detailed, paid analysis)", + "Speak to the owner of the chart directly, in the informal second person singular (in Hungarian: tegező forma, \"te\").", + ), Kind::Synastry => ( "a relationship (synastry) interpretation for two people", "Write for both people at once, in the informal second person plural (in Hungarian: \"ti\", \"kettőtök\"). \ @@ -139,9 +160,16 @@ Give the most weight to the Sun, Moon, Ascendant, chart ruler, tight aspects (or and no medical, legal or financial advice. - Avoid generic horoscope clichés and filler: every paragraph must say something specific to this chart. - Texts are plain paragraphs separated by a blank line, without headings or lists inside; **bold** may be used sparingly. -- Length: each section 2-4 paragraphs (about 150-250 words); the whole analysis about 1300-1800 words. +- {length} - Answer with a single JSON object that matches the given schema, and nothing else.", lang = language_name(language), + length = match kind { + Kind::Summary => "Length: one paragraph of 3-4 sentences (60-100 words). Pick the Sun, Moon and Ascendant \ + (if the birth time is known) and the single most striking feature of the chart (a very tight aspect, \ + a stellium, a strong element emphasis or gap). It must be complete in itself and specific to this chart: \ + no sales talk, and do not mention a longer analysis.", + _ => "Length: each section 2-4 paragraphs (about 150-250 words); the whole analysis about 1300-1800 words.", + }, ); if language == "hu" { text.push_str("\n\n"); @@ -153,17 +181,22 @@ and no medical, legal or financial advice. pub fn build(kind: Kind, language: &str, chart_text: &str) -> Prompt { let mut user = String::from("Chart data:\n\n"); user.push_str(chart_text); - user.push_str("\nSections to write, in this order:\n"); - for (key, about) in sections(kind) { - user.push_str(&format!("- {key}: {about}\n")); + if kind == Kind::Summary { + user.push_str("\nWrite the short summary now."); + } else { + user.push_str("\nSections to write, in this order:\n"); + for (key, about) in sections(kind) { + user.push_str(&format!("- {key}: {about}\n")); + } + user.push_str("\nWrite the analysis now."); } - user.push_str("\nWrite the analysis now."); Prompt { system: rules(kind, language), user, schema_name: match kind { Kind::Natal => "natal_analysis", Kind::Synastry => "synastry_analysis", + Kind::Summary => "chart_summary", }, schema: schema(kind), } @@ -242,6 +275,9 @@ pub fn to_markdown(kind: Kind, language: &str, content: &Value) -> String { }; let mut md = format!("# {}\n\n_{}_\n\n", content["title"].as_str().unwrap_or(""), content["summary"].as_str().unwrap_or("")); + if kind == Kind::Summary { + return md; + } for (key, _) in sections(kind) { let s = &content["sections"][*key]; md.push_str(&format!("## {}\n\n{}\n\n", s["title"].as_str().unwrap_or(key), s["body"].as_str().unwrap_or(""))); @@ -261,6 +297,18 @@ pub fn to_markdown(kind: Kind, language: &str, content: &Value) -> String { mod tests { use super::*; + #[test] + fn summary_prompt_is_short() { + let p = build(Kind::Summary, "hu", "SUN: Cancer"); + assert_eq!(p.schema_name, "chart_summary"); + assert!(p.system.contains("3-4 sentences") && p.system.contains("tegező")); + assert!(!p.user.contains("Sections to write")); + assert_eq!(validate(&p.schema, &json!({"title": "Érzékeny mag", "summary": "Rövid szöveg."})), Ok(())); + assert!(validate(&p.schema, &json!({"title": "Érzékeny mag"})).is_err()); + let md = to_markdown(Kind::Summary, "hu", &json!({"title": "Cím", "summary": "Szöveg."})); + assert_eq!(md, "# Cím\n\n_Szöveg._\n\n"); + } + #[test] fn validate_rejects_placeholder_titles() { let schema = schema(Kind::Synastry); diff --git a/services/worker/src/compare.rs b/services/worker/src/compare.rs index eaeb2bf..93c5b27 100644 --- a/services/worker/src/compare.rs +++ b/services/worker/src/compare.rs @@ -7,7 +7,8 @@ //! ``` //! //! `--chart` is a horoscope-api `/v1/natal` response; `--synastry FILE` (instead -//! of `--chart`) takes a `/v1/synastry` response for a relationship analysis. The models get shuffled +//! of `--chart`) takes a `/v1/synastry` response for a relationship analysis; +//! `--summary` with `--chart` writes the short free summary instead. The models get shuffled //! letters: `A.md`, `B.md`, ... hold the analyses, `key.json` tells which //! letter is which model (with tokens, cost and time). The output on the //! console does not reveal the mapping. @@ -31,14 +32,15 @@ struct Args { } fn parse(args: Vec) -> anyhow::Result { - let (mut chart, mut synastry, mut models, mut language, mut out) = - (None, None, Vec::new(), "hu".to_owned(), None); + let (mut chart, mut synastry, mut models, mut language, mut out) = (None, None, Vec::new(), "hu".to_owned(), None); + let mut summary = false; let mut it = args.into_iter(); while let Some(flag) = it.next() { let mut value = || it.next().with_context(|| format!("{flag} needs a value")); match flag.as_str() { "--chart" => chart = Some(PathBuf::from(value()?)), "--synastry" => synastry = Some(PathBuf::from(value()?)), + "--summary" => summary = true, "--models" => models = value()?.split(',').map(|m| m.trim().to_owned()).filter(|m| !m.is_empty()).collect(), "--language" => language = value()?, "--out" => out = Some(PathBuf::from(value()?)), @@ -46,6 +48,7 @@ fn parse(args: Vec) -> anyhow::Result { } } let (input, kind) = match (chart, synastry) { + (Some(c), None) if summary => (c, prompt::Kind::Summary), (Some(c), None) => (c, prompt::Kind::Natal), (None, Some(s)) => (s, prompt::Kind::Synastry), _ => bail!("give either --chart or --synastry"), diff --git a/services/worker/src/config.rs b/services/worker/src/config.rs index fd69cf9..a0918aa 100644 --- a/services/worker/src/config.rs +++ b/services/worker/src/config.rs @@ -50,7 +50,8 @@ impl Config { mail_from: mail_from.parse().with_context(|| format!("invalid MAIL_FROM '{mail_from}'"))?, poll_interval: Duration::from_secs(parsed("POLL_INTERVAL_SECS", 30)?), max_email_attempts: parsed("MAX_EMAIL_ATTEMPTS", 8)?, - openrouter_api_key: var("OPENROUTER_API_KEY"), + // The lower-case name is accepted too (as written in some secrets files). + openrouter_api_key: var("OPENROUTER_API_KEY").or_else(|| var("openrouter_api_key")), openrouter_base_url: var("OPENROUTER_BASE_URL") .unwrap_or_else(|| crate::analysis::openrouter::DEFAULT_BASE_URL.into()), public_base_url: var("PUBLIC_BASE_URL"),