Compare commits

...
Author SHA1 Message Date
sagifer f037522052 Merge pull request 'Sharing a chart with its short summary, with link previews' (#18) from main into prod
CI / test (push) Successful in 1m9s
CI / build (push) Successful in 21s
CI / deploy (push) Successful in 41s
Reviewed-on: #18
2026-11-19 09:11:59 +01:00
fecoandClaude Opus 5.5 c7600608d3 Sharing a chart with its short summary, with link previews
CI / test (push) Successful in 1m10s
CI / build (push) Successful in 4m33s
CI / deploy (push) Skipped
The summary card gets a share button: a public link (/s/<slug>) with the
wheel and the newest short summary, no name or birth data. The page carries
og:/twitter: tags, and /s/<slug>/kep/<version>.png renders a 1200x630 preview
(wheel, title, text, big three) with next/og and bundled fonts. The version
changes with the summary, so Facebook fetches a rewritten one again.

Backend: a shared chart comes with its newest finished summary, and sharing
the same thing again returns the open link.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-19 07:37:06 +00:00
sagifer e476117c77 Merge pull request 'Main' (#17) from main into prod
CI / test (push) Successful in 1m9s
CI / build (push) Successful in 56s
CI / deploy (push) Successful in 34s
Reviewed-on: #17
2026-11-19 08:13:18 +01:00
fecoandClaude Opus 5.5 da533e8fa9 Worker: separate containers for e-mail and AI generation
CI / test (push) Successful in 1m9s
CI / build (push) Successful in 4m9s
CI / deploy (push) Skipped
WORKER_TASKS (email, cleanup, analyses; all by default) picks the jobs of a
worker process. In production the worker sends e-mails and cleans up (and
will take the other background jobs), worker-ai writes the analyses and
answers with its quick and slow lanes, sized from the server's .env.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-19 06:51:45 +00:00
fecoandClaude Opus 5.5 bc0227042b Worker: separate quick lane for summaries and answers
CI / test (push) Successful in 1m8s
CI / build (push) Successful in 4m9s
CI / deploy (push) Skipped
Summaries and questions get their own slots (QUICK_CONCURRENCY, default 2),
so they never wait behind detailed analyses (ANALYSIS_CONCURRENCY, default
4). A free slow slot also takes quick work; a lane of size 0 is off, so the
lanes can run as separate deployments. Documented that several workers can
share the queue.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-19 06:40:09 +00:00
sagifer d758f5bf12 Merge pull request 'Frontend: justified generated text, mobile layout without sideways scrolling' (#16) from main into prod
CI / test (push) Successful in 1m7s
CI / build (push) Successful in 21s
CI / deploy (push) Successful in 51s
Reviewed-on: #16
2026-11-19 07:15:09 +01:00
fecoandClaude Opus 5.5 d46cd7a445 Frontend: justified generated text, mobile layout without sideways scrolling
CI / test (push) Successful in 1m12s
CI / build (push) Successful in 5m12s
CI / deploy (push) Skipped
Summaries, analyses and answers are justified with hyphenation in the
text's own language. Grid tracks can no longer grow past the screen
(minmax(0, 1fr), min(…, 100%)), form fields may shrink, the privacy table
scrolls on its own, and the body clips horizontal overflow as a safety net.
Phones get tighter spacing and smaller headings; the facts lists stack.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-19 06:10:38 +00:00
fecoandClaude Opus 5.5 8b2c4310ba Merge main into prod: restart running generations, error log, retry notice, questions on relationship analyses
CI / test (push) Successful in 1m7s
CI / build (push) Successful in 19s
CI / deploy (push) Successful in 52s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-18 21:51:39 +00:00
fecoandClaude Opus 5.5 029a001ca6 Questions about relationship analyses too
CI / test (push) Successful in 1m6s
CI / build (push) Successful in 5m1s
CI / deploy (push) Skipped
- The answer sees both charts and the comparison; both people see the questions
- Heading, hint and example question per analysis kind

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-18 21:51:38 +00:00
fecoandClaude Opus 5.5 02e4e225f0 Error log, retry notice, a waiting counter that keeps counting
CI / test (push) Successful in 1m8s
CI / build (push) Successful in 5m13s
CI / deploy (push) Skipped
- generation_errors: every failed attempt (model, attempt, outcome, duration); admin
  Hibanapló page and GET /v1/admin/errors; kept 90 days
- The waiting page counts from when the text was asked for (requested_at), not from
  the page load, so a reload no longer restarts it
- It says when an attempt failed and is retried, and when a failed text's unit was
  given back; admins see the error

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-18 21:47:37 +00:00
fecoandClaude Opus 5.5 cf2fb9d454 jobs: plain query string
CI / test (push) Successful in 1m2s
CI / build (push) Successful in 7m53s
CI / deploy (push) Skipped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-18 21:32:02 +00:00
fecoandClaude Opus 5.5 b5743ec7d1 Admin: list and restart running generations with the models set now
CI / test (push) Successful in 1m17s
CI / build (push) Successful in 5m43s
CI / deploy (push) Skipped
- Modellek page: analyses and answers being written or waiting, with their model
  and the one a restart would use; restart one or all
- Each attempt's started_at is its token: a restarted attempt still running in the
  worker cannot write its result and is dropped within 10 seconds

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-18 21:31:09 +00:00
fecoandClaude Opus 5.5 1c24b9a23f Merge main into prod: model functions (analyses, answers, summary), Opus 5.5 default and fallback
CI / test (push) Successful in 1m0s
CI / build (push) Successful in 19s
CI / deploy (push) Successful in 53s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-18 21:14:13 +00:00
fecoandClaude Opus 5.5 769b4791ae Models: one for analyses and forecasts, one for answers; Opus 5.5 default and fallback
CI / test (push) Successful in 1m1s
CI / build (push) Successful in 4m56s
CI / deploy (push) Skipped
- Admin Modellek: summary, analyses + forecast (shared), question-answer (own model)
- Every default is Opus 5.5; when the chosen model fails twice (permanent: once),
  the default model takes over with fresh attempts before the unit is refunded
- The page shows how often the fallback was needed in the last 30 days

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-18 21:11:08 +00:00
fecoandClaude Opus 5.5 86758cf848 Merge main into prod: worker room and time for reasoning models
CI / test (push) Successful in 1m0s
CI / build (push) Successful in 20s
CI / deploy (push) Successful in 35s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-18 19:52:02 +00:00
fecoandClaude Opus 5.5 5af08ab689 Worker: room and time for reasoning models (32k tokens, 10 min), log answers that miss the schema
CI / test (push) Successful in 1m3s
CI / build (push) Successful in 4m6s
CI / deploy (push) Skipped
DeepSeek V4 Pro took 301 s for a natal analysis: the 300 s timeout cut it off
and the analysis was retried until it failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-18 19:48:36 +00:00
59 changed files with 2888 additions and 361 deletions
+11 -6
View File
@@ -462,8 +462,8 @@ fn question_system(language: &str) -> String {
if language == "hu" {
let mut text = format!(
"Tapasztalt, empatikus, lélektani szemléletű asztrológus vagy a Sorsfonalak alkalmazásban. Az olvasó már \
megkapta a részletes elemzését (születési képletelemzést vagy éves előrejelzést), és most kérdez róla. Válaszolj a \
kérdésére.
megkapta a részletes elemzését (születési képletelemzést, kapcsolati elemzést vagy éves előrejelzést), és most kérdez \
róla. Válaszolj a kérdésére.
Szabályok:
- A válasz a megadott képletadatokon és az elemzésen alapuljon. Ne találj ki pozíciót, fényszöget, házat vagy dátumot, \
@@ -471,8 +471,10 @@ amely nincs az adatok között. Ha a kérdésre az adatok alapján nem lehet fel
amit a képlet erről mutat.
- Maradj összhangban az elemzéssel. Ha a kérdés olyan részletre vonatkozik, amelyet az elemzés nem tárgyalt, a \
képletadatokból egészítsd ki.
- Közvetlenül a kérdezőhöz szólj, tegező formában. Ha a kérdés két ember kapcsolatáról szól, csak abból beszélj, amit \
az adatok mutatnak.
- Közvetlenül a kérdezőhöz szólj, tegező formában. Kapcsolati elemzésnél (két képlet összevetése) a kérdező az egyik \
fél: ha a kérdésből nem derül ki, melyik, beszélj kettejükhöz („ti”, „kettőtök”). A feleket az adatokban Person 1 és \
Person 2 jelöli, a szövegben „az első fél” és „a második fél”. Ne feltételezd a nemüket és a kapcsolat jellegét, és \
csak abból beszélj, amit az adatok mutatnak.
- Hangnem: meleg, őszinte, megerősítő és konkrét. Ne légy fatalista: ne jósolj betegséget, halált, balesetet, \
terhességet vagy biztos eseményeket, és ne adj orvosi, jogi vagy pénzügyi tanácsot. Ha ilyet kérdeznek, kedvesen \
tereld a választ arra, amit az asztrológia valóban mutat: hajlamokra, időszakokra, lehetőségekre.
@@ -490,7 +492,8 @@ használhatsz.
}
format!(
"You are an experienced, warm and psychologically minded astrologer in the Sorsfonalak app. The reader has \
received their detailed analysis (a natal chart interpretation or a yearly forecast) and now asks a question about it. \
received their detailed analysis (a natal chart interpretation, a relationship analysis or a yearly forecast) and now \
asks a question about it. \
Answer it.
Write in {lang}.
@@ -499,7 +502,9 @@ Rules:
- Base the answer on the chart data and the analysis given. Never invent positions, aspects, houses or dates that are \
not listed. If the data cannot answer the question, say so honestly and describe what the chart does show about it.
- Stay consistent with the analysis; fill in details it did not cover from the chart data.
- Speak to the reader directly, in the informal second person.
- Speak to the reader directly, in the informal second person. On a relationship analysis the reader is one of the \
two people (Person 1 and Person 2 in the data); when it is unclear which, speak to both. Do not assume their genders \
or the type of relationship.
- Tone: warm, honest, empowering and concrete. Not fatalistic: no predictions of illness, death, accidents, pregnancy \
or certain events, and no medical, legal or financial advice; if asked, turn gently to what astrology does show \
(tendencies, periods, opportunities).
@@ -0,0 +1,18 @@
-- One model for all analyses (natal, synastry, forecast) and a separate one
-- for answering questions; the short summary keeps its own.
ALTER TABLE model_settings DROP CONSTRAINT model_settings_kind_check;
INSERT INTO model_settings (kind, model, updated_by, updated_at)
SELECT 'analysis', model, updated_by, updated_at FROM model_settings
WHERE kind IN ('natal', 'synastry', 'forecast') ORDER BY updated_at DESC LIMIT 1;
DELETE FROM model_settings WHERE kind IN ('natal', 'synastry', 'forecast');
ALTER TABLE model_settings ADD CONSTRAINT model_settings_kind_check
CHECK (kind IN ('summary', 'analysis', 'question'));
-- When the chosen model fails, the default model takes over (`on_fallback`).
-- NULL: the chosen model is the default, there is nothing to fall back to.
ALTER TABLE analyses
ADD COLUMN fallback_model text,
ADD COLUMN on_fallback boolean NOT NULL DEFAULT false;
ALTER TABLE questions
ADD COLUMN fallback_model text,
ADD COLUMN on_fallback boolean NOT NULL DEFAULT false;
@@ -0,0 +1,26 @@
-- Every failed attempt of an analysis, an answer or a prompt test run, for the
-- admin error log. No foreign keys: the log outlives deleted items. Kept for
-- 90 days (worker cleanup).
CREATE TABLE generation_errors (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
created_at timestamptz NOT NULL DEFAULT now(),
source text NOT NULL CHECK (source IN ('analysis', 'question', 'preview')),
item_id uuid NOT NULL,
kind text NOT NULL,
model text NOT NULL,
attempt integer NOT NULL,
-- What happened next: tried again, the default model took over, or gave up.
outcome text NOT NULL CHECK (outcome IN ('retry', 'fallback', 'failed')),
error text NOT NULL,
seconds integer
);
CREATE INDEX generation_errors_created_idx ON generation_errors (created_at DESC);
CREATE INDEX generation_errors_item_idx ON generation_errors (item_id);
-- When the current text was asked for (a regeneration or an admin restart
-- sets it again): the waiting page counts from here.
ALTER TABLE analyses ADD COLUMN requested_at timestamptz NOT NULL DEFAULT now();
UPDATE analyses SET requested_at = created_at;
ALTER TABLE questions ADD COLUMN requested_at timestamptz NOT NULL DEFAULT now();
UPDATE questions SET requested_at = created_at;
+4
View File
@@ -20,3 +20,7 @@ SIGNUP_MODE=invite
# Image version; every deployment rewrites it
TAG=latest
# worker-ai: analyses and answers written at the same time.
# QUICK_CONCURRENCY=2 # summaries and answers
# ANALYSIS_CONCURRENCY=4 # detailed analyses and forecasts
+2 -1
View File
@@ -82,7 +82,8 @@ A Google OAuth kliensnél a `https://sorsfonalak.hu` címet fel kell venni az en
## Üzemeltetés
- Naplók: `docker compose logs -f backend worker`
- Naplók: `docker compose logs -f backend worker worker-ai`
- A worker két konténerben fut, ugyanabból az image-ből: a `worker` küldi az e-maileket és takarít (`WORKER_TASKS=email,cleanup`, ide kerülnek a további háttérfeladatok is), a `worker-ai` írja az elemzéseket és a válaszokat (`WORKER_TASKS=analyses`, gyors és lassú sáv). A sávok mérete a szerver `.env` fájljában állítható (`QUICK_CONCURRENCY`, `ANALYSIS_CONCURRENCY`).
- Visszaállás korábbi verzióra: `.env`-ben `TAG=<régebbi hash>`, utána `docker compose up -d`
- Mentés: naponta egy `pg_dump` a `/opt/sorsfonalak/backups` mappába, 14 napig megmarad. A mentéseket érdemes a szerverről is elvinni (DigitalOcean backup, vagy `rsync` otthonra).
- Visszatöltés: `gunzip -c backups/sorsfonalak-<dátum>.sql.gz | docker compose exec -T postgres psql -U sorsfonalak sorsfonalak`
+24
View File
@@ -99,10 +99,12 @@ services:
logging: *logging
restart: unless-stopped
# E-mail delivery, cleanup and the other background jobs.
worker:
image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-worker:${TAG:-latest}
environment:
DATABASE_URL: postgres://sorsfonalak:${POSTGRES_PASSWORD}@postgres:5432/sorsfonalak
WORKER_TASKS: email,cleanup
# SMTP_URL or the SES credentials come from .env.secrets (docs/levelkuldes.md);
# listing them here with an empty default would override that file.
SES_REGION: ${SES_REGION:-eu-central-1}
@@ -118,11 +120,33 @@ services:
logging: *logging
restart: unless-stopped
# The same image writing the analyses and answers (quick and slow lane);
# OPENROUTER_API_KEY comes from .env.secrets.
worker-ai:
image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-worker:${TAG:-latest}
environment:
DATABASE_URL: postgres://sorsfonalak:${POSTGRES_PASSWORD}@postgres:5432/sorsfonalak
WORKER_TASKS: analyses
QUICK_CONCURRENCY: ${QUICK_CONCURRENCY:-2}
ANALYSIS_CONCURRENCY: ${ANALYSIS_CONCURRENCY:-4}
PUBLIC_BASE_URL: https://${DOMAIN}
env_file:
- path: .env.secrets
required: false
depends_on:
postgres:
condition: service_healthy
read_only: true
logging: *logging
restart: unless-stopped
frontend:
image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-frontend:${TAG:-latest}
environment:
BACKEND_URL: http://backend:8081
HOROSCOPE_API_URL: http://horoscope-api:8080
# Absolute links of the share previews (og:image).
PUBLIC_BASE_URL: https://${DOMAIN}
depends_on:
backend:
condition: service_healthy
+4 -3
View File
@@ -1,13 +1,14 @@
# Kérdések az elemzésekről
A kész részletes képletelemzés és éves előrejelzés alatt a felhasználó kérdezhet róla („Kérdezz az elemzésedről”). Minden kérdés egy `question` egységet használ; minden csomagban 3 jár, és külön is vehető (+5 kérdés, 1 000 Ft). Admin ingyen kérdez.
A kész részletes képletelemzés, kapcsolati elemzés és éves előrejelzés alatt a felhasználó kérdezhet róla („Kérdezz az elemzésedről”). Minden kérdés egy `question` egységet használ; minden csomagban 3 jár, és külön is vehető (+5 kérdés, 1 000 Ft). Admin ingyen kérdez.
## Hogyan készül a válasz
- **Modell:** ugyanaz, amelyik az elemzést írta (`analyses.model`), nem a Modellek oldalon beállított.
- **Amit a modell kap:** a képlet tömör adatsorát (előrejelzésnél az év adatait is), magát az elemzést, az ugyanerre az elemzésre feltett korábbi legfeljebb 6 kérdést a válasszal, és az új kérdést. Születési dátum, hely, idő és név nem megy ki.
- **Modell:** a Modellek oldalon külön beállítható kérdés-válasz modell (alapból Opus 5.5). Ha a választott modell hibára fut, az alapmodell válaszol (tartalék).
- **Amit a modell kap:** a képlet tömör adatsorát (kapcsolati elemzésnél mindkét képletet és az összevetést, előrejelzésnél az év adatait is), magát az elemzést, az ugyanerre az elemzésre feltett korábbi legfeljebb 6 kérdést a válasszal, és az új kérdést. Születési dátum, hely, idő és név nem megy ki.
- **Prompt:** az admin felületen szerkeszthető (Promptok → Kérdés-válasz). A szóhatár (`QUESTION_MAX_WORDS` = 250) a felhasználói üzenetben is benne van, így a prompt átírásától sem vész el. A kérdés legfeljebb 600 karakter.
- **Szabályok:** csak a képletből és az elemzésből válaszol, nem jósol betegséget, halált, balesetet, terhességet vagy biztos eseményt, nem ad orvosi, jogi, pénzügyi tanácsot; a nem asztrológiai kérdést udvariasan elhárítja; a kérdésben lévő utasításokat nem követi.
- **Kapcsolati elemzés:** az összevetés mindkét tagja kérdezhet (a saját kérdéseiből), és mindketten látják a kérdéseket és a válaszokat.
- **Egyszerre egy:** amíg egy kérdésre készül a válasz, újabb nem tehető fel ugyanarra az elemzésre (így a válaszok egymásra épülnek).
- **Hiba:** a worker újrapróbálja, mint az elemzéseket; végleges hibánál a kérdést visszaadja (egyszer).
- **Újragenerálás:** admin a válasz melletti ↻ gombbal újraírathatja (díjmentesen).
+32
View File
@@ -0,0 +1,32 @@
# Megosztás
A képletoldalon, a rövid összefoglaló alatt van a **Megosztás** gomb. Ez egy nyilvános linket ad (`/s/<kód>`), amelyen a képlet rajza és a legfrissebb rövid összefoglaló látszik. Név és születési adatok nem kerülnek rá.
- **Ugyanaz a link:** ha ugyanazt a képletet újra megosztod, a már nyitott link jön vissza (`POST /v1/shares`: új linknél 201, meglévőnél 200).
- **Visszavonás:** a „Link visszavonása” gomb után az oldal és a kép is 404-et ad.
- **Keresők:** az oldal `noindex`, a keresők nem listázzák.
## Előnézet (Facebook, Messenger, WhatsApp, LinkedIn, X)
Az oldal `og:` és `twitter:` meta tagjei:
| Tag | Tartalom |
|---|---|
| cím | az összefoglaló címe |
| leírás | az összefoglaló első ~200 karaktere |
| kép | `/s/<kód>/kep/<verzió>.png` |
A kép egy 1200×630-as PNG. A Next.js beépített képgenerálója (`next/og`) készíti kérésre, a következőkkel:
- a radix (`src/lib/wheelSvg.ts`; ugyanaz a `<ChartWheel>`, mint az oldalon, beégetett színekkel);
- a cím és a szöveg eleje;
- a Nap, a Hold és az Aszcendens jegye.
Működése:
- **Betűtípusok:** a `src/assets/og` mappából olvassa őket. Hiányzó karakter miatt soha nem tölt le fontot az internetről, mert a nem betű, szám vagy írásjel karaktereket kiszűri.
- **Verzió:** a fájlnévben lévő verzió az összefoglaló azonosítójából és elkészültének idejéből készül. Ha az összefoglaló újragenerálódik, új címet kap a kép, és a Facebook újra letölti.
- **Gyorsítótár:** `Cache-Control: public, max-age=3600, s-maxage=86400`. A Cloudflare egy napig tartja, így egy visszavont link képe legfeljebb egy napig marad ott. A Facebook a saját példányát a saját szabályai szerint tartja meg, nagyjából 30 napig.
- **Frissítés kézzel:** a Facebook megosztás-ellenőrzőjében (Sharing Debugger) a „Scrape Again” gombbal.
A frontend a `PUBLIC_BASE_URL` alapján írja az abszolút címeket; élesben ez `https://${DOMAIN}`.
+6 -3
View File
@@ -20,8 +20,8 @@ Felhasználók, belépés, mentett születési képletek, szinasztriák és megh
| `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 |
| `ANALYSIS_MODEL` | `anthropic/claude-opus-5.5` | alapból ez írja a fizetős részletes elemzéseket (az admin felületen funkciónként felülírható) |
| `SUMMARY_MODEL` | `anthropic/claude-sonnet-5.5` | alapból ez írja minden mentett képlet ingyenes rövid összefoglalóját (kb. 1 cent darabonként) |
| `ANALYSIS_MODEL` | `anthropic/claude-opus-5.5` | az elemzések, előrejelzések és válaszok alapmodellje, és a tartalék, ha a választott modell hibára fut |
| `SUMMARY_MODEL` | `anthropic/claude-opus-5.5` | a rövid összefoglaló alapmodellje (az admin felületen olcsóbbra állítható) |
| `OPENROUTER_MODELS_URL` | `https://openrouter.ai/api/v1/models` | az admin modellválasztó listája árakkal (óránként egyszer kérdezi le) |
| `ANALYSIS_PROMPT_VERSION` | `v3` | a prompt verziója (az elemzés-gyorsítótár kulcsának része) |
| `MAX_CHARTS_PER_USER` | `1000` | biztonsági felső korlát a képletek számára |
@@ -125,7 +125,10 @@ Hibák formátuma: `{"error": {"code", "message"}}`. A születési adatok hibái
- **Ingyenes rész:** minden mentett képlethez elkészül egy rövid összefoglaló (`summary`, `SUMMARY_MODEL`), ezért nem kell fizetni.
- **Fizetős rész:** a részletes elemzés darabra megy. A képletelemzés egy `natal`, a szinasztria-elemzés egy `synastry` egységet von le (`credit_ledger.unit`). Az egységek csomagvásárlásból (Stripe, később) vagy admin jóváírásból jönnek. Havi ingyenes keret nincs.
- **Modell:** funkciónként (összefoglaló, képletelemzés, kapcsolati elemzés, előrejelzés) az admin felületen választható az OpenRouter listájából (`model_settings` tábla); ha nincs beállítva, az `ANALYSIS_MODEL` / `SUMMARY_MODEL` (alapból Opus 5.5, a 2026-11-es összevetés legjobbja, lásd `services/worker/README.md`). Csak kötött JSON-választ adó modell választható. A kliens nem választ modellt, és a modell neve felhasználónak sehol nem jelenik meg.
- **Modell:** három beállítás az admin felületen, az OpenRouter listájából (`model_settings` tábla): az elemzések és az éves előrejelzés (képlet-, kapcsolati elemzés, előrejelzés) közös modellje, a kérdés-válasz modellje és a rövid összefoglalóé. Ha nincs beállítva, az `ANALYSIS_MODEL` / `SUMMARY_MODEL` (alapból mindkettő Opus 5.5, a 2026-11-es összevetés legjobbja, lásd `services/worker/README.md`). Csak kötött JSON-választ adó modell választható. A kliens nem választ modellt, és a modell neve felhasználónak sehol nem jelenik meg.
- **Tartalék:** ha a választott modell kétszer hibára fut (végleges hibánál egyszer), a worker az alapmodellel próbálja tovább (`fallback_model`, `on_fallback`); csak ha az is elbukik, jár vissza az egység. A Modellek oldal mutatja, hány szövegnél kellett az elmúlt 30 napban.
- **Hibanapló:** a worker minden sikertelen próbálkozást a `generation_errors` táblába ír (mi, melyik modell, hányadik kísérlet, mi lett: újrapróbálás, tartalék vagy végleges hiba, mennyi ideig tartott); az admin Hibanapló oldala mutatja (`GET /v1/admin/errors?source=&outcome=`), 90 napig őrizzük. A felhasználó a várakozó oldalon látja, ha az előző próbálkozás nem sikerült és újrapróbáljuk; a számláló a kérés idejétől (`requested_at`) mér.
- **Futó generálások:** a Modellek oldalon látszik minden készülő és sorban álló elemzés és válasz, a modelljével és azzal, amivel most indulna; újraindításkor a jelenlegi beállítással indul újra (`GET /v1/admin/jobs`, `POST /v1/admin/jobs/restart`). Minden kísérlet `started_at` értéke a „jegye”: az újraindítás törli, így a workerben még futó régi kísérlet nem írhatja felül az újat, és a worker 10 másodpercen belül eldobja.
- **Újragenerálás:** admin minden elemzést egyenként újraírathat (`POST /v1/admin/analyses/{id}/regenerate`): ugyanaz a sor (az azonosító és a megosztások maradnak), a jelenlegi prompttal és modellel, egységlevonás nélkül.
- **Újraszámolás:** számítási változás után a `backend recalculate` parancs minden mentett képletet, összevetést és előrejelzést újraszámol, majd minden elemzést újra sorba állít (egységlevonás nélkül).
- **Kérés:** a `POST .../analyses` (`{language?}`) létrehoz egy `pending` elemzést, és levon egy egységet; a szöveget a worker írja meg, általában 1–2 perc alatt. A kliens a `GET /v1/analyses/{id}` végponton kérdezi le az állapotát. Ha nincs egység, 402 `insufficient_credits` a válasz (`unit`, `balance` részletekkel). Hiba esetén a worker visszaadja az egységet.
+6 -4
View File
@@ -55,11 +55,13 @@ pub struct Config {
pub bootstrap_admin_emails: Vec<String>,
/// `SUPPORTED_LOCALES` (default `hu,en`); the first is the default.
pub supported_locales: Vec<String>,
/// `ANALYSIS_MODEL`: writes the paid detailed analyses (default
/// `ANALYSIS_MODEL`: the default model of the analyses, forecasts and
/// answers, and the fallback when a chosen model fails (default
/// `anthropic/claude-opus-5.5`, the best of the 2026-11 comparison).
pub analysis_model: String,
/// `SUMMARY_MODEL`: writes the free short summary of every saved chart
/// (default `anthropic/claude-sonnet-5.5`, about 1 US cent each).
/// `SUMMARY_MODEL`: the default model of the free short summary of every
/// saved chart (default `anthropic/claude-opus-5.5`; the admin page can
/// choose a cheaper one).
pub summary_model: String,
/// `OPENROUTER_MODELS_URL` (default `https://openrouter.ai/api/v1/models`):
/// the model list with prices for the admin page.
@@ -123,7 +125,7 @@ impl Config {
bootstrap_admin_emails: list("BOOTSTRAP_ADMIN_EMAILS").into_iter().map(|e| e.to_lowercase()).collect(),
supported_locales,
analysis_model: var("ANALYSIS_MODEL").unwrap_or_else(|| "anthropic/claude-opus-5.5".into()),
summary_model: var("SUMMARY_MODEL").unwrap_or_else(|| "anthropic/claude-sonnet-5.5".into()),
summary_model: var("SUMMARY_MODEL").unwrap_or_else(|| "anthropic/claude-opus-5.5".into()),
openrouter_models_url: var("OPENROUTER_MODELS_URL")
.unwrap_or_else(|| "https://openrouter.ai/api/v1/models".into()),
prompt_version: var("ANALYSIS_PROMPT_VERSION").unwrap_or_else(|| "v3".into()),
+56 -10
View File
@@ -2,8 +2,9 @@
//! offers (with prices) for the admin page.
//!
//! The choice is in `model_settings`; without a row the configured default
//! is used (`SUMMARY_MODEL` for the short summary, `ANALYSIS_MODEL` else).
//! The model is never shown to users (a business secret).
//! is used (`SUMMARY_MODEL` for the short summary, `ANALYSIS_MODEL` else,
//! both Opus 5.5 by default). When the chosen model fails, the worker falls
//! back to the default. The model is never shown to users (a business secret).
use std::sync::Arc;
use std::time::{Duration, Instant};
@@ -18,21 +19,66 @@ use crate::AppState;
/// The OpenRouter list is fetched at most this often.
const CATALOG_TTL: Duration = Duration::from_secs(3600);
/// The configured default model of a kind.
pub fn default_model(state: &AppState, kind: Kind) -> &str {
/// The model settings of the admin page: one model writes all analyses and
/// forecasts, another the answers to questions, a third the short summary.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Function {
Summary,
Analysis,
Question,
}
impl Function {
pub const ALL: [Function; 3] = [Function::Summary, Function::Analysis, Function::Question];
pub fn key(self) -> &'static str {
match self {
Function::Summary => "summary",
Function::Analysis => "analysis",
Function::Question => "question",
}
}
pub fn parse(key: &str) -> Option<Function> {
Function::ALL.into_iter().find(|f| f.key() == key)
}
pub fn of(kind: Kind) -> Function {
match kind {
Kind::Summary => &state.config.summary_model,
_ => &state.config.analysis_model,
Kind::Summary => Function::Summary,
Kind::Question => Function::Question,
Kind::Natal | Kind::Synastry | Kind::Forecast => Function::Analysis,
}
}
}
/// The model new analyses of this kind are written with.
pub async fn model_for(state: &AppState, kind: Kind) -> Result<String, sqlx::Error> {
/// The configured default model of a function; also the fallback when the
/// chosen model fails.
pub fn default_model(state: &AppState, function: Function) -> &str {
match function {
Function::Summary => &state.config.summary_model,
Function::Analysis | Function::Question => &state.config.analysis_model,
}
}
/// The model new texts of this kind are written with, and the fallback model
/// (`None` when the chosen model is the default).
pub async fn models_for(state: &AppState, kind: Kind) -> Result<(String, Option<String>), sqlx::Error> {
let function = Function::of(kind);
let chosen: Option<String> = sqlx::query_scalar("SELECT model FROM model_settings WHERE kind = $1")
.bind(kind.as_str())
.bind(function.key())
.fetch_optional(&state.db)
.await?;
Ok(chosen.unwrap_or_else(|| default_model(state, kind).to_owned()))
let default = default_model(state, function);
Ok(match chosen {
Some(model) if model != default => (model, Some(default.to_owned())),
_ => (default.to_owned(), None),
})
}
/// The model new texts of this kind are written with.
pub async fn model_for(state: &AppState, kind: Kind) -> Result<String, sqlx::Error> {
Ok(models_for(state, kind).await?.0)
}
/// One model OpenRouter offers, with its price in USD per million tokens.
+31 -28
View File
@@ -49,11 +49,16 @@ pub struct AnalysisRow {
pub credits_charged: i32,
pub created_at: OffsetDateTime,
pub completed_at: Option<OffsetDateTime>,
/// Attempts so far; above 1 the page says it is being tried again.
pub attempts: i32,
pub next_attempt_at: OffsetDateTime,
/// When the current text was asked for (set again by a regeneration).
pub requested_at: OffsetDateTime,
}
const ANALYSIS_COLUMNS: &str = "id, kind, chart_id, synastry_id, forecast_id, language, prompt_version, status, \
content, error, \
credits_charged, created_at, completed_at";
credits_charged, created_at, completed_at, attempts, next_attempt_at, requested_at";
impl AnalysisRow {
pub fn view(&self) -> Value {
@@ -71,6 +76,9 @@ impl AnalysisRow {
"credits_charged": self.credits_charged,
"created_at": rfc3339(self.created_at),
"completed_at": rfc3339_opt(self.completed_at),
"attempts": self.attempts,
"next_attempt_at": rfc3339(self.next_attempt_at),
"requested_at": rfc3339(self.requested_at),
})
}
}
@@ -146,7 +154,7 @@ async fn request(
/// The cache key and the prompt version of a new analysis. The cache key leaves
/// out the admin-edited prompt revision, so a chart keeps its analysis when the
/// prompt changes; copying from another chart needs the same revision.
async fn versions(
pub(super) async fn versions(
state: &AppState,
kind: &str,
hash: &str,
@@ -175,7 +183,7 @@ pub(super) async fn queue(
Target::Synastry { synastry_id, hash } => ("synastry", hash, None, Some(*synastry_id), None),
Target::Forecast { forecast_id, hash } => ("forecast", hash, None, None, Some(*forecast_id)),
};
let model = &crate::models::model_for(state, Kind::parse(kind).expect("known kind")).await?;
let (model, fallback) = &crate::models::models_for(state, Kind::parse(kind).expect("known kind")).await?;
let (cache_key, prompt_version) = &versions(state, kind, hash, model, language).await?;
// Already requested for this chart/synastry: return it.
@@ -197,8 +205,8 @@ pub(super) async fn queue(
let insert = format!(
"INSERT INTO analyses (id, kind, chart_id, synastry_id, requested_by, language, model, prompt_version, \
cache_key, status, content, input_tokens, output_tokens, credits_charged, completed_at, \
forecast_id) \
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16) RETURNING {ANALYSIS_COLUMNS}"
forecast_id, fallback_model) \
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17) RETURNING {ANALYSIS_COLUMNS}"
);
let id = Uuid::now_v7();
@@ -229,6 +237,7 @@ pub(super) async fn queue(
.bind(0)
.bind(OffsetDateTime::now_utc())
.bind(forecast_id)
.bind(fallback)
.fetch_one(&state.db)
.await?;
return Ok((StatusCode::CREATED, row));
@@ -253,6 +262,7 @@ pub(super) async fn queue(
.bind(i32::from(unit.is_some()))
.bind(None::<OffsetDateTime>)
.bind(forecast_id)
.bind(fallback)
.fetch_one(&mut *tx)
.await?;
if let Some(unit) = unit {
@@ -357,6 +367,17 @@ pub async fn request_for_forecast(
request(&state, &auth, Target::Forecast { forecast_id: forecast.id, hash: forecast.forecast_hash }, req).await
}
/// The hash of what the analysis is about (chart, comparison or forecast),
/// part of its cache key; `None` when that was deleted.
pub(super) async fn target_hash(db: &PgPool, row: &AnalysisRow) -> Result<Option<String>, sqlx::Error> {
let (query, id) = match row.kind.as_str() {
"synastry" => ("SELECT synastry_hash FROM synastries WHERE id = $1", row.synastry_id),
"forecast" => ("SELECT forecast_hash FROM forecasts WHERE id = $1", row.forecast_id),
_ => ("SELECT chart_hash FROM charts WHERE id = $1", row.chart_id),
};
sqlx::query_scalar(query).bind(id).fetch_optional(db).await
}
/// Admin: writes an analysis again in place (same id, so links stay), with the
/// current prompt and model. Nobody is charged.
pub async fn regenerate(
@@ -369,41 +390,23 @@ pub async fn regenerate(
return Err(ApiError::conflict("analysis_in_progress", "Ez az elemzés éppen készül."));
}
let kind = Kind::parse(&row.kind).ok_or_else(|| ApiError::Internal(format!("unknown kind {}", row.kind)))?;
let hash: Option<String> = match kind {
Kind::Question => None,
Kind::Natal | Kind::Summary => {
sqlx::query_scalar("SELECT chart_hash FROM charts WHERE id = $1")
.bind(row.chart_id)
.fetch_optional(&state.db)
.await?
}
Kind::Synastry => {
sqlx::query_scalar("SELECT synastry_hash FROM synastries WHERE id = $1")
.bind(row.synastry_id)
.fetch_optional(&state.db)
.await?
}
Kind::Forecast => {
sqlx::query_scalar("SELECT forecast_hash FROM forecasts WHERE id = $1")
.bind(row.forecast_id)
.fetch_optional(&state.db)
.await?
}
};
let hash = target_hash(&state.db, &row).await?;
let hash = hash.ok_or(ApiError::NotFound("analysis"))?;
let model = crate::models::model_for(&state, kind).await?;
let (model, fallback) = crate::models::models_for(&state, kind).await?;
let (cache_key, prompt_version) = versions(&state, kind.as_str(), &hash, &model, &row.language).await?;
let mut tx = state.db.begin().await?;
let row: AnalysisRow = sqlx::query_as(&format!(
"UPDATE analyses SET status = 'pending', content = NULL, error = NULL, model_used = NULL, \
input_tokens = NULL, output_tokens = NULL, cost_usd = NULL, attempts = 0, next_attempt_at = now(), \
started_at = NULL, completed_at = NULL, model = $2, prompt_version = $3, cache_key = $4 \
started_at = NULL, completed_at = NULL, model = $2, prompt_version = $3, cache_key = $4, \
fallback_model = $5, on_fallback = false, requested_at = now() \
WHERE id = $1 AND status IN ('done', 'failed') RETURNING {ANALYSIS_COLUMNS}"
))
.bind(id)
.bind(&model)
.bind(&prompt_version)
.bind(&cache_key)
.bind(&fallback)
.fetch_optional(&mut *tx)
.await?
.ok_or_else(|| ApiError::conflict("analysis_in_progress", "Ez az elemzés éppen készül."))?;
+73
View File
@@ -0,0 +1,73 @@
//! Admin: the error log of the analyses, answers and prompt test runs (every
//! failed attempt, written by the worker), newest first.
use axum::Json;
use axum::extract::{Query, State};
use axum_extra::extract::WithRejection;
use serde::Deserialize;
use serde_json::{Value, json};
use time::OffsetDateTime;
use uuid::Uuid;
use super::St;
use crate::auth::AdminUser;
use crate::error::{ApiError, ApiResult};
use crate::views::rfc3339;
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ErrorQuery {
limit: Option<i64>,
offset: Option<i64>,
/// `analysis`, `question` or `preview`.
source: Option<String>,
/// `retry`, `fallback` or `failed`.
outcome: Option<String>,
}
type Row = (i64, OffsetDateTime, String, Uuid, String, String, i32, String, String, Option<i32>, Option<String>);
pub async fn list(
State(state): St,
_admin: AdminUser,
WithRejection(Query(query), _): WithRejection<Query<ErrorQuery>, ApiError>,
) -> ApiResult<Json<Value>> {
let limit = query.limit.unwrap_or(100).clamp(1, 500);
let offset = query.offset.unwrap_or(0).max(0);
// Whose text it was: the requester of the analysis or the asker.
let rows: Vec<Row> = sqlx::query_as(
"SELECT e.id, e.created_at, e.source, e.item_id, e.kind, e.model, e.attempt, e.outcome, e.error, e.seconds, \
u.email \
FROM generation_errors e \
LEFT JOIN analyses a ON e.source = 'analysis' AND a.id = e.item_id \
LEFT JOIN questions q ON e.source = 'question' AND q.id = e.item_id \
LEFT JOIN prompt_previews p ON e.source = 'preview' AND p.id = e.item_id \
LEFT JOIN users u ON u.id = coalesce(a.requested_by, q.asked_by, p.created_by) \
WHERE ($1::text IS NULL OR e.source = $1) AND ($2::text IS NULL OR e.outcome = $2) \
ORDER BY e.id DESC LIMIT $3 OFFSET $4",
)
.bind(&query.source)
.bind(&query.outcome)
.bind(limit)
.bind(offset)
.fetch_all(&state.db)
.await?;
let (total, last_day): (i64, i64) = sqlx::query_as(
"SELECT count(*), count(*) FILTER (WHERE created_at > now() - interval '1 day') FROM generation_errors \
WHERE ($1::text IS NULL OR source = $1) AND ($2::text IS NULL OR outcome = $2)",
)
.bind(&query.source)
.bind(&query.outcome)
.fetch_one(&state.db)
.await?;
let errors: Vec<Value> = rows
.into_iter()
.map(|(id, at, source, item, kind, model, attempt, outcome, error, seconds, email)| {
json!({
"id": id, "created_at": rfc3339(at), "source": source, "item_id": item, "kind": kind, "model": model,
"attempt": attempt, "outcome": outcome, "error": error, "seconds": seconds, "user": email,
})
})
.collect();
Ok(Json(json!({ "errors": errors, "total": total, "last_day": last_day, "limit": limit, "offset": offset })))
}
+150
View File
@@ -0,0 +1,150 @@
//! Admin: the analyses and answers being written or waiting in the queue,
//! and restarting them with the models set now (e.g. after switching away
//! from a slow model). A restarted attempt that is still running in the
//! worker is dropped there and cannot overwrite the new one.
use std::collections::HashMap;
use analysis_prompt::Kind;
use axum::Json;
use axum::extract::State;
use axum_extra::extract::WithRejection;
use serde::Deserialize;
use serde_json::{Value, json};
use time::OffsetDateTime;
use uuid::Uuid;
use super::analyses::{find_analysis, target_hash, versions};
use super::{Body, St};
use crate::AppState;
use crate::auth::AdminUser;
use crate::error::ApiResult;
use crate::models::{Function, models_for};
use crate::views::{rfc3339, rfc3339_opt};
type JobRow = (
Uuid,
String,
String,
String,
Option<String>,
bool,
i32,
Option<OffsetDateTime>,
OffsetDateTime,
OffsetDateTime,
Option<String>,
);
const COLUMNS: &str =
"id, kind, status, model, fallback_model, on_fallback, attempts, started_at, created_at, next_attempt_at, error";
async fn open_jobs(state: &AppState) -> Result<Vec<(&'static str, JobRow)>, sqlx::Error> {
let analyses: Vec<JobRow> = sqlx::query_as(&format!(
"SELECT {COLUMNS} FROM analyses WHERE status IN ('pending', 'running') ORDER BY created_at"
))
.fetch_all(&state.db)
.await?;
let questions: Vec<JobRow> = sqlx::query_as(
"SELECT id, 'question', status, model, fallback_model, on_fallback, attempts, started_at, created_at, \
next_attempt_at, error \
FROM questions WHERE status IN ('pending', 'running') ORDER BY created_at",
)
.fetch_all(&state.db)
.await?;
Ok(analyses.into_iter().map(|r| ("analysis", r)).chain(questions.into_iter().map(|r| ("question", r))).collect())
}
pub async fn list(State(state): St, _admin: AdminUser) -> ApiResult<Json<Value>> {
Ok(Json(json!({ "jobs": views(&state).await? })))
}
async fn views(state: &AppState) -> Result<Vec<Value>, sqlx::Error> {
// The models a restart would use, per function.
let mut next: HashMap<&'static str, (String, Option<String>)> = HashMap::new();
for (function, kind) in
[(Function::Summary, Kind::Summary), (Function::Analysis, Kind::Natal), (Function::Question, Kind::Question)]
{
next.insert(function.key(), models_for(state, kind).await?);
}
Ok(open_jobs(state)
.await?
.into_iter()
.map(|(table, (id, kind, status, model, fallback, on_fallback, attempts, started, created, due, error))| {
let function = Function::of(Kind::parse(&kind).unwrap_or(Kind::Natal)).key();
let (next_model, next_fallback) = &next[function];
let active = if on_fallback { fallback.clone().unwrap_or_else(|| model.clone()) } else { model.clone() };
json!({
"id": id, "type": table, "kind": kind, "status": status, "model": active, "on_fallback": on_fallback,
"next_model": next_model, "next_fallback": next_fallback, "attempts": attempts,
"started_at": rfc3339_opt(started), "created_at": rfc3339(created), "next_attempt_at": rfc3339(due),
"error": error,
})
})
.collect())
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Restart {
/// The jobs to restart; all open ones when missing.
ids: Option<Vec<Uuid>>,
}
pub async fn restart(
State(state): St,
AdminUser(admin): AdminUser,
WithRejection(Json(req), _): Body<Restart>,
) -> ApiResult<Json<Value>> {
let mut restarted = 0;
for (table, (id, kind, ..)) in open_jobs(&state).await? {
if req.ids.as_ref().is_some_and(|ids| !ids.contains(&id)) {
continue;
}
let done = if table == "question" {
let language: String = sqlx::query_scalar("SELECT language FROM questions WHERE id = $1")
.bind(id)
.fetch_one(&state.db)
.await?;
let (model, fallback, prompt_version) = super::questions::model_and_version(&state, &language).await?;
sqlx::query(
"UPDATE questions SET status = 'pending', model = $2, fallback_model = $3, on_fallback = false, \
prompt_version = $4, attempts = 0, next_attempt_at = now(), started_at = NULL, error = NULL, \
requested_at = now() \
WHERE id = $1 AND status IN ('pending', 'running')",
)
.bind(id)
.bind(&model)
.bind(&fallback)
.bind(&prompt_version)
.execute(&state.db)
.await?
.rows_affected()
} else {
let Some(row) = find_analysis(&state.db, id).await? else { continue };
let Some(hash) = target_hash(&state.db, &row).await? else { continue };
let (model, fallback) = models_for(&state, Kind::parse(&kind).unwrap_or(Kind::Natal)).await?;
let (cache_key, prompt_version) = versions(&state, &kind, &hash, &model, &row.language).await?;
sqlx::query(
"UPDATE analyses SET status = 'pending', model = $2, fallback_model = $3, on_fallback = false, \
cache_key = $4, prompt_version = $5, attempts = 0, next_attempt_at = now(), started_at = NULL, \
error = NULL, requested_at = now() \
WHERE id = $1 AND status IN ('pending', 'running')",
)
.bind(id)
.bind(&model)
.bind(&fallback)
.bind(&cache_key)
.bind(&prompt_version)
.execute(&state.db)
.await?
.rows_affected()
};
restarted += done;
}
if restarted > 0 {
sqlx::query("SELECT pg_notify('analyses', '')").execute(&state.db).await?;
}
tracing::info!(admin = %admin.id(), restarted, "generations restarted");
Ok(Json(json!({ "restarted": restarted, "jobs": views(&state).await? })))
}
+5
View File
@@ -10,8 +10,10 @@ mod admin;
mod analyses;
mod auth;
mod charts;
mod errors;
mod forecasts;
mod invitations;
mod jobs;
mod models;
mod payments;
mod prompts;
@@ -116,6 +118,9 @@ pub fn router(state: Arc<AppState>) -> Router {
.route("/v1/admin/prompts/{kind}/{language}", axum::routing::put(prompts::save))
.route("/v1/admin/prompts/{kind}/{language}/preview", post(prompts::start_preview))
.route("/v1/admin/previews/{id}", get(prompts::get_preview))
.route("/v1/admin/errors", get(errors::list))
.route("/v1/admin/jobs", get(jobs::list))
.route("/v1/admin/jobs/restart", post(jobs::restart))
.route("/v1/admin/models", get(models::list))
.route("/v1/admin/models/catalog", get(models::catalog))
.route("/v1/admin/models/{kind}", axum::routing::put(models::save))
+36 -23
View File
@@ -1,7 +1,7 @@
//! Admin: which model writes which kind of analysis, chosen from the models
//! OpenRouter offers. A change applies to analyses requested after it.
//! Admin: which model writes the analyses and forecasts, the answers to
//! questions and the short summary, chosen from the models OpenRouter offers.
//! A change applies to texts requested after it.
use analysis_prompt::Kind;
use axum::Json;
use axum::extract::{Path, State};
use axum_extra::extract::WithRejection;
@@ -13,7 +13,7 @@ use super::{Body, St};
use crate::AppState;
use crate::auth::AdminUser;
use crate::error::{ApiError, ApiResult};
use crate::models::default_model;
use crate::models::{Function, default_model};
use crate::views::rfc3339;
fn catalog_error(e: String) -> ApiError {
@@ -23,27 +23,38 @@ fn catalog_error(e: String) -> ApiError {
}
}
async fn entry(state: &AppState, kind: Kind) -> Result<Value, sqlx::Error> {
async fn entry(state: &AppState, function: Function) -> Result<Value, sqlx::Error> {
let chosen: Option<(String, OffsetDateTime, Option<String>)> = sqlx::query_as(
"SELECT m.model, m.updated_at, u.email FROM model_settings m LEFT JOIN users u ON u.id = m.updated_by \
WHERE m.kind = $1",
)
.bind(kind.as_str())
.bind(function.key())
.fetch_optional(&state.db)
.await?;
// Typical size of this kind of analysis, from the latest ones: for the cost estimate.
let (input, output, samples): (Option<f64>, Option<f64>, i64) = sqlx::query_as(
// Typical size of the latest texts, for the cost estimate, and how often
// the default model had to take over in the last 30 days.
let (table, kinds) = match function {
Function::Summary => ("analyses", "kind = 'summary'"),
Function::Analysis => ("analyses", "kind IN ('natal', 'synastry', 'forecast')"),
Function::Question => ("questions", "true"),
};
let (input, output, samples): (Option<f64>, Option<f64>, i64) = sqlx::query_as(&format!(
"SELECT avg(input_tokens)::float8, avg(output_tokens)::float8, count(*) FROM ( \
SELECT input_tokens, output_tokens FROM analyses \
WHERE kind = $1 AND status = 'done' AND input_tokens IS NOT NULL AND output_tokens IS NOT NULL \
ORDER BY completed_at DESC LIMIT 50) recent",
)
.bind(kind.as_str())
SELECT input_tokens, output_tokens FROM {table} \
WHERE {kinds} AND status = 'done' AND input_tokens IS NOT NULL AND output_tokens IS NOT NULL \
ORDER BY completed_at DESC LIMIT 50) recent"
))
.fetch_one(&state.db)
.await?;
let default = default_model(state, kind);
let (fallbacks, finished): (i64, i64) = sqlx::query_as(&format!(
"SELECT count(*) FILTER (WHERE on_fallback), count(*) FROM {table} \
WHERE {kinds} AND status IN ('done', 'failed') AND completed_at > now() - interval '30 days'"
))
.fetch_one(&state.db)
.await?;
let default = default_model(state, function);
Ok(json!({
"kind": kind.as_str(),
"kind": function.key(),
"model": chosen.as_ref().map_or(default, |c| c.0.as_str()),
"default": default,
"custom": chosen.is_some(),
@@ -52,13 +63,15 @@ async fn entry(state: &AppState, kind: Kind) -> Result<Value, sqlx::Error> {
"avg_input_tokens": input,
"avg_output_tokens": output,
"samples": samples,
"fallbacks_30d": fallbacks,
"finished_30d": finished,
}))
}
pub async fn list(State(state): St, _admin: AdminUser) -> ApiResult<Json<Value>> {
let mut functions = Vec::new();
for kind in Kind::ANALYSES {
functions.push(entry(&state, kind).await?);
for function in Function::ALL {
functions.push(entry(&state, function).await?);
}
Ok(Json(json!({ "functions": functions })))
}
@@ -81,9 +94,9 @@ pub async fn save(
WithRejection(Path(kind), _): WithRejection<Path<String>, ApiError>,
WithRejection(Json(req), _): Body<SaveModel>,
) -> ApiResult<Json<Value>> {
let kind = Kind::parse(&kind).ok_or(ApiError::NotFound("function"))?;
let function = Function::parse(&kind).ok_or(ApiError::NotFound("function"))?;
match req.model.as_deref().map(str::trim) {
Some(model) if model != default_model(&state, kind) => {
Some(model) if model != default_model(&state, function) => {
let models = state.models.models().await.map_err(catalog_error)?;
if !models.iter().any(|m| m.id == model) {
return Err(ApiError::BadRequest(format!(
@@ -95,16 +108,16 @@ pub async fn save(
ON CONFLICT (kind) DO UPDATE SET model = EXCLUDED.model, updated_by = EXCLUDED.updated_by, \
updated_at = now()",
)
.bind(kind.as_str())
.bind(function.key())
.bind(model)
.bind(admin.id())
.execute(&state.db)
.await?;
}
_ => {
sqlx::query("DELETE FROM model_settings WHERE kind = $1").bind(kind.as_str()).execute(&state.db).await?;
sqlx::query("DELETE FROM model_settings WHERE kind = $1").bind(function.key()).execute(&state.db).await?;
}
}
tracing::info!(admin = %admin.id(), kind = kind.as_str(), "analysis model changed");
Ok(Json(entry(&state, kind).await?))
tracing::info!(admin = %admin.id(), function = function.key(), "model changed");
Ok(Json(entry(&state, function).await?))
}
+36 -25
View File
@@ -1,7 +1,8 @@
//! Questions about a finished detailed analysis: a natal chart analysis or a
//! yearly forecast. Each question uses a `question` unit (admins ask for
//! free). The worker answers with the model that wrote the analysis, seeing
//! the chart data, the analysis and the earlier questions about it.
//! Questions about a finished detailed analysis: a natal chart analysis, a
//! relationship (synastry) analysis or a yearly forecast. On a comparison both
//! people see the questions and answers. Each question uses a `question` unit (admins ask for
//! free). The worker answers with the question model of the admin page,
//! seeing the chart data, the analysis and the earlier questions about it.
use analysis_prompt::{Kind, QUESTION_MAX_CHARS};
use axum::Json;
@@ -23,7 +24,7 @@ use crate::error::{ApiError, ApiResult};
use crate::views::{rfc3339, rfc3339_opt};
/// The analyses that can be asked about.
const ASKABLE: [&str; 2] = ["natal", "forecast"];
const ASKABLE: [&str; 3] = ["natal", "synastry", "forecast"];
/// A safety cap per analysis.
const MAX_PER_ANALYSIS: i64 = 100;
@@ -39,10 +40,13 @@ pub struct QuestionRow {
pub credits_charged: i32,
pub created_at: OffsetDateTime,
pub completed_at: Option<OffsetDateTime>,
pub attempts: i32,
pub next_attempt_at: OffsetDateTime,
pub requested_at: OffsetDateTime,
}
const QUESTION_COLUMNS: &str =
"id, analysis_id, question, status, answer, error, credits_charged, created_at, completed_at";
const QUESTION_COLUMNS: &str = "id, analysis_id, question, status, answer, error, credits_charged, created_at, \
completed_at, attempts, next_attempt_at, requested_at";
impl QuestionRow {
pub fn view(&self) -> Value {
@@ -56,6 +60,9 @@ impl QuestionRow {
"credits_charged": self.credits_charged,
"created_at": rfc3339(self.created_at),
"completed_at": rfc3339_opt(self.completed_at),
"attempts": self.attempts,
"next_attempt_at": rfc3339(self.next_attempt_at),
"requested_at": rfc3339(self.requested_at),
})
}
}
@@ -64,21 +71,19 @@ async fn find_question(db: &PgPool, id: Uuid) -> Result<Option<QuestionRow>, sql
sqlx::query_as(&format!("SELECT {QUESTION_COLUMNS} FROM questions WHERE id = $1")).bind(id).fetch_optional(db).await
}
/// The model of the analysis (questions are answered by the same model) and
/// the prompt version of the question prompt in force.
async fn model_and_version(
/// The question model (and its fallback) and the version of the question
/// prompt in force.
pub(super) async fn model_and_version(
state: &crate::AppState,
analysis_id: Uuid,
language: &str,
) -> Result<(String, String), sqlx::Error> {
let model: String =
sqlx::query_scalar("SELECT model FROM analyses WHERE id = $1").bind(analysis_id).fetch_one(&state.db).await?;
) -> Result<(String, Option<String>, String), sqlx::Error> {
let (model, fallback) = crate::models::models_for(state, Kind::Question).await?;
let base = &state.config.prompt_version;
let version = match super::prompts::current_revision(&state.db, Kind::Question.as_str(), language).await? {
Some(id) => format!("{base}-r{id}"),
None => base.clone(),
};
Ok((model, version))
Ok((model, fallback, version))
}
pub async fn list(State(state): St, auth: AuthUser, WithRejection(Path(id), _): IdPath) -> ApiResult<Json<Value>> {
@@ -111,7 +116,7 @@ pub async fn ask(
return Err(ApiError::NotFound("analysis"));
}
if !ASKABLE.contains(&analysis.kind.as_str()) {
return Err(ApiError::BadRequest("questions can be asked about a natal analysis or a forecast".into()));
return Err(ApiError::BadRequest("questions can be asked about a detailed analysis or a forecast".into()));
}
if analysis.status != "done" {
return Err(ApiError::conflict("analysis_not_ready", "Az elemzés még nem készült el."));
@@ -141,12 +146,13 @@ pub async fn ask(
}
let admin = auth.user.has_role(Role::Admin);
let (model, prompt_version) = model_and_version(&state, id, &analysis.language).await?;
let (model, fallback, prompt_version) = model_and_version(&state, &analysis.language).await?;
let question_id = Uuid::now_v7();
let mut tx = state.db.begin().await?;
let row: QuestionRow = sqlx::query_as(&format!(
"INSERT INTO questions (id, analysis_id, asked_by, question, language, model, prompt_version, credits_charged) \
VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING {QUESTION_COLUMNS}"
"INSERT INTO questions (id, analysis_id, asked_by, question, language, model, prompt_version, credits_charged, \
fallback_model) \
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING {QUESTION_COLUMNS}"
))
.bind(question_id)
.bind(id)
@@ -156,6 +162,7 @@ pub async fn ask(
.bind(&model)
.bind(&prompt_version)
.bind(i32::from(!admin))
.bind(&fallback)
.fetch_one(&mut *tx)
.await?;
if !admin {
@@ -175,26 +182,30 @@ pub async fn get_one(State(state): St, auth: AuthUser, WithRejection(Path(id), _
}
/// Admin: answers a question again in place, with the current question prompt
/// and the analysis's model. Nobody is charged.
/// and model. Nobody is charged.
pub async fn regenerate(
State(state): St,
_admin: AdminUser,
WithRejection(Path(id), _): IdPath,
) -> ApiResult<Json<Value>> {
let row = find_question(&state.db, id).await?.ok_or(ApiError::NotFound("question"))?;
let language: String =
sqlx::query_scalar("SELECT language FROM questions WHERE id = $1").bind(id).fetch_one(&state.db).await?;
let (model, prompt_version) = model_and_version(&state, row.analysis_id, &language).await?;
let language: String = sqlx::query_scalar("SELECT language FROM questions WHERE id = $1")
.bind(id)
.fetch_optional(&state.db)
.await?
.ok_or(ApiError::NotFound("question"))?;
let (model, fallback, prompt_version) = model_and_version(&state, &language).await?;
let mut tx = state.db.begin().await?;
let row: QuestionRow = sqlx::query_as(&format!(
"UPDATE questions SET status = 'pending', answer = NULL, error = NULL, model_used = NULL, input_tokens = NULL, \
output_tokens = NULL, cost_usd = NULL, attempts = 0, next_attempt_at = now(), started_at = NULL, \
completed_at = NULL, model = $2, prompt_version = $3 \
completed_at = NULL, model = $2, prompt_version = $3, fallback_model = $4, on_fallback = false, \
requested_at = now() \
WHERE id = $1 AND status IN ('done', 'failed') RETURNING {QUESTION_COLUMNS}"
))
.bind(id)
.bind(&model)
.bind(&prompt_version)
.bind(&fallback)
.fetch_optional(&mut *tx)
.await?
.ok_or_else(|| ApiError::conflict("question_in_progress", "Erre a kérdésre éppen készül a válasz."))?;
+44
View File
@@ -1,6 +1,9 @@
//! Public sharing links. Creating and revoking a link needs login; opening
//! one (`GET /v1/public/shares/{slug}`) does not. The public view never
//! contains birth data unless the owner allowed it for their own chart.
//! A shared chart comes with its newest short summary (the share page and
//! its preview image show both). Sharing the same thing again returns the
//! link that is already open.
use axum::Json;
use axum::extract::{Path, State};
@@ -109,6 +112,24 @@ pub async fn create(
}
};
let title = req.title.map(|t| t.trim().chars().take(120).collect::<String>()).filter(|t| !t.is_empty());
let open: Option<ShareRow> = sqlx::query_as(&format!(
"SELECT {SHARE_COLUMNS} FROM shares WHERE owner_id = $1 AND kind = $2 AND revoked_at IS NULL \
AND chart_id IS NOT DISTINCT FROM $3 AND synastry_id IS NOT DISTINCT FROM $4 \
AND analysis_id IS NOT DISTINCT FROM $5 AND title IS NOT DISTINCT FROM $6 AND show_birth_data = $7 \
ORDER BY created_at DESC LIMIT 1"
))
.bind(auth.id())
.bind(kind)
.bind(chart_id)
.bind(synastry_id)
.bind(analysis_id)
.bind(&title)
.bind(req.show_birth_data)
.fetch_optional(&state.db)
.await?;
if let Some(row) = open {
return Ok((StatusCode::OK, Json(row.view(&state.config.public_base_url))));
}
let row: ShareRow = sqlx::query_as(&format!(
"INSERT INTO shares (id, owner_id, slug, kind, chart_id, synastry_id, analysis_id, title, show_birth_data) \
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING {SHARE_COLUMNS}"
@@ -175,6 +196,7 @@ async fn public_body(db: &PgPool, share: &ShareRow) -> Result<Value, ApiError> {
if let Some(chart_id) = share.chart_id {
let chart = find_chart(db, chart_id).await?.ok_or(ApiError::NotFound("share"))?;
body["chart"] = public_chart_block(&chart, share);
body["summary"] = latest_summary(db, chart_id).await?;
} else if let Some(synastry_id) = share.synastry_id {
let s = load_synastry(db, synastry_id).await?.ok_or(ApiError::NotFound("share"))?;
body["synastry"] = public_synastry_block(&s, share);
@@ -198,6 +220,28 @@ async fn public_body(db: &PgPool, share: &ShareRow) -> Result<Value, ApiError> {
Ok(body)
}
/// The newest finished short summary of a chart (`null` if none).
async fn latest_summary(db: &PgPool, chart_id: Uuid) -> Result<Value, sqlx::Error> {
type Row = (Uuid, String, Option<Value>, Option<OffsetDateTime>);
let row: Option<Row> = sqlx::query_as(
"SELECT id, language, content, completed_at FROM analyses \
WHERE chart_id = $1 AND kind = 'summary' AND status = 'done' ORDER BY completed_at DESC LIMIT 1",
)
.bind(chart_id)
.fetch_optional(db)
.await?;
Ok(match row {
Some((id, language, content, completed_at)) => json!({
"id": id,
"language": language,
"title": content.as_ref().and_then(|c| c["title"].as_str()),
"summary": content.as_ref().and_then(|c| c["summary"].as_str()),
"completed_at": rfc3339_opt(completed_at),
}),
None => Value::Null,
})
}
/// Public: the shared content for the share page and its OG image.
pub async fn public_view(State(state): St, Path(slug): Path<String>) -> ApiResult<Json<Value>> {
let share: ShareRow = sqlx::query_as(&format!(
+151 -16
View File
@@ -628,6 +628,30 @@ async fn public_shares(pool: PgPool) {
for hidden in ["input", "location", "time", "astronomy", "birth"] {
assert!(shown.get(hidden).is_none(), "{hidden} must not be public");
}
assert!(r.body["summary"].is_null(), "no finished summary yet");
// the newest finished summary comes with the chart
sqlx::query(
"INSERT INTO analyses (id, kind, chart_id, requested_by, language, model, prompt_version, cache_key, \
credits_charged, status, content, completed_at) \
VALUES ($1, 'summary', $2::uuid, (SELECT id FROM users WHERE email = 'anna@example.com'), 'hu', 'm', 'v', \
'k', 0, 'done', $3, now())",
)
.bind(uuid::Uuid::now_v7())
.bind(chart_id)
.bind(json!({"title": "Csendes erő", "summary": "Rövid **összefoglaló**."}))
.execute(&app.pool)
.await
.unwrap();
let r = app.get(&format!("/v1/public/shares/{slug}"), None).await;
assert_eq!(r.body["summary"]["title"], "Csendes erő");
assert_eq!(r.body["summary"]["summary"], "Rövid **összefoglaló**.");
// sharing the same again gives the open link
let r = app
.post("/v1/shares", Some(&anna), json!({"kind": "chart", "target_id": chart_id, "title": "A radixom"}))
.await;
assert_eq!((r.status, r.body["slug"].as_str()), (StatusCode::OK, Some(slug.as_str())));
let r = app
.post("/v1/shares", Some(&anna), json!({"kind": "chart", "target_id": chart_id, "show_birth_data": true}))
@@ -761,6 +785,18 @@ async fn synastry_analyses_use_synastry_units(pool: PgPool) {
app.get("/v1/credits", Some(&anna)).await.body["balance"],
json!({"natal": 1, "synastry": 0, "forecast": 0, "question": 0})
);
// questions can be asked about the relationship analysis too
let analysis = r.body["id"].as_str().unwrap().to_string();
sqlx::query("UPDATE analyses SET status = 'done', content = '{\"title\": \"Kettőtök\"}' WHERE kind = 'synastry'")
.execute(&app.pool)
.await
.unwrap();
grant_units(&app, &anna, "question", 1).await;
let r = app
.post(&format!("/v1/analyses/{analysis}/questions"), Some(&anna), json!({"question": "Mire figyeljünk?"}))
.await;
assert_eq!((r.status, r.body["status"].as_str()), (StatusCode::ACCEPTED, Some("pending")), "{}", r.body);
}
#[sqlx::test(migrator = "db::MIGRATOR")]
@@ -1499,9 +1535,8 @@ async fn admins_choose_the_model_of_each_function(pool: PgPool) {
models,
[
("summary", "anthropic/claude-summary", false),
("natal", "anthropic/claude-test", false),
("synastry", "anthropic/claude-test", false),
("forecast", "anthropic/claude-test", false),
("analysis", "anthropic/claude-test", false),
("question", "anthropic/claude-test", false),
]
);
@@ -1516,9 +1551,9 @@ async fn admins_choose_the_model_of_each_function(pool: PgPool) {
let (app, admin) = (&app, &admin);
async move { app.call("PUT", &uri, Some(admin), Some(json!({ "model": model }))).await }
};
assert_eq!(put("natal", json!("vendor/plain")).await.status, StatusCode::BAD_REQUEST);
assert_eq!(put("composite", json!("openai/gpt-x")).await.status, StatusCode::NOT_FOUND);
let r = put("natal", json!("openai/gpt-x")).await;
assert_eq!(put("analysis", json!("vendor/plain")).await.status, StatusCode::BAD_REQUEST);
assert_eq!(put("natal", json!("openai/gpt-x")).await.status, StatusCode::NOT_FOUND);
let r = put("analysis", json!("openai/gpt-x")).await;
assert_eq!((r.status, &r.body["model"], &r.body["custom"]), (StatusCode::OK, &json!("openai/gpt-x"), &json!(true)));
// new analyses use it; regenerating writes it again in place with the current model
@@ -1527,9 +1562,13 @@ async fn admins_choose_the_model_of_each_function(pool: PgPool) {
let r = app.post(&format!("/v1/charts/{chart_id}/analyses"), Some(&admin), json!({})).await;
assert_eq!(r.status, StatusCode::ACCEPTED, "{}", r.body);
let id = r.body["id"].as_str().unwrap().to_string();
let model =
|| sqlx::query_scalar::<_, String>("SELECT model FROM analyses WHERE id = $1::uuid").bind(&id).fetch_one(&pool);
assert_eq!(model().await.unwrap(), "openai/gpt-x");
let model = || {
sqlx::query_as::<_, (String, Option<String>)>("SELECT model, fallback_model FROM analyses WHERE id = $1::uuid")
.bind(&id)
.fetch_one(&pool)
};
// the default model is kept as the fallback
assert_eq!(model().await.unwrap(), ("openai/gpt-x".into(), Some("anthropic/claude-test".into())));
let regenerate_uri = format!("/v1/admin/analyses/{id}/regenerate");
let regenerate = || app.post(&regenerate_uri, Some(&admin), json!({}));
assert_eq!(regenerate().await.status, StatusCode::CONFLICT); // still being written
@@ -1537,7 +1576,7 @@ async fn admins_choose_the_model_of_each_function(pool: PgPool) {
.execute(&pool)
.await
.unwrap();
assert_eq!(put("natal", Value::Null).await.body["model"], "anthropic/claude-test");
assert_eq!(put("analysis", Value::Null).await.body["model"], "anthropic/claude-test");
assert_eq!(
app.post(&format!("/v1/admin/analyses/{id}/regenerate"), Some(&anna), json!({})).await.status,
StatusCode::FORBIDDEN
@@ -1548,7 +1587,7 @@ async fn admins_choose_the_model_of_each_function(pool: PgPool) {
(StatusCode::OK, Some("pending"), &Value::Null)
);
assert_eq!(r.body["id"].as_str(), Some(id.as_str()));
assert_eq!(model().await.unwrap(), "anthropic/claude-test");
assert_eq!(model().await.unwrap(), ("anthropic/claude-test".into(), None));
let r = app.get(&format!("/v1/charts/{chart_id}/analyses"), Some(&admin)).await;
assert_eq!(r.body["analyses"].as_array().unwrap().iter().filter(|a| a["kind"] == "natal").count(), 1);
}
@@ -1587,15 +1626,14 @@ async fn questions_about_an_analysis_use_question_units(pool: PgPool) {
assert!(r.body.get("model").is_none(), "the model is a secret");
assert_eq!(left().await, json!(2));
let question = r.body["id"].as_str().unwrap().to_string();
// the same model as the analysis answers
let (q_model, a_model): (String, String) = sqlx::query_as(
"SELECT q.model, a.model FROM questions q JOIN analyses a ON a.id = q.analysis_id WHERE q.id = $1::uuid",
)
// the question model of the admin page answers (here the default)
let (q_model, fallback): (String, Option<String>) =
sqlx::query_as("SELECT model, fallback_model FROM questions WHERE id = $1::uuid")
.bind(&question)
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(q_model, a_model);
assert_eq!((q_model.as_str(), fallback), ("anthropic/claude-test", None));
// one at a time
let r = ask(&anna, "És a munkában?").await;
assert_eq!((r.status, r.body["error"]["code"].as_str()), (StatusCode::CONFLICT, Some("question_in_progress")));
@@ -1637,3 +1675,100 @@ async fn questions_about_an_analysis_use_question_units(pool: PgPool) {
);
assert_eq!(left().await, json!(5), "regenerating charges nobody");
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn admins_restart_open_generations_with_the_current_models(pool: PgPool) {
let app = TestApp::new(pool.clone()).await;
let admin = app.register("admin@example.com", "Admin").await;
let anna = app.register("anna@example.com", "Anna").await;
assert_eq!(app.get("/v1/admin/jobs", Some(&anna)).await.status, StatusCode::FORBIDDEN);
let put = |model: &str| {
let (app, admin, body) = (&app, &admin, json!({ "model": model }));
async move { app.call("PUT", "/v1/admin/models/analysis", Some(admin), Some(body)).await }
};
assert_eq!(put("openai/gpt-x").await.status, StatusCode::OK);
let chart = app.chart(&admin, "Saját", true, "1990-03-15").await;
let chart_id = chart["id"].as_str().unwrap();
let r = app.post(&format!("/v1/charts/{chart_id}/analyses"), Some(&admin), json!({})).await;
let id = r.body["id"].as_str().unwrap().to_string();
// the worker is writing it with the chosen model
sqlx::query("UPDATE analyses SET status = 'running', started_at = now(), attempts = 1 WHERE id = $1::uuid")
.bind(&id)
.execute(&pool)
.await
.unwrap();
// after switching back to the default, the list shows what a restart would use
assert_eq!(
app.call("PUT", "/v1/admin/models/analysis", Some(&admin), Some(json!({"model": null}))).await.status,
StatusCode::OK
);
let jobs = app.get("/v1/admin/jobs", Some(&admin)).await.body["jobs"].clone();
let job = jobs.as_array().unwrap().iter().find(|j| j["id"] == json!(id)).expect("the analysis is listed");
assert_eq!(
(&job["status"], &job["model"], &job["next_model"]),
(&json!("running"), &json!("openai/gpt-x"), &json!("anthropic/claude-test"))
);
let r = app.post("/v1/admin/jobs/restart", Some(&admin), json!({ "ids": [id] })).await;
assert_eq!((r.status, &r.body["restarted"]), (StatusCode::OK, &json!(1)), "{}", r.body);
let (status, model, fallback, started, attempts): (
String,
String,
Option<String>,
Option<time::OffsetDateTime>,
i32,
) = sqlx::query_as("SELECT status, model, fallback_model, started_at, attempts FROM analyses WHERE id = $1::uuid")
.bind(&id)
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(
(status.as_str(), model.as_str(), fallback, started, attempts),
("pending", "anthropic/claude-test", None, None, 0)
);
// finished ones are left alone
sqlx::query("UPDATE analyses SET status = 'done', content = '{}'").execute(&pool).await.unwrap();
assert_eq!(app.post("/v1/admin/jobs/restart", Some(&admin), json!({})).await.body["restarted"], 0);
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn admins_read_the_error_log(pool: PgPool) {
let app = TestApp::new(pool.clone()).await;
let admin = app.register("admin@example.com", "Admin").await;
let anna = app.register("anna@example.com", "Anna").await;
let chart = app.chart(&anna, "Saját", true, "1990-03-15").await;
let chart_id = chart["id"].as_str().unwrap();
let analysis: uuid::Uuid = sqlx::query_scalar("SELECT id FROM analyses WHERE chart_id = $1::uuid")
.bind(chart_id)
.fetch_one(&pool)
.await
.unwrap();
for (attempt, outcome) in [(1, "retry"), (2, "failed")] {
sqlx::query(
"INSERT INTO generation_errors (source, item_id, kind, model, attempt, outcome, error, seconds) \
VALUES ('analysis', $1, 'summary', 'cheap/model', $2, $3, 'answer cut off at the token limit', 301)",
)
.bind(analysis)
.bind(attempt)
.bind(outcome)
.execute(&pool)
.await
.unwrap();
}
assert_eq!(app.get("/v1/admin/errors", Some(&anna)).await.status, StatusCode::FORBIDDEN);
let r = app.get("/v1/admin/errors", Some(&admin)).await;
assert_eq!((r.status, &r.body["total"], &r.body["last_day"]), (StatusCode::OK, &json!(2), &json!(2)), "{}", r.body);
let first = &r.body["errors"][0];
assert_eq!(
(&first["outcome"], &first["attempt"], &first["user"], &first["seconds"]),
(&json!("failed"), &json!(2), &json!("anna@example.com"), &json!(301))
);
let r = app.get("/v1/admin/errors?outcome=retry", Some(&admin)).await;
assert_eq!(r.body["errors"].as_array().unwrap().len(), 1);
assert_eq!(app.get("/v1/admin/errors?source=question", Some(&admin)).await.body["total"], 0);
// users see the attempts of their analysis (the page says it is tried again)
let r = app.get(&format!("/v1/analyses/{analysis}"), Some(&anna)).await;
assert_eq!(r.body["attempts"], 0);
assert!(r.body["next_attempt_at"].is_string());
}
+9
View File
@@ -0,0 +1,9 @@
<!-- BEGIN:nextjs-agent-rules -->
## This is NOT the Next.js you know
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices.
This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.
<!-- END:nextjs-agent-rules -->
+2
View File
@@ -4,6 +4,8 @@ const config: NextConfig = {
// Small self-contained server for the container image.
output: "standalone",
poweredByHeader: false,
// The fonts of the share preview images are read from disk at run time.
outputFileTracingIncludes: { "/s/[slug]/kep/[file]": ["./src/assets/og/*.ttf"] },
};
export default config;
@@ -37,6 +37,7 @@ export default async function PrivacyPage() {
<section>
<h2>2. Milyen adatokat kezelünk, és miért?</h2>
<div className="table-wrap">
<table className="legal-table">
<thead>
<tr>
@@ -98,6 +99,7 @@ export default async function PrivacyPage() {
</tr>
</tbody>
</table>
</div>
<p>
Bankkártyaadatot nem kezelünk és nem tárolunk; a fizetést, amikor elindul, külső fizetési szolgáltató
végzi, akinek a neve itt lesz feltüntetve.
@@ -0,0 +1,155 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { api, errorText } from "@/lib/api";
import { formatDate } from "@/lib/astro";
import type { GenerationError } from "@/lib/types";
const PAGE = 100;
const SOURCES: Record<string, string> = { analysis: "Elemzés", question: "Kérdés-válasz", preview: "Prompt-próba" };
const KINDS: Record<string, string> = {
summary: "összefoglaló",
natal: "képletelemzés",
synastry: "kapcsolati",
forecast: "előrejelzés",
question: "válasz",
};
const OUTCOMES: Record<GenerationError["outcome"], { label: string; tone: string }> = {
retry: { label: "újrapróbálva", tone: "neutral" },
fallback: { label: "tartalék modell vette át", tone: "neutral" },
failed: { label: "végleg sikertelen", tone: "tense" },
};
interface Page {
errors: GenerationError[];
total: number;
last_day: number;
}
/** The admin error log with filters and paging. */
export function ErrorLog() {
const [source, setSource] = useState("");
const [outcome, setOutcome] = useState("");
const [errors, setErrors] = useState<GenerationError[] | null>(null);
const [total, setTotal] = useState(0);
const [lastDay, setLastDay] = useState(0);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const load = useCallback(
async (offset: number) => {
setBusy(true);
setError(null);
const params = new URLSearchParams({ limit: String(PAGE), offset: String(offset) });
if (source) params.set("source", source);
if (outcome) params.set("outcome", outcome);
try {
const page = await api<Page>(`/admin/errors?${params}`);
setErrors((all) => (offset === 0 ? page.errors : [...(all ?? []), ...page.errors]));
setTotal(page.total);
setLastDay(page.last_day);
} catch (e) {
setError(errorText(e));
} finally {
setBusy(false);
}
},
[source, outcome],
);
useEffect(() => {
load(0);
}, [load]);
return (
<section className="card" style={{ gap: 12 }}>
<div className="row" style={{ gap: 12, flexWrap: "wrap", alignItems: "flex-end" }}>
<div className="field">
<label htmlFor="error-source">Mi</label>
<select id="error-source" className="inp" value={source} onChange={(e) => setSource(e.target.value)}>
<option value="">mind</option>
{Object.entries(SOURCES).map(([v, l]) => (
<option key={v} value={v}>
{l}
</option>
))}
</select>
</div>
<div className="field">
<label htmlFor="error-outcome">Következmény</label>
<select id="error-outcome" className="inp" value={outcome} onChange={(e) => setOutcome(e.target.value)}>
<option value="">mind</option>
{Object.entries(OUTCOMES).map(([v, o]) => (
<option key={v} value={v}>
{o.label}
</option>
))}
</select>
</div>
<p className="hint" style={{ margin: 0 }}>
{total} bejegyzés, ebből {lastDay} az elmúlt 24 órában
</p>
<button type="button" className="btn btn-sm btn-ghost" onClick={() => load(0)} disabled={busy}>
Frissítés
</button>
</div>
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
{errors === null ? (
<p className="muted">Betöltés…</p>
) : errors.length === 0 ? (
<p className="muted">Nincs hiba. 🎉</p>
) : (
<div className="table-wrap">
<table className="error-log">
<thead>
<tr>
<th>Időpont</th>
<th>Mi</th>
<th>Modell</th>
<th>Kísérlet</th>
<th>Következmény</th>
<th>Hiba</th>
</tr>
</thead>
<tbody>
{errors.map((e) => (
<tr key={e.id}>
<td className="num">{formatDate(e.created_at, true)}</td>
<td>
{SOURCES[e.source] ?? e.source}
{e.source !== "question" && ` (${KINDS[e.kind] ?? e.kind})`}
{e.user && <span className="hint">{e.user}</span>}
<code className="hint" title={e.item_id}>
{e.item_id.slice(0, 8)}
</code>
</td>
<td>
<code>{e.model}</code>
</td>
<td className="num">
{e.attempt}.{e.seconds !== null && <span className="hint">{e.seconds} mp</span>}
</td>
<td>
<span className={`outcome tone-${OUTCOMES[e.outcome].tone}`}>{OUTCOMES[e.outcome].label}</span>
</td>
<td className="error-text">{e.error}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
{errors && errors.length < total && (
<button type="button" className="btn btn-sm" onClick={() => load(errors.length)} disabled={busy}>
{busy ? "Betöltés…" : "Régebbiek"}
</button>
)}
</section>
);
}
@@ -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 (
<main className="page" style={{ maxWidth: 1180 }}>
<AdminNav current="/admin/hibak" />
<div className="page-head">
<h1>Hibanapló</h1>
<p className="muted">
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.
</p>
</div>
<ErrorLog />
</main>
);
}
@@ -4,13 +4,17 @@ import { useEffect, useMemo, useState } from "react";
import { api, errorText } from "@/lib/api";
import { formatDate } from "@/lib/astro";
import type { CatalogModel, ModelFunction, PromptKind } from "@/lib/types";
import type { CatalogModel, ModelFunction } from "@/lib/types";
const LABELS: Record<Exclude<PromptKind, "question">, { title: string; about: string }> = {
import { RunningJobs } from "./RunningJobs";
const LABELS: Record<ModelFunction["kind"], { title: string; about: string }> = {
summary: { title: "Tömör összefoglaló", about: "Ingyenes, minden új képlethez magától elkészül. Olcsó, gyors modell elég." },
natal: { title: "Részletes képletelemzés", about: "Fizetős, hat fejezet." },
synastry: { title: "Kapcsolati elemzés", about: "Fizetős, öt fejezet két képletről." },
forecast: { title: "Éves előrejelzés", about: "Fizetős, öt fejezet, a leghosszabb adatsorral." },
analysis: {
title: "Elemzések és éves előrejelzés",
about: "Fizetős szövegek: részletes képletelemzés, kapcsolati elemzés és éves előrejelzés.",
},
question: { title: "Kérdés-válasz", about: "A kész elemzésekre és előrejelzésekre feltett kérdések válasza (legfeljebb 250 szó)." },
};
/** How many models the picker lists at once (narrow it with the search). */
@@ -58,11 +62,13 @@ export function AdminModels() {
</p>
)}
<p className="hint">
Az elemzésekre feltett kérdésekre mindig ugyanaz a modell válaszol, amelyik az adott elemzést írta.
Tartalék: ha a választott modell kétszer hibára fut (vagy egyszer végleges hibával), az alapértelmezett modell írja
meg a szöveget. Csak ha az is elbukik, kapja vissza a felhasználó az egységét.
</p>
{functions.map((f) => (
<FunctionModel key={f.kind} fn={f} catalog={catalog} onSaved={replace} />
))}
<RunningJobs />
</div>
);
}
@@ -82,7 +88,7 @@ function FunctionModel({
const [error, setError] = useState<string | null>(null);
const current = catalog?.find((m) => m.id === fn.model);
const cost = estimate(fn, current);
const label = LABELS[fn.kind as keyof typeof LABELS];
const label = LABELS[fn.kind];
const searchId = `model-search-${fn.kind}`;
const matches = useMemo(() => {
@@ -134,6 +140,11 @@ function FunctionModel({
? `Módosítva: ${fn.updated_at ? formatDate(fn.updated_at, true) : ""}${fn.updated_by ? `, ${fn.updated_by}` : ""}`
: "Alapértelmezett"}
</span>
{fn.custom && (
<span className={fn.fallbacks_30d > 0 ? "hint warn" : "hint"}>
Tartalék: {fn.default} · az elmúlt 30 napban {fn.fallbacks_30d} / {fn.finished_30d} szövegnél kellett
</span>
)}
</div>
</div>
<div className="form-actions">
@@ -0,0 +1,138 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { api, errorText } from "@/lib/api";
import type { AdminJob } from "@/lib/types";
const KINDS: Record<AdminJob["kind"], string> = {
summary: "Összefoglaló",
natal: "Képletelemzés",
synastry: "Kapcsolati elemzés",
forecast: "Éves előrejelzés",
question: "Kérdés-válasz",
};
const REFRESH_MS = 10_000;
function since(iso: string): string {
const minutes = Math.max(0, Math.round((Date.now() - new Date(iso).getTime()) / 60_000));
return minutes < 1 ? "most" : `${minutes} perce`;
}
/**
* Analyses and answers being written or waiting. A restart starts them again
* with the models set now; an attempt still running is dropped by the worker.
*/
export function RunningJobs() {
const [jobs, setJobs] = useState<AdminJob[] | null>(null);
const [busy, setBusy] = useState(false);
const [asking, setAsking] = useState(false);
const [message, setMessage] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const load = useCallback(() => {
api<{ jobs: AdminJob[] }>("/admin/jobs")
.then((d) => setJobs(d.jobs))
.catch((e) => setError(errorText(e)));
}, []);
useEffect(() => {
load();
const timer = setInterval(load, REFRESH_MS);
return () => clearInterval(timer);
}, [load]);
async function restart(ids?: string[]) {
setBusy(true);
setError(null);
setMessage(null);
try {
const r = await api<{ restarted: number; jobs: AdminJob[] }>("/admin/jobs/restart", { body: ids ? { ids } : {} });
setJobs(r.jobs);
setMessage(r.restarted > 0 ? `${r.restarted} generálás újraindítva.` : "Nem volt mit újraindítani.");
setAsking(false);
} catch (e) {
setError(errorText(e));
} finally {
setBusy(false);
}
}
const changed = (jobs ?? []).filter((j) => j.model !== j.next_model).length;
return (
<section className="card model-card" aria-labelledby="jobs-title">
<div className="model-head">
<div>
<h2 id="jobs-title">Futó generálások</h2>
<p className="hint">
Az éppen készülő és a sorban álló elemzések és válaszok. Újraindításkor mindegyik azzal a modellel indul újra,
ami most be van állítva; a még futó régi kérést a worker eldobja. Senkitől nem von le újabb egységet.
</p>
</div>
{jobs && jobs.length > 0 && (
<div className="regenerate">
{asking ? (
<>
<span className="hint">
{jobs.length} generálás indul újra{changed > 0 ? `, ebből ${changed} másik modellel` : ""}.
</span>
<button type="button" className="btn btn-sm" onClick={() => restart()} disabled={busy}>
{busy ? "Újraindítás…" : "Igen, mind"}
</button>
<button type="button" className="btn btn-sm btn-ghost" onClick={() => setAsking(false)} disabled={busy}>
Mégse
</button>
</>
) : (
<button type="button" className="btn btn-sm" onClick={() => setAsking(true)}>
↻ Mind újraindítása ({jobs.length})
</button>
)}
</div>
)}
</div>
{message && (
<p className="msg" role="status">
{message}
</p>
)}
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
{jobs === null ? (
<p className="muted">Betöltés…</p>
) : jobs.length === 0 ? (
<p className="muted">Most semmi nem készül és semmi nem vár a sorban.</p>
) : (
<ul className="model-options">
{jobs.map((j) => (
<li key={j.id} className="job-row">
<span>
<strong>{KINDS[j.kind]}</strong>
<span className="hint">
{j.status === "running" && j.started_at
? `fut, ${since(j.started_at)} indult`
: `vár (kérve ${since(j.created_at)})`}
{j.attempts > 0 ? ` · ${j.attempts}. kísérlet` : ""}
{j.on_fallback ? " · tartalék modellel" : ""}
</span>
{j.error && <span className="hint">utolsó hiba: {j.error}</span>}
</span>
<span className="model-price">
<code>{j.model}</code>
{j.model !== j.next_model ? <strong>→ {j.next_model}</strong> : <span>újraindítva is ez</span>}
</span>
<button type="button" className="btn btn-sm btn-ghost" onClick={() => restart([j.id])} disabled={busy}>
↻
<span className="sr-only"> Újraindítás</span>
</button>
</li>
))}
</ul>
)}
</section>
);
}
@@ -40,7 +40,7 @@ const KINDS: { kind: PromptKind; id: string; label: string; about: string }[] =
id: "kerdesek",
label: "Kérdés-válasz",
about:
"A kész képletelemzésre vagy előrejelzésre feltett kérdések válasza (legfeljebb 250 szó). A modell kapja a képlet adatait, az elemzést és a korábbi kérdéseket; ugyanaz a modell válaszol, amelyik az elemzést írta.",
"A kész képletelemzésre, kapcsolati elemzésre vagy előrejelzésre feltett kérdések válasza (legfeljebb 250 szó). A modell kapja a képlet adatait, az elemzést és a korábbi kérdéseket; a Modellek oldalon beállított kérdés-válasz modell válaszol.",
},
];
+1 -1
View File
@@ -22,7 +22,7 @@ const FAQ: [string, string][] = [
],
[
"Mit jelent a kérdés?",
"A kész részletes képletelemzésed vagy éves előrejelzésed alatt kérdezhetsz róla, például hogy mit jelent egy fényszög a munkádra nézve, vagy mire figyelj egy időszakban. A választ ugyanaz a modell írja, amelyik az elemzést, a képleted és az elemzés alapján, legfeljebb 250 szóban. Minden csomagban 3 kérdés van, és külön is vehetsz még.",
"A kész képletelemzésed, kapcsolati elemzésed vagy éves előrejelzésed alatt kérdezhetsz róla, például hogy mit jelent egy fényszög a munkádra nézve, mire figyeljetek egy kapcsolatban, vagy mire figyelj egy időszakban. A válasz a képleted és az elemzés alapján készül, legfeljebb 250 szóban. Minden csomagban 3 kérdés van, és külön is vehetsz még.",
],
[
"Mire kell a személyhely?",
+81 -18
View File
@@ -28,6 +28,8 @@
html, body { margin: 0; }
body {
min-height: 100vh;
overflow-x: clip; /* nothing may push the page sideways on a phone */
overflow-wrap: break-word;
background: var(--bg);
color: var(--ink);
font: 400 15px/1.55 var(--font-body);
@@ -71,8 +73,8 @@ p { margin: 0; }
.page-head { display: flex; flex-direction: column; gap: 6px; }
.card { background: var(--panel); border: 1px solid var(--line); border-radius: 14px; padding: 24px; display: flex; flex-direction: column; gap: 18px; }
.card-head { display: flex; justify-content: space-between; align-items: baseline; gap: 12px; flex-wrap: wrap; }
.grid-2 { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 16px; }
.facts { display: grid; grid-template-columns: max-content 1fr; gap: 8px 20px; margin: 0; }
.grid-2 { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(240px, 100%), 1fr)); gap: 16px; }
.facts { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 8px 20px; margin: 0; }
.facts dt { color: var(--muted); }
.facts dd { margin: 0; }
@@ -81,11 +83,11 @@ p { margin: 0; }
.field label, .label { font-size: 14px; font-weight: 500; }
.hint { font-size: 13px; color: var(--muted); }
.inp {
width: 100%; min-height: 48px; padding: 0 14px; border-radius: var(--radius);
width: 100%; min-width: 0; max-width: 100%; min-height: 48px; padding: 0 14px; border-radius: var(--radius);
border: 1px solid var(--line-2); background: var(--panel-2); color: var(--ink);
font: 400 15px var(--font-body);
}
select.inp { padding-right: 32px; }
select.inp { padding-right: 32px; text-overflow: ellipsis; }
.inp::placeholder { color: #8a93ab; }
.inp:focus { outline: none; border-color: var(--gold); box-shadow: 0 0 0 3px rgba(217, 180, 106, 0.25); }
.inp:disabled { opacity: 0.55; }
@@ -190,7 +192,7 @@ td.num { font-variant-numeric: tabular-nums; white-space: nowrap; }
.analysis-section h3 { font-size: 24px; color: var(--gold); }
.analysis-section p, .analysis-lists li { font-size: 16px; line-height: 1.75; color: var(--ink-2); }
.analysis strong { color: var(--ink); font-weight: 600; }
.analysis-lists { display: grid; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); gap: 24px; }
.analysis-lists { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(260px, 100%), 1fr)); gap: 24px; }
.analysis-lists h3 { font-size: 22px; margin-bottom: 8px; }
.analysis-lists ul { margin: 0; padding-left: 20px; display: flex; flex-direction: column; gap: 8px; }
.analysis-advice { border-top: 1px solid var(--line); padding-top: 24px; }
@@ -308,7 +310,7 @@ td.num { font-variant-numeric: tabular-nums; white-space: nowrap; }
.w-point:hover .w-point-glyph { fill: var(--gold); }
@media (max-width: 900px) {
.chart-layout { grid-template-columns: 1fr; }
.chart-layout { grid-template-columns: minmax(0, 1fr); }
}
@media (max-width: 640px) {
@@ -342,7 +344,7 @@ td.num { font-variant-numeric: tabular-nums; white-space: nowrap; }
@media (max-width: 640px) { .tab { padding: 12px 10px; font-size: 14px; } .tabs { scroll-margin-top: 120px; } }
/* Charts list, persons */
.chart-cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 16px; }
.chart-cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(240px, 100%), 1fr)); gap: 16px; }
.chart-card {
background: var(--panel); border: 1px solid var(--line); border-radius: 14px; display: flex; flex-direction: column;
transition: border-color 0.15s;
@@ -485,14 +487,14 @@ td.num { font-variant-numeric: tabular-nums; white-space: nowrap; }
.nature-challenging { background: var(--tense); }
.nature-neutral { background: var(--gold); }
.nature-list { margin: 0; display: flex; flex-direction: column; gap: 8px; }
.nature-list > div { display: grid; grid-template-columns: 128px 1fr; gap: 8px; align-items: baseline; }
.nature-list > div { display: grid; grid-template-columns: 128px minmax(0, 1fr); gap: 8px; align-items: baseline; }
.nature-list dt { display: inline-flex; align-items: center; gap: 8px; font-size: 14px; color: var(--ink-2); }
.nature-list dd { margin: 0; }
.nature-dot { width: 10px; height: 10px; border-radius: 50%; display: inline-block; }
.pair-card { gap: 4px; }
.pair-row {
display: grid; grid-template-columns: auto 1fr auto; gap: 12px; align-items: center; padding: 10px 0;
display: grid; grid-template-columns: auto minmax(0, 1fr) auto; gap: 12px; align-items: center; padding: 10px 0;
color: inherit; text-decoration: none; border-bottom: 1px solid var(--line);
}
.pair-row:last-child { border-bottom: 0; padding-bottom: 0; }
@@ -501,7 +503,7 @@ a.pair-row:hover strong { color: var(--gold); }
.pair-text strong { font-family: var(--font-display); font-size: 21px; font-weight: 600; }
.compare-new { gap: 16px; }
.compare-form { display: grid; grid-template-columns: 1fr auto 1fr auto; gap: 12px; align-items: end; }
.compare-form { display: grid; grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr) auto; gap: 12px; align-items: end; }
.compare-swap { font-size: 20px; padding: 0 10px; }
.compare-tile { gap: 6px; padding: 16px 20px; }
.compare-tile strong { font-family: var(--font-display); font-size: 21px; font-weight: 600; }
@@ -509,12 +511,12 @@ a.pair-row:hover strong { color: var(--gold); }
.compare-tile .form-actions { margin-top: 6px; }
.back-link { font-size: 14px; text-decoration: none; align-self: flex-start; }
@media (max-width: 640px) {
.compare-form { grid-template-columns: 1fr auto; }
.compare-form { grid-template-columns: minmax(0, 1fr) auto; }
.compare-form .field:first-child { grid-column: 1; }
.compare-swap { grid-column: 2; grid-row: 1 / span 2; align-self: center; }
.compare-form .field:nth-child(3) { grid-column: 1; }
.compare-form > .btn-primary { grid-column: 1 / -1; width: 100%; }
.nature-list > div { grid-template-columns: 1fr; gap: 2px; }
.nature-list > div { grid-template-columns: minmax(0, 1fr); gap: 2px; }
.nav { overflow-x: auto; scrollbar-width: none; }
.nav a { white-space: nowrap; padding: 10px 9px; }
.cross-grid td.cross-corner { min-width: 56px; font-size: 9px; }
@@ -522,7 +524,7 @@ a.pair-row:hover strong { color: var(--gold); }
/* Packages */
.pkg-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 16px; align-items: stretch; }
.pkg-grid-compact { grid-template-columns: repeat(auto-fit, minmax(210px, 1fr)); gap: 12px; }
.pkg-grid-compact { grid-template-columns: repeat(auto-fit, minmax(min(210px, 100%), 1fr)); gap: 12px; }
.pkg {
position: relative; display: flex; flex-direction: column; gap: 10px; padding: 22px 20px 20px;
background: var(--panel); border: 1px solid var(--line-2); border-radius: var(--radius);
@@ -589,7 +591,7 @@ a.pair-row:hover strong { color: var(--gold); }
.timeline-month h3 { font-size: 20px; margin: 0 0 8px; text-transform: capitalize; }
.timeline-month ol, .transit-list { margin: 0; padding: 0; list-style: none; display: flex; flex-direction: column; gap: 6px; }
.timeline-item {
display: grid; grid-template-columns: 64px 56px 1fr; gap: 10px; align-items: baseline;
display: grid; grid-template-columns: 64px 56px minmax(0, 1fr); gap: 10px; align-items: baseline;
padding: 8px 12px; border-left: 3px solid var(--line); border-radius: 4px; background: rgba(255, 255, 255, 0.02);
}
.timeline-date { color: var(--muted); font-variant-numeric: tabular-nums; white-space: nowrap; }
@@ -599,15 +601,15 @@ a.pair-row:hover strong { color: var(--gold); }
.timeline-item.tone-harmonic, .transit-list .tone-harmonic { border-left-color: var(--harmonic); }
.timeline-item.tone-neutral, .transit-list .tone-neutral { border-left-color: var(--gold); }
.transit-list li {
display: grid; grid-template-columns: 72px 1fr; gap: 10px; align-items: baseline;
display: grid; grid-template-columns: 72px minmax(0, 1fr); gap: 10px; align-items: baseline;
padding: 8px 12px; border-left: 3px solid var(--line); border-radius: 4px;
}
.transit-list li > span:last-child { display: flex; flex-direction: column; gap: 2px; }
.transit-list li > span:last-child { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
.transit-list .sym { font-size: 17px; color: var(--gold); white-space: nowrap; }
.transit-list .pill { align-self: flex-start; font-size: 12px; padding: 1px 8px; border: 1px solid var(--gold); border-radius: 999px; color: var(--gold); }
.plain-list { margin: 8px 0 12px; padding-left: 18px; display: flex; flex-direction: column; gap: 4px; }
@media (max-width: 560px) {
.timeline-item { grid-template-columns: 52px 1fr; }
.timeline-item { grid-template-columns: 52px minmax(0, 1fr); }
.timeline-glyph { display: none; }
}
@@ -638,8 +640,69 @@ a.pair-row:hover strong { color: var(--gold); }
.questions { display: flex; flex-direction: column; gap: 14px; margin-top: 28px; padding-top: 22px; border-top: 1px solid var(--line); }
.questions h3 { margin: 0; }
.qa { display: flex; flex-direction: column; gap: 8px; padding: 14px 16px; border: 1px solid var(--line); border-radius: 12px; }
.qa-question { margin: 0; display: flex; flex-direction: column; gap: 2px; font-weight: 600; white-space: pre-wrap; }
.qa-question { margin: 0; display: flex; flex-direction: column; gap: 2px; font-weight: 600; white-space: pre-wrap; overflow-wrap: anywhere; }
.qa-answer { display: flex; flex-direction: column; gap: 6px; }
.qa-answer p { margin: 0 0 8px; }
.qa-form { display: flex; flex-direction: column; gap: 8px; }
.qa-form textarea { resize: vertical; min-height: 84px; }
.hint.warn { 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; }
/* Generated text (summaries, analyses, answers): justified, with hyphenation so
narrow screens get no wide gaps. The last line of a paragraph stays ragged. */
.analysis-lead, .analysis-section p, .analysis-lists li, .summary-text, .qa-answer p {
text-align: justify;
hyphens: auto;
-webkit-hyphens: auto;
hyphenate-limit-chars: 7 3 3;
}
/* Phones: tighter spacing, smaller headings, no sideways scrolling */
@media (max-width: 640px) {
.page { padding: 20px 14px 48px; gap: 18px; }
.card { padding: 16px; gap: 14px; }
h2 { font-size: 24px; }
.analysis { gap: 22px; }
.analysis-head h2 { font-size: 28px; }
.analysis-section h3 { font-size: 21px; }
.analysis-lists h3 { font-size: 20px; }
.analysis-lead { font-size: 16px; line-height: 1.65; }
.analysis-section p, .analysis-lists li, .summary-text { font-size: 15.5px; line-height: 1.7; }
.analysis-lists ul { padding-left: 18px; }
.summary-title { font-size: 23px; }
.questions { margin-top: 22px; padding-top: 18px; }
.qa { padding: 12px; }
.pay-box { padding: 16px; }
.loading-wheel { width: 96px; height: 96px; }
.tagline { font-size: 32px; }
}
@media (max-width: 480px) {
/* label above value: the label column would squeeze the values */
.facts { grid-template-columns: minmax(0, 1fr); gap: 2px; }
.facts dd + dt { margin-top: 8px; }
.site-header { gap: 8px 12px; }
.logo { font-size: 25px; }
}
/* Sharing a chart (summary card) and the public share page */
.share { display: flex; flex-direction: column; gap: 10px; align-items: flex-start; }
.share-open { align-items: stretch; padding: 14px; border: 1px solid var(--line-2); border-radius: var(--radius); background: var(--panel-2); }
.share-link { display: flex; gap: 8px; }
.share-link .inp { min-height: 36px; font-size: 14px; }
.share-trio { display: flex; flex-wrap: wrap; gap: 6px 18px; color: var(--ink-2); font-size: 14px; }
.share-trio .sym { color: var(--gold); }
.share-cta { gap: 12px; }
.share-cta h2 { font-size: 24px; }
.share-cta .btn { align-self: flex-start; }
@@ -129,6 +129,7 @@ export default async function ComparisonPage({ params }: { params: Promise<{ id:
isAdmin={me.user.roles.includes("admin")}
canPay={config?.mock_payments ?? false}
note={`Az elemzésben az első fél: ${name1}, a második fél: ${name2}.`}
questionsLeft={me.analyses_left.question ?? 0}
/>
),
},
@@ -0,0 +1,108 @@
// The link preview image of a shared chart (og:image): 1200×630 PNG with the
// wheel, the title and the text of the short summary. The file name carries
// a version (see `imageVersion`), so a rewritten summary gets a new address
// and Facebook and co. fetch it again.
import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { ImageResponse } from "next/og";
import { SIGNS, signName } from "@/lib/astro";
import { bigThree, loadShare, plain, shorten } from "@/lib/share";
import { wheelSvg } from "@/lib/wheelSvg";
const W = 1200;
const H = 630;
const WHEEL = 590;
const FONTS = join(process.cwd(), "src/assets/og");
let fonts: Promise<{ name: string; data: Buffer; weight: 400 | 600; style: "normal" }[]> | null = null;
function loadFonts() {
fonts ??= Promise.all(
(
[
["Cormorant Garamond", "CormorantGaramond-SemiBold.ttf", 600],
["Inter", "Inter-Regular.ttf", 400],
["Inter", "Inter-SemiBold.ttf", 600],
["DejaVu Sans", "DejaVuSans.ttf", 400],
] as const
).map(async ([name, file, weight]) => ({
name,
data: await readFile(join(FONTS, file)),
weight,
style: "normal" as const,
})),
);
return fonts;
}
// Letters, digits, punctuation and spaces only: a character missing from the
// fonts would make the renderer download a font from the internet.
const printable = (s: string) => s.replace(/[^\p{L}\p{N}\p{P}\p{Zs}+=<>°]/gu, "");
export async function GET(_req: Request, { params }: { params: Promise<{ slug: string; file: string }> }) {
const { slug } = await params;
const share = await loadShare(slug);
const chart = share?.chart?.chart;
if (!share || !chart) return new Response("Not found", { status: 404 });
const title = printable(share.summary?.title ?? "Születési képlet");
const text = printable(shorten(plain(share.summary?.summary ?? ""), 280));
const svg = wheelSvg(chart, chart.time_known, WHEEL);
const trio = bigThree(chart);
const image = new ImageResponse(
(
<div style={{ display: "flex", width: W, height: H, background: "#0d1220", color: "#ece6d8", fontFamily: "Inter" }}>
<div style={{ display: "flex", width: WHEEL + 40, height: H, alignItems: "center", justifyContent: "center" }}>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={`data:image/svg+xml;base64,${Buffer.from(svg).toString("base64")}`}
width={WHEEL}
height={WHEEL}
alt=""
/>
</div>
<div
style={{
display: "flex",
flexDirection: "column",
flex: 1,
padding: "56px 56px 44px 8px",
gap: 18,
}}
>
<div style={{ display: "flex", fontSize: 17, fontWeight: 600, letterSpacing: 2.5, color: "#d9b46a" }}>
SZÜLETÉSI KÉPLET · RÖVIDEN
</div>
<div style={{ display: "flex", fontFamily: "Cormorant Garamond", fontSize: 56, lineHeight: 1.05 }}>{title}</div>
{text && <div style={{ display: "flex", fontSize: 23, lineHeight: 1.45, color: "#c9cfdc" }}>{text}</div>}
<div style={{ display: "flex", marginTop: "auto", gap: 22, fontSize: 21, color: "#c9cfdc" }}>
{trio.map((t) => (
<div key={t.label} style={{ display: "flex", alignItems: "center", gap: 8 }}>
<span style={{ fontFamily: "DejaVu Sans", color: "#d9b46a" }}>
{(SIGNS[t.sign]?.glyph ?? "").replace(/︎/g, "")}
</span>
<span>
{t.label === "Aszcendens" ? "Asc" : t.label} {signName(t.sign)}
</span>
</div>
))}
</div>
<div style={{ display: "flex", fontFamily: "Cormorant Garamond", fontSize: 30, color: "#ece6d8" }}>
sors<span style={{ color: "#d9b46a" }}>fonalak</span>
</div>
</div>
</div>
),
{
width: W,
height: H,
fonts: await loadFonts(),
// A day at the edge: a revoked link's image goes away from there too.
headers: { "Cache-Control": "public, max-age=3600, s-maxage=86400" },
},
);
return image;
}
+112
View File
@@ -0,0 +1,112 @@
import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import { ChartWheel, WheelLegend } from "@/components/ChartWheel";
import { Rich } from "@/components/Rich";
import { Logo } from "@/components/SiteHeader";
import { SIGNS, signName } from "@/lib/astro";
import { getMe } from "@/lib/server";
import { bigThree, imageVersion, loadShare, plain, shorten, siteUrl } from "@/lib/share";
type Props = { params: Promise<{ slug: string }> };
/** Title, description and preview image for Facebook, Messenger, WhatsApp and co. */
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { slug } = await params;
const share = await loadShare(slug);
if (!share?.chart) return { title: "A link nem érhető el", robots: { index: false } };
const base = await siteUrl();
const title = share.summary?.title ?? "Születési képlet";
const description = share.summary?.summary
? shorten(plain(share.summary.summary), 200)
: "Egy születési képlet a Sorsfonalakon.";
const url = `${base}/s/${slug}`;
const image = { url: `${base}/s/${slug}/kep/${imageVersion(share)}.png`, width: 1200, height: 630, alt: title };
return {
title,
description,
// Personal content: shown when shared, not listed in search engines.
robots: { index: false, follow: false },
alternates: { canonical: url },
openGraph: { type: "website", siteName: "Sorsfonalak", locale: "hu_HU", url, title, description, images: [image] },
twitter: { card: "summary_large_image", title, description, images: [image.url] },
};
}
/** A shared chart: the wheel and its short summary, open to anyone with the link. */
export default async function SharedChartPage({ params }: Props) {
const { slug } = await params;
const [share, me] = await Promise.all([loadShare(slug), getMe()]);
const chart = share?.chart?.chart;
if (!share || !chart) notFound();
const summary = share.summary;
const trio = bigThree(chart);
return (
<>
{!me && (
<header className="site-header">
<Logo />
<span style={{ flex: 1 }} />
<Link href="/belepes" className="btn btn-sm">
Belépés
</Link>
</header>
)}
<main className="page" style={{ maxWidth: 1180 }}>
<div className="page-head">
<span className="eyebrow">Megosztott születési képlet</span>
<h1>{summary?.title ?? "Születési képlet"}</h1>
</div>
<section className="chart-layout" aria-label="A megosztott képlet">
<div className="card chart-wheel-card">
<ChartWheel chart={chart} timeKnown={chart.time_known} />
<WheelLegend />
</div>
<div className="field chart-side">
<section className="card summary-card" aria-label="Röviden">
<span className="eyebrow">Röviden</span>
{summary?.summary ? (
<p className="summary-text" lang={summary.language}>
<Rich text={summary.summary} />
</p>
) : (
<p className="muted">Ehhez a képlethez még nincs rövid összefoglaló.</p>
)}
{trio.length > 0 && (
<p className="share-trio">
{trio.map((t) => (
<span key={t.label}>
<span className="sym" aria-hidden="true">
{SIGNS[t.sign]?.glyph}
</span>{" "}
{t.label} {signName(t.sign)}
</span>
))}
</p>
)}
{!chart.time_known && (
<p className="hint">A születési idő nem ismert, ezért a képleten nincsenek házak és Aszcendens.</p>
)}
</section>
<section className="card share-cta">
<h2>És a te képleted mit mutat?</h2>
<p className="muted">
Add meg a születési adataidat, és megkapod a saját képletedet a rövid összefoglalóval együtt, ingyen.
</p>
<Link href={me ? "/keplet" : "/belepes"} className="btn btn-primary">
{me ? "A saját képletem" : "Elkészítem a sajátomat"}
</Link>
</section>
</div>
</section>
<p className="hint">
Ezt a képletet a tulajdonosa osztotta meg, név és születési adatok nélkül. A szöveget mesterséges intelligencia
írta a képlet alapján.
</p>
</main>
</>
);
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,187 @@
Fonts are (c) Bitstream (see below). DejaVu changes are in public domain.
Glyphs imported from Arev fonts are (c) Tavmjong Bah (see below)
Bitstream Vera Fonts Copyright
------------------------------
Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera is
a trademark of Bitstream, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of the fonts accompanying this license ("Fonts") and associated
documentation files (the "Font Software"), to reproduce and distribute the
Font Software, including without limitation the rights to use, copy, merge,
publish, distribute, and/or sell copies of the Font Software, and to permit
persons to whom the Font Software is furnished to do so, subject to the
following conditions:
The above copyright and trademark notices and this permission notice shall
be included in all copies of one or more of the Font Software typefaces.
The Font Software may be modified, altered, or added to, and in particular
the designs of glyphs or characters in the Fonts may be modified and
additional glyphs or characters may be added to the Fonts, only if the fonts
are renamed to names not containing either the words "Bitstream" or the word
"Vera".
This License becomes null and void to the extent applicable to Fonts or Font
Software that has been modified and is distributed under the "Bitstream
Vera" names.
The Font Software may be sold as part of a larger software package but no
copy of one or more of the Font Software typefaces may be sold by itself.
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT,
TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME
FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING
ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE
FONT SOFTWARE.
Except as contained in this notice, the names of Gnome, the Gnome
Foundation, and Bitstream Inc., shall not be used in advertising or
otherwise to promote the sale, use or other dealings in this Font Software
without prior written authorization from the Gnome Foundation or Bitstream
Inc., respectively. For further information, contact: fonts at gnome dot
org.
Arev Fonts Copyright
------------------------------
Copyright (c) 2006 by Tavmjong Bah. All Rights Reserved.
Permission is hereby granted, free of charge, to any person obtaining
a copy of the fonts accompanying this license ("Fonts") and
associated documentation files (the "Font Software"), to reproduce
and distribute the modifications to the Bitstream Vera Font Software,
including without limitation the rights to use, copy, merge, publish,
distribute, and/or sell copies of the Font Software, and to permit
persons to whom the Font Software is furnished to do so, subject to
the following conditions:
The above copyright and trademark notices and this permission notice
shall be included in all copies of one or more of the Font Software
typefaces.
The Font Software may be modified, altered, or added to, and in
particular the designs of glyphs or characters in the Fonts may be
modified and additional glyphs or characters may be added to the
Fonts, only if the fonts are renamed to names not containing either
the words "Tavmjong Bah" or the word "Arev".
This License becomes null and void to the extent applicable to Fonts
or Font Software that has been modified and is distributed under the
"Tavmjong Bah Arev" names.
The Font Software may be sold as part of a larger software package but
no copy of one or more of the Font Software typefaces may be sold by
itself.
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL
TAVMJONG BAH BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Except as contained in this notice, the name of Tavmjong Bah shall not
be used in advertising or otherwise to promote the sale, use or other
dealings in this Font Software without prior written authorization
from Tavmjong Bah. For further information, contact: tavmjong @ free
. fr.
TeX Gyre DJV Math
-----------------
Fonts are (c) Bitstream (see below). DejaVu changes are in public domain.
Math extensions done by B. Jackowski, P. Strzelczyk and P. Pianowski
(on behalf of TeX users groups) are in public domain.
Letters imported from Euler Fraktur from AMSfonts are (c) American
Mathematical Society (see below).
Bitstream Vera Fonts Copyright
Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera
is a trademark of Bitstream, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of the fonts accompanying this license (“Fonts”) and associated
documentation
files (the “Font Software”), to reproduce and distribute the Font Software,
including without limitation the rights to use, copy, merge, publish,
distribute,
and/or sell copies of the Font Software, and to permit persons to whom
the Font Software is furnished to do so, subject to the following
conditions:
The above copyright and trademark notices and this permission notice
shall be
included in all copies of one or more of the Font Software typefaces.
The Font Software may be modified, altered, or added to, and in particular
the designs of glyphs or characters in the Fonts may be modified and
additional
glyphs or characters may be added to the Fonts, only if the fonts are
renamed
to names not containing either the words “Bitstream” or the word “Vera”.
This License becomes null and void to the extent applicable to Fonts or
Font Software
that has been modified and is distributed under the “Bitstream Vera”
names.
The Font Software may be sold as part of a larger software package but
no copy
of one or more of the Font Software typefaces may be sold by itself.
THE FONT SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT,
TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME
FOUNDATION
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL,
SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN
ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR
INABILITY TO USE
THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
Except as contained in this notice, the names of GNOME, the GNOME
Foundation,
and Bitstream Inc., shall not be used in advertising or otherwise to promote
the sale, use or other dealings in this Font Software without prior written
authorization from the GNOME Foundation or Bitstream Inc., respectively.
For further information, contact: fonts at gnome dot org.
AMSFonts (v. 2.2) copyright
The PostScript Type 1 implementation of the AMSFonts produced by and
previously distributed by Blue Sky Research and Y&Y, Inc. are now freely
available for general use. This has been accomplished through the
cooperation
of a consortium of scientific publishers with Blue Sky Research and Y&Y.
Members of this consortium include:
Elsevier Science IBM Corporation Society for Industrial and Applied
Mathematics (SIAM) Springer-Verlag American Mathematical Society (AMS)
In order to assure the authenticity of these fonts, copyright will be
held by
the American Mathematical Society. This is not meant to restrict in any way
the legitimate use of the fonts, such as (but not limited to) electronic
distribution of documents containing these fonts, inclusion of these fonts
into other public domain or commercial font collections or computer
applications, use of the outline data to create derivative fonts and/or
faces, etc. However, the AMS does require that the AMS copyright notice be
removed from any derivative versions of the fonts which have been altered in
any way. In addition, to ensure the fidelity of TeX documents using Computer
Modern fonts, Professor Donald Knuth, creator of the Computer Modern faces,
has requested that any alterations which yield different font metrics be
given a different name.
$Id$
@@ -0,0 +1,93 @@
Copyright 2015 the Cormorant Project Authors (github.com/CatharsisFonts/Cormorant)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
@@ -0,0 +1,93 @@
Copyright 2020 The Inter Project Authors (https://github.com/rsms/inter)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
@@ -0,0 +1,5 @@
Fonts of the share preview images (`src/app/s/[slug]/kep`), read at run time.
- Cormorant Garamond SemiBold, Inter Regular and SemiBold: static instances from
Google Fonts, SIL Open Font License (LICENSE-OFL-*.txt).
- DejaVu Sans 2.37: the zodiac and planet glyphs (LICENSE-DejaVu.txt).
@@ -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. */
@@ -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
<p className="muted" role="status">
{text}
</p>
<p className="hint" aria-hidden="true">
<p className="hint" aria-hidden="true" suppressHydrationWarning>
{elapsed}
</p>
</div>
@@ -8,9 +8,28 @@ 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;
const TEXTS = {
natal: {
title: "Kérdezz az elemzésedről",
hint: "Mit jelent ez a te életedben, hogyan kapcsolódik két rész egymáshoz? A válasz a képleted és az elemzés alapján készül, legfeljebb 250 szóban.",
example: "Pl. Hogyan hat a Hold helyzete a kapcsolataimra?",
},
synastry: {
title: "Kérdezz a kapcsolatotokról",
hint: "Hol erősítitek egymást, mire figyeljetek egy vitában, mit ad nektek a kapcsolat? A válasz a két képlet és az elemzés alapján készül, legfeljebb 250 szóban. A kérdéseket és a válaszokat mindketten látjátok.",
example: "Pl. Hogyan kezeljük jobban a nézeteltéréseinket?",
},
forecast: {
title: "Kérdezz az előrejelzésedről",
hint: "Mire figyelj egy időszakban, mit hozhat egy tranzit a munkádban vagy a kapcsolataidban? A válasz az év adatai és az előrejelzés alapján készül, legfeljebb 250 szóban.",
example: "Pl. Mire figyeljek a nyári időszakban a munkámban?",
},
};
const POLL_MS = 3000;
const MAX_POLLS = 80; // 4 minutes
@@ -24,13 +43,14 @@ export function AnalysisQuestions({
left: initialLeft,
isAdmin,
canPay,
forecast = false,
about,
}: {
analysisId: string;
left: number;
isAdmin: boolean;
canPay: boolean;
forecast?: boolean;
/** What the analysis is about: the heading and the example question follow it. */
about: "natal" | "synastry" | "forecast";
}) {
const [questions, setQuestions] = useState<Question[] | null>(null);
const [left, setLeft] = useState(initialLeft);
@@ -114,11 +134,8 @@ export function AnalysisQuestions({
const canAsk = isAdmin || left > 0;
return (
<section className="questions" aria-labelledby={`${fieldId}-title`}>
<h3 id={`${fieldId}-title`}>Kérdezz {forecast ? "az előrejelzésedről" : "az elemzésedről"}</h3>
<p className="hint">
Mit jelent ez a te életedben, mire figyelj egy időszakban, hogyan kapcsolódik két rész egymáshoz? A válasz a képleted
és az elemzés alapján készül, legfeljebb 250 szóban.
</p>
<h3 id={`${fieldId}-title`}>{TEXTS[about].title}</h3>
<p className="hint">{TEXTS[about].hint}</p>
{questions?.map((q) => (
<article key={q.id} className="qa" aria-busy={q.status === "pending" || q.status === "running"}>
@@ -139,12 +156,21 @@ export function AnalysisQuestions({
<RegenerateButton<Question> url={`/admin/questions/${q.id}/regenerate`} onStarted={replace} />
)}
<p className="msg msg-error" role="alert">
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.
</p>
{isAdmin && q.error && <p className="hint">Hiba: {q.error}</p>}
</div>
) : (
<AnalysisLoading compact text="Készül a válasz, ez általában fél perc…" />
<>
<AnalysisLoading
compact
text="Készül a válasz, ez általában fél perc…"
since={q.requested_at ?? q.created_at}
/>
<RetryNotice status={q.status} error={q.error} nextAttemptAt={q.next_attempt_at} isAdmin={isAdmin} />
</>
)}
</article>
))}
@@ -160,9 +186,7 @@ export function AnalysisQuestions({
rows={3}
maxLength={MAX_CHARS}
value={text}
placeholder={
forecast ? "Pl. Mire figyeljek a nyári időszakban a munkámban?" : "Pl. Hogyan hat a Hold helyzete a kapcsolataimra?"
}
placeholder={TEXTS[about].example}
onChange={(e) => setText(e.target.value)}
disabled={busy || waiting}
/>
@@ -11,14 +11,17 @@ const ORDER = { natal: NATAL_ORDER, synastry: SYNASTRY_ORDER, forecast: FORECAST
export function AnalysisView({
content,
kind = "natal",
language,
}: {
content: AnalysisContent;
kind?: "natal" | "synastry" | "forecast";
/** The language of the text, for hyphenation. */
language?: string;
}) {
const order = ORDER[kind];
const sections = order.map((key) => content.sections?.[key]).filter((s) => s !== undefined);
return (
<article className="analysis">
<article className="analysis" lang={language}>
<header className="analysis-head">
<h2>{content.title}</h2>
{content.summary && (
@@ -7,7 +7,9 @@ import type { Analysis } from "@/lib/types";
import { AnalysisLoading } from "./AnalysisLoading";
import { RegenerateButton } from "./RegenerateButton";
import { RetryNotice } from "./RetryNotice";
import { Rich } from "./Rich";
import { ShareChart } from "./ShareChart";
import { openTab } from "./Tabs";
const POLL_MS = 3000;
@@ -77,9 +79,10 @@ export function ChartSummary({
<h2 id="summary-title" className="summary-title">
{content.title}
</h2>
<p className="summary-text">
<p className="summary-text" lang={summary?.language}>
<Rich text={content.summary ?? ""} />
</p>
<ShareChart chartId={chartId} />
<a
href="#elemzes"
className="summary-more"
@@ -102,7 +105,21 @@ export function ChartSummary({
Az összefoglaló most nem készült el. Töltsd újra az oldalt egy kicsit később.
</p>
) : (
<AnalysisLoading compact text="Az összefoglalód készül, ez néhány másodperc…" />
<>
<AnalysisLoading
compact
text="Az összefoglalód készül, ez néhány másodperc…"
since={summary?.requested_at ?? summary?.created_at}
/>
{summary && (
<RetryNotice
status={summary.status}
error={summary.error}
nextAttemptAt={summary.next_attempt_at}
isAdmin={isAdmin}
/>
)}
</>
)}
</>
)}
@@ -11,6 +11,7 @@ import { AnalysisLoading } from "./AnalysisLoading";
import { AnalysisQuestions } from "./AnalysisQuestions";
import { PackageChooser } from "./PackageCards";
import { RegenerateButton } from "./RegenerateButton";
import { RetryNotice } from "./RetryNotice";
import { AnalysisView } from "./AnalysisView";
const POLL_MS = 5000;
@@ -99,7 +100,7 @@ export function DetailedAnalysis({
canPay: boolean;
/** Shown above a finished analysis (e.g. who is the first and the second person). */
note?: string;
/** Questions left; given where questions can be asked (natal analysis, forecast). */
/** Questions left; given where questions can be asked. */
questionsLeft?: number;
}) {
const [analysis, setAnalysis] = useState<Analysis | null>(initial);
@@ -154,14 +155,14 @@ export function DetailedAnalysis({
<RegenerateButton<Analysis> url={`/admin/analyses/${analysis.id}/regenerate`} onStarted={setAnalysis} />
)}
{note && <p className="hint">{note}</p>}
<AnalysisView content={analysis.content} kind={target.kind} />
{questionsLeft !== undefined && target.kind !== "synastry" && (
<AnalysisView content={analysis.content} kind={target.kind} language={analysis.language} />
{questionsLeft !== undefined && (
<AnalysisQuestions
analysisId={analysis.id}
left={questionsLeft}
isAdmin={isAdmin}
canPay={canPay}
forecast={target.kind === "forecast"}
about={target.kind}
/>
)}
</section>
@@ -172,7 +173,15 @@ export function DetailedAnalysis({
return (
<section className="analysis-card" aria-label={t.eyebrow} aria-busy="true">
<span className="eyebrow">{t.eyebrow}</span>
<AnalysisLoading title={t.loadingTitle} text={t.loading} />
<AnalysisLoading title={t.loadingTitle} text={t.loading} since={analysis?.requested_at ?? analysis?.created_at} />
{analysis && (
<RetryNotice
status={analysis.status}
error={analysis.error}
nextAttemptAt={analysis.next_attempt_at}
isAdmin={isAdmin}
/>
)}
</section>
);
}
@@ -186,9 +195,15 @@ export function DetailedAnalysis({
<p className="muted">{t.about}</p>
<p className="ai-line">{AI_SHORT}</p>
{analysis?.status === "failed" && (
<p className="msg msg-error" role="alert">
Az előző kérés nem sikerült{isAdmin ? "" : ", az elemzést visszaadtuk a keretedbe"}. Próbáld újra.
<div className="msg msg-error" role="alert">
<p style={{ margin: 0 }}>
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."}
</p>
{isAdmin && analysis.error && <p className="hint">Hiba: {analysis.error}</p>}
</div>
)}
{error && (
<p className="msg msg-error" role="alert">
@@ -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 (
<div className="msg retry-notice" role="status">
<p>
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.` : ""}
</p>
{isAdmin && <p className="hint">Hiba: {error}</p>}
</div>
);
}
@@ -0,0 +1,122 @@
"use client";
import { useState } from "react";
import { api, errorText } from "@/lib/api";
interface Share {
id: string;
url: string;
}
/** Share link of a chart with its short summary: copy, Facebook, the phone's share menu, revoke. */
export function ShareChart({ chartId }: { chartId: string }) {
const [share, setShare] = useState<Share | null>(null);
const [busy, setBusy] = useState(false);
const [copied, setCopied] = useState(false);
const [error, setError] = useState<string | null>(null);
const [revoked, setRevoked] = useState(false);
async function open() {
setBusy(true);
setError(null);
try {
setShare(await api<Share>("/shares", { body: { kind: "chart", target_id: chartId } }));
setRevoked(false);
} catch (e) {
setError(errorText(e));
} finally {
setBusy(false);
}
}
async function copy() {
if (!share) return;
try {
await navigator.clipboard.writeText(share.url);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
} catch {
setError("Nem sikerült másolni; jelöld ki a linket, és másold kézzel.");
}
}
async function nativeShare() {
if (!share) return;
try {
await navigator.share({ url: share.url });
} catch {
// closed by the user
}
}
async function revoke() {
if (!share || !window.confirm("Visszavonod a linket? Aki megkapta, többé nem tudja megnyitni.")) return;
setBusy(true);
try {
await api(`/shares/${share.id}`, { method: "DELETE" });
setShare(null);
setRevoked(true);
} catch (e) {
setError(errorText(e));
} finally {
setBusy(false);
}
}
if (!share) {
return (
<div className="share">
<button type="button" className="btn btn-sm" onClick={open} disabled={busy}>
{busy ? "Link készül…" : "Megosztás"}
</button>
{revoked && <p className="hint">A linket visszavontad.</p>}
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
</div>
);
}
const facebook = `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(share.url)}`;
return (
<div className="share share-open">
<p className="hint">
A linken a képleted rajza és ez az összefoglaló látszik, név és születési adatok nélkül. Bárki megnyithatja,
akinek elküldöd.
</p>
<div className="share-link">
<input
className="inp"
readOnly
value={share.url}
aria-label="Megosztási link"
onFocus={(e) => e.currentTarget.select()}
/>
<button type="button" className="btn btn-sm" onClick={copy}>
{copied ? "Kimásolva" : "Másolás"}
</button>
</div>
<div className="form-actions">
<a className="btn btn-sm btn-primary" href={facebook} target="_blank" rel="noopener noreferrer">
Megosztás Facebookon
</a>
{typeof navigator !== "undefined" && "share" in navigator && (
<button type="button" className="btn btn-sm" onClick={nativeShare}>
Küldés…
</button>
)}
<button type="button" className="btn btn-sm btn-ghost" onClick={revoke} disabled={busy}>
Link visszavonása
</button>
</div>
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
</div>
);
}
+81
View File
@@ -0,0 +1,81 @@
// Public share links (`/s/<slug>`): loading the shared content and the
// texts of the page, its link preview and its preview image.
import "server-only";
import { headers } from "next/headers";
import { cache } from "react";
import { BACKEND_URL } from "./server";
import type { ChartResult } from "./types";
export interface PublicSummary {
id: string;
language: string;
title: string | null;
summary: string | null;
completed_at: string | null;
}
/** `GET /v1/public/shares/{slug}` of a shared chart. */
export interface PublicShare {
kind: "chart" | "synastry" | "analysis";
title: string | null;
created_at: string;
chart?: { label: string; chart: ChartResult & { time_known: boolean } };
summary?: PublicSummary | null;
}
const SLUG = /^[A-Za-z0-9_-]{8,64}$/;
/** The shared content, or `null` if the link is unknown or revoked (one backend call per request). */
export const loadShare = cache(async (slug: string): Promise<PublicShare | null> => {
if (!SLUG.test(slug)) return null;
const res = await fetch(`${BACKEND_URL}/v1/public/shares/${slug}`, { cache: "no-store" });
if (res.status === 404) return null;
if (!res.ok) throw new Error(`share ${slug}: HTTP ${res.status}`);
return (await res.json()) as PublicShare;
});
/** The site's own address, for absolute links in the preview tags. */
export async function siteUrl(): Promise<string> {
const fixed = process.env.PUBLIC_BASE_URL;
if (fixed) return fixed.replace(/\/$/, "");
const h = await headers();
const host = h.get("x-forwarded-host") ?? h.get("host") ?? "localhost:3001";
const proto = h.get("x-forwarded-proto") ?? (host.startsWith("localhost") ? "http" : "https");
return `${proto}://${host}`;
}
/** Model text without the `**bold**` marks. */
export function plain(text: string): string {
return text.replace(/\*\*/g, "").replace(/\s+/g, " ").trim();
}
/** At most `max` characters, cut at a word, with an ellipsis. */
export function shorten(text: string, max: number): string {
if (text.length <= max) return text;
const cut = text.slice(0, max - 1);
const space = cut.lastIndexOf(" ");
return `${(space > max * 0.6 ? cut.slice(0, space) : cut).replace(/[\s,;:–-]+$/, "")}…`;
}
/** Changes whenever the summary is rewritten, so link previews fetch the new image. */
export function imageVersion(share: PublicShare): string {
const s = share.summary;
if (!s) return "kep";
const time = s.completed_at ? Date.parse(s.completed_at).toString(36) : "0";
return `${s.id.replace(/-/g, "").slice(-8)}${time}`;
}
/** "Nap Nyilas · Hold Bika · Aszcendens Mérleg" (the ascendant only with a known time). */
export function bigThree(chart: ChartResult & { time_known: boolean }): { label: string; sign: string }[] {
const sign = (id: string) => chart.points.find((p) => p.id === id)?.sign;
const asc = chart.angles?.ascendant;
const out: { label: string; sign: string }[] = [];
const sun = sign("sun");
const moon = sign("moon");
if (sun) out.push({ label: "Nap", sign: sun });
if (moon) out.push({ label: "Hold", sign: moon });
if (chart.time_known && typeof asc === "object" && asc) out.push({ label: "Aszcendens", sign: asc.sign });
return out;
}
+47 -2
View File
@@ -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 {
@@ -248,9 +271,9 @@ export interface AdminUser {
export type PromptKind = "summary" | "natal" | "synastry" | "forecast" | "question";
/** Admin: the model writing one kind of analysis. */
/** Admin: the model of one function (all analyses and forecasts, answers, the short summary). */
export interface ModelFunction {
kind: PromptKind;
kind: "summary" | "analysis" | "question";
model: string;
/** The configured default (environment). */
default: string;
@@ -261,6 +284,28 @@ export interface ModelFunction {
avg_input_tokens: number | null;
avg_output_tokens: number | null;
samples: number;
/** In the last 30 days: texts the default model had to write, of all finished. */
fallbacks_30d: number;
finished_30d: number;
}
/** Admin: an analysis or answer being written or waiting in the queue. */
export interface AdminJob {
id: string;
type: "analysis" | "question";
kind: "summary" | "natal" | "synastry" | "forecast" | "question";
status: "pending" | "running";
/** The model of the current attempt. */
model: string;
on_fallback: boolean;
/** What a restart would use now. */
next_model: string;
next_fallback: string | null;
attempts: number;
started_at: string | null;
created_at: string;
next_attempt_at: string;
error: string | null;
}
/** A model OpenRouter offers; prices in USD per million tokens. */
+74
View File
@@ -0,0 +1,74 @@
// The chart wheel as a standalone SVG document, for the share preview image.
// It reuses the page's <ChartWheel> and turns its element tree into markup
// with the colours inlined (no page CSS there).
import { Fragment, isValidElement, type ReactElement, type ReactNode } from "react";
import { ChartWheel, SIZE } from "@/components/ChartWheel";
import type { ChartResult } from "@/lib/types";
// The page's wheel rules (globals.css) with the colour tokens resolved.
const STYLE = `
.w-ring{fill:none;stroke:#2c3654;stroke-width:1.2}
.w-faint{stroke:#1f2740}
.w-inner{fill:#0f1426}
.w-sign{stroke:#2c3654;stroke-width:1}
.w-fire{fill:rgba(227,139,106,.09)}
.w-earth{fill:rgba(159,216,176,.07)}
.w-air{fill:rgba(217,180,106,.08)}
.w-water{fill:rgba(127,176,224,.09)}
.w-sign-glyph{fill:#d9b46a;font-family:'DejaVu Sans';font-size:22px}
.w-tick,.w-cusp{stroke:#2c3654;stroke-width:1}
.w-axis{stroke:#d9b46a;stroke-width:1.8}
.w-axis-label{fill:#d9b46a;font-family:Inter;font-weight:600;font-size:14px}
.w-house-num{fill:#a3abc0;font-family:Inter;font-size:12px}
.w-aspect{stroke-linecap:round}
.w-asp-trine{stroke:#7fb0e0}
.w-asp-sextile{stroke:#7fb0e0;stroke-dasharray:5 4}
.w-asp-square{stroke:#f0a35e}
.w-asp-opposition{stroke:#e38b8b}
.w-point-tick{stroke:#ece6d8;stroke-width:1.6}
.w-leader{stroke:#a3abc0;stroke-width:.7;stroke-opacity:.6}
.w-point-glyph{fill:#ece6d8;font-family:'DejaVu Sans';font-size:22px}
.w-point-deg{fill:#a3abc0;font-family:Inter;font-size:10.5px}
.w-end{fill:#c9cfdc}
.w-point-glyph,.w-point-deg,.w-house-num,.w-axis-label{paint-order:stroke;stroke:#111729;stroke-width:4px;stroke-linejoin:round}
`;
// React prop names that are not SVG attributes (or not wanted in the image).
const SKIP = new Set(["children", "key", "role", "id"]);
const escape = (s: string) =>
s.replace(/︎/g, "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
function attribute(name: string): string {
if (name === "className") return "class";
if (name === "viewBox") return name;
return name.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`);
}
function markup(node: ReactNode): string {
if (node === null || node === undefined || typeof node === "boolean") return "";
if (typeof node === "string" || typeof node === "number") return escape(String(node));
if (Array.isArray(node)) return node.map(markup).join("");
if (!isValidElement(node)) return "";
const { type, props } = node as ReactElement<Record<string, unknown>>;
if (type === Fragment) return markup(props.children as ReactNode);
if (typeof type === "function") return markup((type as (p: unknown) => ReactNode)(props));
if (typeof type !== "string" || type === "title" || type === "desc") return "";
const attrs = Object.entries(props)
.filter(([k, v]) => !SKIP.has(k) && !k.startsWith("aria-") && v !== undefined && v !== null && v !== false)
.map(([k, v]) => ` ${attribute(k)}="${escape(String(v))}"`)
.join("");
return `<${type}${attrs}>${markup(props.children as ReactNode)}</${type}>`;
}
/** The wheel as an SVG document of `size` pixels. */
export function wheelSvg(chart: ChartResult, timeKnown: boolean, size = SIZE): string {
const body = markup(ChartWheel({ chart, timeKnown }))
.replace(/^<svg[^>]*>/, "")
.replace(/<\/svg>$/, "");
return (
`<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 ${SIZE} ${SIZE}">` +
`<style>${STYLE}</style>${body}</svg>`
);
}
+9 -2
View File
@@ -21,6 +21,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 levon egy elemzési egységet. Egy trigger (`NOTIFY analyses`) felébreszti a workert; egyszerre `ANALYSIS_CONCURRENCY` elemzés készül.
- **Két sáv**, saját helyekkel, hogy egy rövid szöveg ne várjon a hosszúak mögött:
- *gyors sáv* (`QUICK_CONCURRENCY`, alapból 2): előbb a kérdések, aztán a rövid összefoglalók;
- *lassú sáv* (`ANALYSIS_CONCURRENCY`, alapból 4): a részletes elemzések és az előrejelzések. Ha nincs ilyen, a szabad hely gyors munkát vesz fel, végül az admin próbafuttatásait.
- A 0 kikapcsolja a sávot, így a két sáv külön telepítésként is futhat (például Kubernetesen: egy gyors és egy lassú deployment).
- **Több worker** is dolgozhat ugyanabból a sorból: a sorokat `FOR UPDATE SKIP LOCKED` foglalja, egy munkát csak egy worker kap meg. Leálláskor mindegyik csak a saját félbehagyott munkáit adja vissza a sorba, az elakadt (15 percnél régebben futó) munkákat bármelyik visszateszi. Az e-mail-küldés és a takarítás is biztonságos több példányban.
- 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.
- **5 fokos szabály:** ha egy pont legfeljebb 5°-kal (`CUSP_ORB`) a következő ház csúcsa előtt áll, a szöveg már abban a házban adja meg, és odaírja, hogy formálisan az előzőben van („house 11 (on the cusp: 2°00' before it, formally house 10)”). Így olvassák az asztrológusok. A számított ház, a képlet rajza és a táblázatok nem változnak. Ugyanez érvényes az összevetés házátfedéseire, a szolár Aszcendensre, az év urára és a fogyatkozásokra.
- 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 (`crates/analysis-prompt`, `PROMPT_VERSION = v3`; ha a sor `prompt_version`-je `v3-r<id>`, a system prompt az admin által szerkesztett `prompt_revisions` sorból jön):
@@ -45,7 +50,7 @@ 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.
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 (kb. 0,009 dollár, a Haiku kb. 0,001). 2026-11-18 óta minden funkció alapmodellje az Opus 5.5 (`SUMMARY_MODEL`, `ANALYSIS_MODEL`); olcsóbb modell az admin Modellek oldalán választható, hiba esetén az Opus 5.5 a tartalék.
```bash
OPENROUTER_API_KEY=... worker compare-models --chart natal.json \
@@ -72,7 +77,9 @@ Ugyanazt a radix-elemzést több modellel is megírja, véletlenszerű betűkkel
| `OPENROUTER_API_KEY` | – | OpenRouter-kulcs (compose-ban a `.env.secrets` fájlból); nélküle az elemzések várnak |
| `OPENROUTER_BASE_URL` | `https://openrouter.ai/api/v1` | |
| `PUBLIC_BASE_URL` | – | `HTTP-Referer` fejléc az OpenRouter felé |
| `ANALYSIS_CONCURRENCY` | `4` | egyszerre írt elemzések |
| `WORKER_TASKS` | `email,cleanup,analyses` | a folyamat feladatai; élesben `worker`: `email,cleanup`, `worker-ai`: `analyses` |
| `ANALYSIS_CONCURRENCY` | `4` | lassú sáv: egyszerre írt részletes elemzések és előrejelzések (0: kikapcsolva) |
| `QUICK_CONCURRENCY` | `2` | gyors sáv: egyszerre írt rövid összefoglalók és válaszok (0: kikapcsolva) |
| `MAX_ANALYSIS_ATTEMPTS` | `3` | ennyi próbálkozás után sikertelen az elemzés (az egység visszajár) |
| `BIND_ADDR`, `LOG_FORMAT`, `RUST_LOG` | `0.0.0.0:8082`, `text`, `info` | |
+248 -53
View File
@@ -8,6 +8,17 @@
//!
//! Admin test runs of an edited prompt (`prompt_previews`) go through the
//! same loop when no analysis is due: one attempt, no credits, no retries.
//!
//! Two lanes, each with its own slots, so a short text never waits behind
//! the long ones: the quick lane writes summaries and answers questions, the
//! slow lane writes the detailed analyses and forecasts (and the test runs).
//! A free slow slot also takes quick work. A lane of size 0 is off, so the
//! lanes can run as separate deployments; several workers may share the
//! queue, rows are claimed with `FOR UPDATE SKIP LOCKED`.
//!
//! Fallback: when the model chosen on the admin page fails twice (or once with
//! a permanent error), the default model (`fallback_model`) takes over with a
//! fresh set of attempts; only when that fails too is the unit refunded.
pub mod compact;
pub mod openrouter;
@@ -25,6 +36,7 @@ use uuid::Uuid;
use self::openrouter::{Completion, LlmError, OpenRouter};
use self::prompt::{Kind, PROMPT_VERSION, Prompt};
use self::questions::QuestionJob;
/// A `running` analysis older than this was left behind by a stopped worker.
const STUCK_AFTER_MINUTES: i32 = 15;
@@ -40,6 +52,48 @@ pub struct Job {
pub model: String,
pub prompt_version: String,
pub attempts: i32,
/// The default model, when the chosen one is another (see the module docs).
pub fallback_model: Option<String>,
pub on_fallback: bool,
/// When this attempt started; also its token: an admin restart clears it,
/// so a superseded attempt neither writes its result nor keeps running.
pub started_at: time::OffsetDateTime,
}
impl Job {
/// The model of this attempt.
pub fn active_model(&self) -> &str {
active_model(&self.model, self.fallback_model.as_deref(), self.on_fallback)
}
}
pub fn active_model<'a>(model: &'a str, fallback: Option<&'a str>, on_fallback: bool) -> &'a str {
match fallback {
Some(f) if on_fallback => f,
_ => model,
}
}
/// What happens after a failed attempt.
#[derive(Debug, PartialEq, Eq)]
pub enum Next {
Retry(Duration),
/// Switch to the fallback model, with a fresh set of attempts, at once.
Fallback,
/// Give up (and refund).
Fail,
}
/// The chosen model gets two attempts (one after a permanent error), then the
/// fallback model takes over with its own `max_attempts`.
pub fn next_step(error: &LlmError, attempts: i32, max_attempts: i32, can_fall_back: bool) -> Next {
if can_fall_back && (matches!(error, LlmError::Permanent(_)) || attempts >= 2) {
return Next::Fallback;
}
match error {
LlmError::Transient(_) if attempts < max_attempts => Next::Retry(backoff(attempts)),
_ => Next::Fail,
}
}
/// A test run of an edited system prompt on a chart.
@@ -55,11 +109,36 @@ pub struct PreviewJob {
pub system: String,
}
/// Which analyses a claim may take.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Lane {
/// The short summary of a chart (questions are claimed separately).
Quick,
/// The detailed analyses and the yearly forecast.
Slow,
}
impl Lane {
fn kinds(self) -> &'static [&'static str] {
match self {
Lane::Quick => &["summary"],
Lane::Slow => &["natal", "synastry", "forecast"],
}
}
}
/// Slots per lane; 0 turns a lane off.
#[derive(Debug, Clone, Copy)]
pub struct Lanes {
pub quick: usize,
pub slow: usize,
}
pub struct Analyzer {
pub db: PgPool,
pub llm: OpenRouter,
pub max_attempts: i32,
pub concurrency: usize,
pub lanes: Lanes,
/// Analyses and previews being written right now (released on shutdown).
running: Mutex<HashSet<Uuid>>,
}
@@ -71,18 +150,21 @@ pub fn backoff(attempts: i32) -> Duration {
}
impl Analyzer {
pub fn new(db: PgPool, llm: OpenRouter, max_attempts: i32, concurrency: usize) -> Self {
Self { db, llm, max_attempts, concurrency: concurrency.max(1), running: Mutex::default() }
pub fn new(db: PgPool, llm: OpenRouter, max_attempts: i32, lanes: Lanes) -> Self {
Self { db, llm, max_attempts, lanes, running: Mutex::default() }
}
/// Takes the next due analysis, if any.
pub async fn claim(&self) -> Result<Option<Job>, sqlx::Error> {
/// Takes the next due analysis of the lane, if any.
pub async fn claim(&self, lane: Lane) -> Result<Option<Job>, sqlx::Error> {
let job: Option<Job> = sqlx::query_as(
"UPDATE analyses SET status = 'running', started_at = now(), attempts = attempts + 1 \
WHERE id = (SELECT id FROM analyses WHERE status = 'pending' AND next_attempt_at <= now() \
AND kind = ANY($1) \
ORDER BY next_attempt_at LIMIT 1 FOR UPDATE SKIP LOCKED) \
RETURNING id, kind, chart_id, synastry_id, forecast_id, language, model, prompt_version, attempts",
RETURNING id, kind, chart_id, synastry_id, forecast_id, language, model, prompt_version, attempts, \
fallback_model, on_fallback, started_at",
)
.bind(lane.kinds())
.fetch_optional(&self.db)
.await?;
if let Some(job) = &job {
@@ -206,6 +288,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'",
@@ -229,12 +313,21 @@ impl Analyzer {
/// Writes one claimed analysis and records the outcome.
pub async fn handle(&self, job: Job) {
let started = Instant::now();
let result = match self.prompt_for(&job).await {
Ok(prompt) => self.llm.complete(&job.model, &prompt).await.map(|mut c| {
let work = async {
match self.prompt_for(&job).await {
Ok(prompt) => self.llm.complete(job.active_model(), &prompt).await.map(|mut c| {
prompt::polish(&job.language, &mut c.content);
c
}),
Err(e) => Err(e),
}
};
let result = tokio::select! {
result = work => result,
() = self.superseded("analyses", job.id, job.started_at) => {
tracing::info!(id = %job.id, "analysis restarted by an admin; this attempt is dropped");
return;
}
};
if let Err(e) = self.finish(&job, result, started.elapsed()).await {
tracing::error!(id = %job.id, error = %e, "saving the analysis result failed");
@@ -248,7 +341,7 @@ impl Analyzer {
sqlx::query(
"UPDATE analyses SET status = 'done', content = $2, model_used = $3, input_tokens = $4, \
output_tokens = $5, cost_usd = $6, error = NULL, completed_at = now() \
WHERE id = $1 AND status = 'running'",
WHERE id = $1 AND status = 'running' AND started_at = $7",
)
.bind(job.id)
.bind(&c.content)
@@ -256,6 +349,7 @@ impl Analyzer {
.bind(c.input_tokens)
.bind(c.output_tokens)
.bind(c.cost_usd)
.bind(job.started_at)
.execute(&self.db)
.await?;
tracing::info!(
@@ -263,36 +357,75 @@ impl Analyzer {
cost_usd = c.cost_usd, secs = took.as_secs(), "analysis done"
);
}
Err(LlmError::Transient(message)) if job.attempts < self.max_attempts => {
let wait = backoff(job.attempts);
Err(e) => {
let can_fall_back = !job.on_fallback && job.fallback_model.is_some();
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, \
next_attempt_at = now() + make_interval(secs => $3) WHERE id = $1 AND status = 'running'",
next_attempt_at = now() + make_interval(secs => $3) \
WHERE id = $1 AND status = 'running' AND started_at = $4",
)
.bind(job.id)
.bind(&message)
.bind(e.message())
.bind(wait.as_secs_f64())
.bind(job.started_at)
.execute(&self.db)
.await?;
tracing::warn!(id = %job.id, attempts = job.attempts, retry_in_secs = wait.as_secs(), error = %message, "analysis will be retried");
tracing::warn!(id = %job.id, attempts = job.attempts, retry_in_secs = wait.as_secs(), error = %e.message(), "analysis will be retried");
}
Err(e) => {
self.fail(job.id, e.message()).await?;
Next::Fallback => {
sqlx::query(
"UPDATE analyses SET status = 'pending', error = $2, on_fallback = true, attempts = 0, \
next_attempt_at = now() WHERE id = $1 AND status = 'running' AND started_at = $3",
)
.bind(job.id)
.bind(e.message())
.bind(job.started_at)
.execute(&self.db)
.await?;
tracing::warn!(
id = %job.id, model = %job.model, fallback = ?job.fallback_model, error = %e.message(),
"the chosen model failed, the default model takes over"
);
}
Next::Fail => {
self.fail(job.id, job.started_at, e.message()).await?;
tracing::error!(id = %job.id, attempts = job.attempts, error = %e.message(), "analysis failed");
}
}
}
}
Ok(())
}
/// Marks the analysis failed and gives its unit back (once).
async fn fail(&self, id: Uuid, message: &str) -> Result<(), sqlx::Error> {
async fn fail(&self, id: Uuid, started_at: time::OffsetDateTime, message: &str) -> Result<(), sqlx::Error> {
let mut tx = self.db.begin().await?;
let row: Option<(Option<Uuid>, i32, String)> = sqlx::query_as(
"UPDATE analyses SET status = 'failed', error = $2, completed_at = now() \
WHERE id = $1 AND status = 'running' RETURNING requested_by, credits_charged, kind",
WHERE id = $1 AND status = 'running' AND started_at = $3 RETURNING requested_by, credits_charged, kind",
)
.bind(id)
.bind(message)
.bind(started_at)
.fetch_optional(&mut *tx)
.await?;
if let Some((Some(user), units, kind)) = row
@@ -345,6 +478,53 @@ 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::<String>())
.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) {
let query = format!("SELECT status = 'running' AND started_at = $2 FROM {table} WHERE id = $1");
loop {
tokio::time::sleep(Duration::from_secs(10)).await;
match sqlx::query_scalar::<_, Option<bool>>(&query).bind(id).bind(started_at).fetch_optional(&self.db).await
{
Ok(Some(Some(true))) => {}
Ok(_) => return,
Err(_) => {}
}
}
}
/// On shutdown: analyses still being written go back to `pending` at once.
async fn release_running(&self) {
let ids: Vec<Uuid> = self.running.lock().unwrap().drain().collect();
@@ -385,8 +565,46 @@ impl Analyzer {
}
}
/// Work a free slot can take, in order of preference.
pub(crate) enum Work {
Analysis(Job),
Question(QuestionJob),
Preview(PreviewJob),
}
impl Analyzer {
/// Quick work: a question first (someone is waiting for a short answer),
/// then a summary.
pub(crate) async fn claim_quick(&self) -> Result<Option<Work>, sqlx::Error> {
if let Some(job) = self.claim_question().await? {
return Ok(Some(Work::Question(job)));
}
Ok(self.claim(Lane::Quick).await?.map(Work::Analysis))
}
/// Slow work: a detailed analysis, else quick work, else a test run.
pub(crate) async fn claim_slow(&self) -> Result<Option<Work>, sqlx::Error> {
if let Some(job) = self.claim(Lane::Slow).await? {
return Ok(Some(Work::Analysis(job)));
}
if let Some(work) = self.claim_quick().await? {
return Ok(Some(work));
}
Ok(self.claim_preview().await?.map(Work::Preview))
}
async fn work(&self, work: Work) {
match work {
Work::Analysis(job) => self.handle(job).await,
Work::Question(job) => self.handle_question(job).await,
Work::Preview(job) => self.handle_preview(job).await,
}
}
}
pub async fn run(analyzer: Arc<Analyzer>, poll: Duration, stop: watch::Receiver<bool>) {
let slots = Arc::new(Semaphore::new(analyzer.concurrency));
let quick = Arc::new(Semaphore::new(analyzer.lanes.quick));
let slow = Arc::new(Semaphore::new(analyzer.lanes.slow));
let mut tasks = tokio::task::JoinSet::new();
let mut listener = crate::listen(&analyzer.db, "analyses").await;
let mut last_requeue: Option<Instant> = None;
@@ -402,50 +620,27 @@ pub async fn run(analyzer: Arc<Analyzer>, poll: Duration, stop: watch::Receiver<
Err(e) => tracing::error!(error = %e, "requeueing analyses"),
}
}
// Fill the free slots.
// Fill the free slots: the quick lane first, then the slow one.
for lane in [Lane::Quick, Lane::Slow] {
let slots = if lane == Lane::Quick { &quick } else { &slow };
while let Ok(permit) = slots.clone().try_acquire_owned() {
// Questions first: someone is waiting for a short answer.
match analyzer.claim_question().await {
Ok(Some(job)) => {
let claimed = match lane {
Lane::Quick => analyzer.claim_quick().await,
Lane::Slow => analyzer.claim_slow().await,
};
match claimed {
Ok(Some(work)) => {
let analyzer = analyzer.clone();
tasks.spawn(async move {
analyzer.handle_question(job).await;
drop(permit);
});
continue;
}
Ok(None) => {}
Err(e) => {
tracing::error!(error = %e, "claiming a question");
break;
}
}
match analyzer.claim().await {
Ok(Some(job)) => {
let analyzer = analyzer.clone();
tasks.spawn(async move {
analyzer.handle(job).await;
drop(permit);
});
}
// No analysis is due: a prompt test run, if one waits.
Ok(None) => match analyzer.claim_preview().await {
Ok(Some(job)) => {
let analyzer = analyzer.clone();
tasks.spawn(async move {
analyzer.handle_preview(job).await;
analyzer.work(work).await;
drop(permit);
});
}
Ok(None) => break,
Err(e) => {
tracing::error!(error = %e, "claiming a prompt preview");
tracing::error!(error = %e, ?lane, "claiming work");
break;
}
},
Err(e) => {
tracing::error!(error = %e, "claiming an analysis");
break;
}
}
}
+9 -5
View File
@@ -8,8 +8,9 @@ use serde_json::{Value, json};
use super::prompt::{Prompt, validate};
pub const DEFAULT_BASE_URL: &str = "https://openrouter.ai/api/v1";
/// Room for reasoning tokens as well as the answer.
const MAX_TOKENS: u32 = 16_000;
/// Room for reasoning tokens as well as the answer: reasoning models (e.g.
/// DeepSeek) think at length before answering. Only a cap, not a cost.
const MAX_TOKENS: u32 = 32_000;
pub struct OpenRouter {
http: reqwest::Client,
@@ -143,7 +144,8 @@ fn error_message(body: &Value, fallback: &str) -> String {
impl OpenRouter {
pub fn new(base_url: &str, api_key: &str, referer: Option<String>) -> Self {
let http = reqwest::Client::builder()
.timeout(Duration::from_secs(300))
// Reasoning models can take several minutes for a long analysis.
.timeout(Duration::from_secs(600))
.connect_timeout(Duration::from_secs(10))
.build()
.expect("HTTP client");
@@ -203,8 +205,10 @@ impl OpenRouter {
let content = extract_json(raw).ok_or_else(|| {
LlmError::Transient(format!("answer is not JSON: {}", raw.chars().take(200).collect::<String>()))
})?;
validate(&prompt.schema, &content)
.map_err(|e| LlmError::Transient(format!("answer does not match the schema: {e}")))?;
validate(&prompt.schema, &content).map_err(|e| {
tracing::warn!(model, answer = %raw.chars().take(500).collect::<String>(), "answer does not match the schema");
LlmError::Transient(format!("answer does not match the schema: {e}"))
})?;
let usage = &reply["usage"];
let tokens = |key: &str| usage[key].as_i64().and_then(|n| i32::try_from(n).ok());
+75 -20
View File
@@ -1,7 +1,7 @@
//! Answers to questions about a finished analysis (`questions` rows). The
//! model of the analysis answers, seeing the chart data the analysis was
//! written from, the analysis itself and the earlier questions about it.
//! Retries and refunds work as for analyses.
//! question model answers, seeing the chart data the analysis was written
//! from, the analysis itself and the earlier questions about it. Retries,
//! fallback and refunds work as for analyses.
use std::time::{Duration, Instant};
@@ -10,7 +10,7 @@ use uuid::Uuid;
use super::openrouter::{Completion, LlmError};
use super::prompt::{self, Kind};
use super::{Analyzer, backoff};
use super::{Analyzer, Next, active_model, next_step};
/// The earlier questions and answers given to the model, at most this many.
const HISTORY: i64 = 6;
@@ -25,6 +25,10 @@ pub struct QuestionJob {
pub prompt_version: String,
pub attempts: i32,
pub created_at: time::OffsetDateTime,
pub fallback_model: Option<String>,
pub on_fallback: bool,
/// The token of this attempt (see `Job::started_at`).
pub started_at: time::OffsetDateTime,
}
impl Analyzer {
@@ -34,7 +38,8 @@ impl Analyzer {
"UPDATE questions SET status = 'running', started_at = now(), attempts = attempts + 1 \
WHERE id = (SELECT id FROM questions WHERE status = 'pending' AND next_attempt_at <= now() \
ORDER BY next_attempt_at LIMIT 1 FOR UPDATE SKIP LOCKED) \
RETURNING id, analysis_id, question, language, model, prompt_version, attempts, created_at",
RETURNING id, analysis_id, question, language, model, prompt_version, attempts, created_at, \
fallback_model, on_fallback, started_at",
)
.fetch_optional(&self.db)
.await?;
@@ -46,8 +51,9 @@ impl Analyzer {
async fn question_prompt(&self, job: &QuestionJob) -> Result<prompt::Prompt, LlmError> {
let db_err = |e: sqlx::Error| LlmError::Transient(format!("database: {e}"));
let (kind, chart_id, forecast_id, content): (String, Option<Uuid>, Option<Uuid>, Option<Value>) =
sqlx::query_as("SELECT kind, chart_id, forecast_id, content FROM analyses WHERE id = $1")
type Row = (String, Option<Uuid>, Option<Uuid>, Option<Uuid>, Option<Value>);
let (kind, chart_id, synastry_id, forecast_id, content): Row =
sqlx::query_as("SELECT kind, chart_id, synastry_id, forecast_id, content FROM analyses WHERE id = $1")
.bind(job.analysis_id)
.fetch_optional(&self.db)
.await
@@ -57,6 +63,7 @@ impl Analyzer {
let content = content.ok_or_else(|| LlmError::Permanent("the analysis has no text".into()))?;
let chart_text = match kind {
Kind::Forecast => self.forecast_text(forecast_id).await?,
Kind::Synastry => self.synastry_text(synastry_id).await?,
_ => self.natal_text(chart_id).await?,
};
let analysis = prompt::to_markdown(kind, &job.language, &content);
@@ -88,12 +95,24 @@ impl Analyzer {
/// Answers one claimed question and records the outcome.
pub async fn handle_question(&self, job: QuestionJob) {
let started = Instant::now();
let result = match self.question_prompt(&job).await {
Ok(p) => self.llm.complete(&job.model, &p).await.map(|mut c| {
let work = async {
match self.question_prompt(&job).await {
Ok(p) => {
let model = active_model(&job.model, job.fallback_model.as_deref(), job.on_fallback);
self.llm.complete(model, &p).await.map(|mut c| {
prompt::polish(&job.language, &mut c.content);
c
}),
})
}
Err(e) => Err(e),
}
};
let result = tokio::select! {
result = work => result,
() = self.superseded("questions", job.id, job.started_at) => {
tracing::info!(id = %job.id, "answer restarted by an admin; this attempt is dropped");
return;
}
};
if let Err(e) = self.finish_question(&job, result, started.elapsed()).await {
tracing::error!(id = %job.id, error = %e, "saving the answer failed");
@@ -113,7 +132,7 @@ impl Analyzer {
sqlx::query(
"UPDATE questions SET status = 'done', answer = $2, model_used = $3, input_tokens = $4, \
output_tokens = $5, cost_usd = $6, error = NULL, completed_at = now() \
WHERE id = $1 AND status = 'running'",
WHERE id = $1 AND status = 'running' AND started_at = $7",
)
.bind(job.id)
.bind(&answer)
@@ -121,6 +140,7 @@ impl Analyzer {
.bind(c.input_tokens)
.bind(c.output_tokens)
.bind(c.cost_usd)
.bind(job.started_at)
.execute(&self.db)
.await?;
tracing::info!(
@@ -128,36 +148,71 @@ impl Analyzer {
secs = took.as_secs(), "answer done"
);
}
Err(LlmError::Transient(message)) if job.attempts < self.max_attempts => {
let wait = backoff(job.attempts);
Err(e) => {
let can_fall_back = !job.on_fallback && job.fallback_model.is_some();
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, \
next_attempt_at = now() + make_interval(secs => $3) WHERE id = $1 AND status = 'running'",
next_attempt_at = now() + make_interval(secs => $3) \
WHERE id = $1 AND status = 'running' AND started_at = $4",
)
.bind(job.id)
.bind(&message)
.bind(e.message())
.bind(wait.as_secs_f64())
.bind(job.started_at)
.execute(&self.db)
.await?;
tracing::warn!(id = %job.id, attempts = job.attempts, error = %message, "answer will be retried");
tracing::warn!(id = %job.id, attempts = job.attempts, error = %e.message(), "answer will be retried");
}
Err(e) => {
self.fail_question(job.id, e.message()).await?;
Next::Fallback => {
sqlx::query(
"UPDATE questions SET status = 'pending', error = $2, on_fallback = true, attempts = 0, \
next_attempt_at = now() WHERE id = $1 AND status = 'running' AND started_at = $3",
)
.bind(job.id)
.bind(e.message())
.bind(job.started_at)
.execute(&self.db)
.await?;
tracing::warn!(
id = %job.id, model = %job.model, error = %e.message(),
"the chosen model failed, the default model answers"
);
}
Next::Fail => {
self.fail_question(job.id, job.started_at, e.message()).await?;
tracing::error!(id = %job.id, attempts = job.attempts, error = %e.message(), "answer failed");
}
}
}
}
Ok(())
}
/// Marks the question failed and gives its unit back (once).
async fn fail_question(&self, id: Uuid, message: &str) -> Result<(), sqlx::Error> {
async fn fail_question(
&self,
id: Uuid,
started_at: time::OffsetDateTime,
message: &str,
) -> Result<(), sqlx::Error> {
let mut tx = self.db.begin().await?;
let row: Option<(Option<Uuid>, i32)> = sqlx::query_as(
"UPDATE questions SET status = 'failed', error = $2, completed_at = now() \
WHERE id = $1 AND status = 'running' RETURNING asked_by, credits_charged",
WHERE id = $1 AND status = 'running' AND started_at = $3 RETURNING asked_by, credits_charged",
)
.bind(id)
.bind(message)
.bind(started_at)
.fetch_optional(&mut *tx)
.await?;
if let Some((Some(user), units)) = row
+2 -1
View File
@@ -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<Vec<(&'static str, u64)>, sqlx::Error> {
+36 -1
View File
@@ -5,7 +5,38 @@ use std::time::Duration;
use anyhow::Context;
use lettre::message::Mailbox;
/// The jobs a worker process runs (`WORKER_TASKS`, comma-separated).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Tasks {
/// Sending the e-mails of `email_outbox`.
pub email: bool,
/// The hourly removal of expired data.
pub cleanup: bool,
/// Writing the analyses and answers with the LLM (both lanes).
pub analyses: bool,
}
impl Tasks {
pub const ALL: Tasks = Tasks { email: true, cleanup: true, analyses: true };
pub fn parse(raw: &str) -> anyhow::Result<Self> {
let mut tasks = Tasks { email: false, cleanup: false, analyses: false };
for name in raw.split(',').map(str::trim).filter(|n| !n.is_empty()) {
match name {
"email" => tasks.email = true,
"cleanup" => tasks.cleanup = true,
"analyses" => tasks.analyses = true,
other => anyhow::bail!("unknown task '{other}' in WORKER_TASKS (email, cleanup, analyses)"),
}
}
anyhow::ensure!(tasks != Tasks { email: false, cleanup: false, analyses: false }, "WORKER_TASKS names no task");
Ok(tasks)
}
}
pub struct Config {
/// What this process does; all of it by default.
pub tasks: Tasks,
pub database_url: String,
/// `smtp://host:port` (plain, e.g. Mailpit), `smtp://user:pass@host:587?tls=required`
/// (STARTTLS) or `smtps://...` (TLS). Without it, Amazon SES from the AWS
@@ -24,8 +55,10 @@ pub struct Config {
pub openrouter_base_url: String,
/// Frontend address, sent to OpenRouter as `HTTP-Referer`.
pub public_base_url: Option<String>,
/// Analyses written at the same time.
/// Detailed analyses and forecasts written at the same time (0: none).
pub analysis_concurrency: usize,
/// Summaries and answers written at the same time (0: none).
pub quick_concurrency: usize,
/// After this many failed attempts an analysis fails and is refunded.
pub max_analysis_attempts: i32,
}
@@ -55,6 +88,7 @@ impl Config {
},
};
Ok(Self {
tasks: var("WORKER_TASKS").map(|raw| Tasks::parse(&raw)).transpose()?.unwrap_or(Tasks::ALL),
database_url: var("DATABASE_URL").context("DATABASE_URL is required")?,
smtp_url,
smtp_about,
@@ -67,6 +101,7 @@ impl Config {
.unwrap_or_else(|| crate::analysis::openrouter::DEFAULT_BASE_URL.into()),
public_base_url: var("PUBLIC_BASE_URL"),
analysis_concurrency: parsed("ANALYSIS_CONCURRENCY", 4)?,
quick_concurrency: parsed("QUICK_CONCURRENCY", 2)?,
max_analysis_attempts: parsed("MAX_ANALYSIS_ATTEMPTS", 3)?,
})
}
+16 -3
View File
@@ -5,6 +5,9 @@
//! * hourly cleanup of expired sessions, tokens, invites and old e-mails
//! * writing the requested text analyses with an LLM (OpenRouter)
//!
//! `WORKER_TASKS` (e.g. `email,cleanup` or `analyses`) picks the jobs of one
//! process, so they can run in separate containers; all of them by default.
//!
//! Configuration: see [`config::Config`]; plus `BIND_ADDR` (default
//! `0.0.0.0:8082`, only `/healthz`), `LOG_FORMAT` and `RUST_LOG`.
//! `worker healthcheck` performs a local health check (for Docker);
@@ -91,7 +94,10 @@ async fn main() -> anyhow::Result<()> {
let (stop_tx, stop) = watch::channel(false);
let mut jobs = tokio::task::JoinSet::new();
let tasks = config.tasks;
tracing::info!(email = tasks.email, cleanup = tasks.cleanup, analyses = tasks.analyses, "worker tasks");
match &config.smtp_url {
_ if !tasks.email => {}
Some(url) => {
let delivery = email::Delivery::new(pool.clone(), email::Mailer::smtp(url)?, &config);
let via = config.smtp_about.clone().unwrap_or_else(|| "SMTP_URL".into());
@@ -101,17 +107,24 @@ async fn main() -> anyhow::Result<()> {
None => tracing::warn!("neither SMTP_URL nor SES credentials are set: e-mails stay in the outbox"),
}
match &config.openrouter_api_key {
_ if !tasks.analyses => {}
Some(key) => {
let llm =
analysis::openrouter::OpenRouter::new(&config.openrouter_base_url, key, config.public_base_url.clone());
let analyzer =
analysis::Analyzer::new(pool.clone(), llm, config.max_analysis_attempts, config.analysis_concurrency);
tracing::info!(concurrency = analyzer.concurrency, "analyses enabled");
let lanes = analysis::Lanes { quick: config.quick_concurrency, slow: config.analysis_concurrency };
if lanes.quick + lanes.slow == 0 {
tracing::warn!("QUICK_CONCURRENCY and ANALYSIS_CONCURRENCY are both 0: this worker writes no analyses");
} else {
let analyzer = analysis::Analyzer::new(pool.clone(), llm, config.max_analysis_attempts, lanes);
tracing::info!(quick = lanes.quick, slow = lanes.slow, "analyses enabled");
jobs.spawn(analysis::run(Arc::new(analyzer), config.poll_interval, stop.clone()));
}
}
None => tracing::warn!("OPENROUTER_API_KEY is not set: analyses stay pending"),
}
if tasks.cleanup {
jobs.spawn(cleanup::run(pool.clone(), stop.clone()));
}
let app = Router::new().route("/healthz", get(healthz)).with_state(pool);
let listener = tokio::net::TcpListener::bind(addr).await.with_context(|| format!("binding {addr}"))?;
+193 -6
View File
@@ -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<Uuid>,) =
@@ -222,6 +223,16 @@ async fn cleanup_removes_only_expired_data(db: PgPool) {
// --- analyses ----------------------------------------------------------------------------
#[test]
fn worker_tasks_are_chosen_by_name() {
use crate::config::Tasks;
let mail = Tasks::parse("email, cleanup").unwrap();
assert_eq!(mail, Tasks { email: true, cleanup: true, analyses: false });
assert_eq!(Tasks::parse("analyses").unwrap(), Tasks { email: false, cleanup: false, analyses: true });
assert!(Tasks::parse("emails").is_err());
assert!(Tasks::parse(" , ").is_err());
}
mod analyses {
use std::sync::{Arc, Mutex};
@@ -234,7 +245,7 @@ mod analyses {
use crate::analysis::openrouter::OpenRouter;
use crate::analysis::prompt::{Kind, schema, validate};
use crate::analysis::{Analyzer, backoff};
use crate::analysis::{Analyzer, Lane, Lanes, backoff};
/// Scripted replies (then the last one forever) and the requests received.
#[derive(Clone, Default)]
@@ -336,11 +347,11 @@ mod analyses {
}
fn analyzer(db: &PgPool, base_url: &str) -> Analyzer {
Analyzer::new(db.clone(), OpenRouter::new(base_url, "test-key", None), 3, 2)
Analyzer::new(db.clone(), OpenRouter::new(base_url, "test-key", None), 3, Lanes { quick: 1, slow: 2 })
}
async fn run_once(a: &Analyzer) -> bool {
match a.claim().await.unwrap() {
match a.claim(Lane::Slow).await.unwrap() {
Some(job) => {
a.handle(job).await;
true
@@ -463,10 +474,10 @@ mod analyses {
let a = analyzer(&db, &url);
// the analysis goes first; the preview only when nothing else is due
let job = a.claim().await.unwrap().expect("the analysis");
let job = a.claim(Lane::Slow).await.unwrap().expect("the analysis");
assert_eq!(job.id, analysis);
a.handle(job).await;
assert!(a.claim().await.unwrap().is_none());
assert!(a.claim(Lane::Slow).await.unwrap().is_none());
let job = a.claim_preview().await.unwrap().expect("the preview");
a.handle_preview(job).await;
let (status, title, model, credits): (String, Option<String>, Option<String>, i64) = sqlx::query_as(
@@ -533,6 +544,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")]
@@ -736,4 +759,168 @@ mod analyses {
.unwrap();
assert_eq!(refunds, vec![("question".to_string(), 1)]);
}
#[test]
fn the_chosen_model_gets_two_attempts_then_the_default_takes_over() {
use crate::analysis::openrouter::LlmError;
use crate::analysis::{Next, next_step};
let t = || LlmError::Transient("overloaded".into());
let p = || LlmError::Permanent("no such model".into());
assert_eq!(next_step(&t(), 1, 3, true), Next::Retry(backoff(1)));
assert_eq!(next_step(&t(), 2, 3, true), Next::Fallback);
assert_eq!(next_step(&p(), 1, 3, true), Next::Fallback);
// without a fallback (or already on it): retries, then failure
assert_eq!(next_step(&t(), 2, 3, false), Next::Retry(backoff(2)));
assert_eq!(next_step(&t(), 3, 3, false), Next::Fail);
assert_eq!(next_step(&p(), 1, 3, false), Next::Fail);
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn the_default_model_writes_when_the_chosen_one_fails(db: PgPool) {
let s = setup(&db).await;
let id = request_analysis(&db, &s).await;
sqlx::query("UPDATE analyses SET model = 'cheap/model', fallback_model = 'test/model' WHERE id = $1")
.bind(id)
.execute(&db)
.await
.unwrap();
let broken = json!({"title": "Csak cím"});
let (fake, url) = fake_openrouter(vec![reply(&broken), reply(&broken), reply(&content(Kind::Natal))]).await;
let a = analyzer(&db, &url);
assert!(run_once(&a).await);
make_due(&db, id).await;
assert!(run_once(&a).await); // second failure: the default model takes over at once
assert!(run_once(&a).await);
let (status, on_fallback, credits): (String, bool, i32) =
sqlx::query_as("SELECT status, on_fallback, credits_charged FROM analyses WHERE id = $1")
.bind(id)
.fetch_one(&db)
.await
.unwrap();
assert_eq!((status.as_str(), on_fallback, credits), ("done", true, 1));
assert!(refunds(&db, s.user).await.is_empty());
let models: Vec<String> =
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")]
async fn a_restarted_attempt_does_not_write_its_result(db: PgPool) {
let s = setup(&db).await;
let id = request_analysis(&db, &s).await;
let (_, url) = fake_openrouter(vec![reply(&content(Kind::Natal))]).await;
let a = analyzer(&db, &url);
let job = a.claim(Lane::Slow).await.unwrap().expect("a job");
// an admin restarts it while the worker is still writing it
sqlx::query("UPDATE analyses SET status = 'pending', started_at = NULL, attempts = 0 WHERE id = $1")
.bind(id)
.execute(&db)
.await
.unwrap();
a.handle(job).await;
let (status, content): (String, Option<Value>) =
sqlx::query_as("SELECT status, content FROM analyses WHERE id = $1").bind(id).fetch_one(&db).await.unwrap();
assert_eq!((status.as_str(), content), ("pending", None));
// the new attempt writes it
assert!(run_once(&a).await);
let status: String =
sqlx::query_scalar("SELECT status FROM analyses WHERE id = $1").bind(id).fetch_one(&db).await.unwrap();
assert_eq!(status, "done");
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn summaries_have_their_own_lane(db: PgPool) {
let s = setup(&db).await;
let natal = request_analysis(&db, &s).await;
let summary = |id: Uuid| {
sqlx::query(
"INSERT INTO analyses (id, kind, chart_id, requested_by, language, model, prompt_version, cache_key, \
credits_charged) \
VALUES ($1, 'summary', $2, $3, 'hu', 'test/model', 'v1', 'key', 0)",
)
.bind(id)
.bind(s.chart)
.bind(s.user)
};
let first = Uuid::now_v7();
summary(first).execute(&db).await.unwrap();
let a = analyzer(&db, "http://127.0.0.1:9");
// the quick lane takes the summary, never the detailed analysis
let id_of = |work: Option<crate::analysis::Work>| match work {
Some(crate::analysis::Work::Analysis(job)) => Some(job.id),
Some(_) => panic!("not an analysis"),
None => None,
};
assert_eq!(id_of(a.claim_quick().await.unwrap()), Some(first));
assert_eq!(id_of(a.claim_quick().await.unwrap()), None);
// the slow lane prefers the detailed analysis, then helps with quick work
let second = Uuid::now_v7();
summary(second).execute(&db).await.unwrap();
assert_eq!(id_of(a.claim_slow().await.unwrap()), Some(natal));
assert_eq!(id_of(a.claim_slow().await.unwrap()), Some(second));
assert_eq!(id_of(a.claim_slow().await.unwrap()), None);
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn answers_a_question_about_a_relationship_with_both_charts(db: PgPool) {
let s = setup(&db).await;
let response = fixture("synastry-response.json");
let (chart2, synastry, analysis) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
sqlx::query(
"INSERT INTO charts (id, owner_id, label, is_primary, kind, birth_data, result, chart_hash) \
VALUES ($1, $2, 'Partner', false, 'person', '{}', $3, 'hash2')",
)
.bind(chart2)
.bind(s.user)
.bind(&response["person2"])
.execute(&db)
.await
.unwrap();
sqlx::query(
"INSERT INTO synastries (id, owner_id, chart1_id, chart2_id, result, synastry_hash) \
VALUES ($1, $2, $3, $4, $5, 'sh')",
)
.bind(synastry)
.bind(s.user)
.bind(s.chart)
.bind(chart2)
.bind(&response)
.execute(&db)
.await
.unwrap();
sqlx::query(
"INSERT INTO analyses (id, kind, synastry_id, requested_by, language, model, prompt_version, cache_key, \
status, content) VALUES ($1, 'synastry', $2, $3, 'hu', 'test/model', 'v1', 'k', 'done', $4)",
)
.bind(analysis)
.bind(synastry)
.bind(s.user)
.bind(content(Kind::Synastry))
.execute(&db)
.await
.unwrap();
let id = ask(&db, analysis, s.user, "Mire figyeljünk egy vitában?", "pending", None).await;
let (fake, url) = fake_openrouter(vec![reply(&json!({"answer": "Arra, hogy..."}))]).await;
let a = analyzer(&db, &url);
assert!(answer_once(&a).await);
let status: String =
sqlx::query_scalar("SELECT status FROM questions WHERE id = $1").bind(id).fetch_one(&db).await.unwrap();
assert_eq!(status, "done");
let requests = fake.requests.lock().unwrap();
let user = requests[0]["messages"][1]["content"].as_str().unwrap();
assert!(user.starts_with("Képletadatok:\n\nSYNASTRY") && user.contains("Person 2"), "both charts");
assert!(!user.contains("Szeged") && !user.contains("Pécs"));
}
}