feat: Personas-Seite mit Übersicht, Editor, Wiederherstellen, Dirty-State und Testen-Verweis, Version 0.1.33 (#1199)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-29 16:04:29 +01:00
parent 56741a46b9
commit e0a70aeb11
9 changed files with 406 additions and 49 deletions

View File

@ -171,6 +171,7 @@ pub fn routes() -> Router<Arc<AppState>> {
)
.route("/ui/personas", get(personas::page))
.route("/ui/personas/speichern", post(personas::save))
.route("/ui/personas/wiederherstellen", post(personas::restore))
.route("/ui/personas.js", get(personas::script))
.route("/ui/modelle/probe", post(chat::preview))
.route("/ui/stimmen.js", get(stimmen::script))
@ -1334,6 +1335,10 @@ td.aktionen{white-space:nowrap}td.aktionen{position:sticky;right:0;background:va
.formular label{display:flex;flex-direction:column;gap:.25rem;font-size:.85rem;color:var(--muted)}
.formular .haken{flex-direction:row;align-items:center;gap:.45rem;color:var(--text)}.formular input[type=checkbox]{width:1.05rem;height:1.05rem;accent-color:var(--accent)}
.formular .breite{grid-column:1/-1}
.kennzahlen{display:grid;grid-template-columns:repeat(auto-fit,minmax(9rem,1fr));gap:.7rem;margin-top:.8rem}.kennzahl{background:var(--surface-2);border:1px solid var(--border);border-radius:var(--radius);padding:.6rem .8rem;display:flex;flex-direction:column;gap:.1rem;min-width:0}.kennzahl b{font-size:1.25rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.persona-suche{display:block;margin-bottom:.9rem}.persona-suche input{width:100%}.persona-karten{display:grid;grid-template-columns:repeat(auto-fill,minmax(16rem,1fr));gap:.9rem}.persona-karte{background:var(--surface-2);border:1px solid var(--border);border-radius:var(--radius);padding:.9rem 1rem;display:flex;flex-direction:column;gap:.5rem;min-width:0}.persona-karte h3{margin:0;overflow-wrap:anywhere}.persona-karte .zeile{margin-top:auto}
.persona-layout{display:grid;grid-template-columns:11rem minmax(0,1fr);gap:1.1rem;align-items:start}.persona-nav{position:sticky;top:.8rem;display:flex;flex-direction:column;gap:.4rem;margin:0}.persona-form textarea{width:100%;min-height:8rem;font:inherit;resize:vertical}.persona-form h3{margin:.8rem 0 0;font-size:1rem}.persona-form h3:first-child{margin-top:0}.persona-leiste{margin-top:.4rem}.zeichenzahl{display:block;text-align:right}.persona-form [hidden],.persona-karten [hidden]{display:none}
@media (max-width:48rem){.persona-layout{grid-template-columns:1fr}.persona-nav{position:static;flex-direction:row;flex-wrap:wrap}}
.unter{display:block;white-space:nowrap;margin-top:.15rem}.blase.assistant:empty,.blase span:empty{min-width:1.5rem;min-height:1.2em;display:inline-block}
details.card summary{cursor:pointer;font-weight:600}details.card[open] summary{margin-bottom:.8rem}
.geheim{font-family:ui-monospace,"JetBrains Mono",Menlo,monospace;font-size:1rem;word-break:break-all;background:var(--bg);border:1px dashed var(--accent);border-radius:10px;padding:.7rem .9rem;user-select:all}

View File

@ -15,7 +15,7 @@ use axum::http::{HeaderMap, StatusCode};
use axum::response::{IntoResponse, Response};
use serde_json::{Value, json};
use super::{esc, guard, html, layout, redirect, secure, viewer};
use super::{esc, form_field, guard, html, layout, redirect, secure, viewer};
use crate::access::{AccessSlot, RequestId, StartedAt};
use crate::error::ApiError;
use crate::state::AppState;
@ -30,7 +30,11 @@ const DEFAULT_MAX_TOKENS: u64 = 4096;
const MAX_SPEECH_CHARS: usize = 4000;
const MAX_VOICE_CHARS: usize = 100;
pub(super) async fn page(State(state): State<Arc<AppState>>, headers: HeaderMap) -> Response {
pub(super) async fn page(
State(state): State<Arc<AppState>>,
headers: HeaderMap,
axum::extract::RawQuery(query): axum::extract::RawQuery,
) -> Response {
let Some(viewer) = viewer(&state, &headers) else {
return redirect("/ui/login");
};
@ -62,6 +66,12 @@ pub(super) async fn page(State(state): State<Arc<AppState>>, headers: HeaderMap)
}
}
let personas = state.store().personas(&viewer.user).unwrap_or_default();
// „Testen“ auf der Personas-Seite (→ #1199): ?persona=ID wählt sie vor, auch gegen den Standard; nur eigene.
let gewaehlt = query
.as_deref()
.and_then(|q| form_field(q.as_bytes(), "persona"))
.and_then(|v| v.parse::<i64>().ok())
.filter(|id| personas.iter().any(|p| p.id == *id));
// CHAT-01/Persona-Popover: Angaben je Persona für die Detailansicht (nur Angaben, kein Prompt-Text).
let persona_options: String = personas
.iter()
@ -73,7 +83,7 @@ pub(super) async fn page(State(state): State<Arc<AppState>>, headers: HeaderMap)
esc(p.voice.as_deref().unwrap_or("")),
p.systemprompt.chars().count() + p.style.chars().count(),
// Der Standard des Benutzers ist vorgewählt (→ #1248); „aus“ schaltet jede Persona ab.
if p.standard { " selected" } else { "" },
if gewaehlt.map_or(p.standard, |g| g == p.id) { " selected" } else { "" },
esc(&p.name),
if p.standard { " (Standard)" } else { "" }
)

View File

@ -38,23 +38,36 @@ fn fields(
models: &str,
voices: &[(String, bool)],
initial_hint: &str,
options: &str,
) -> String {
let get = |f: fn(&Persona) -> &str| p.map(f).unwrap_or("");
format!(
"<form method=\"post\" action=\"/ui/personas/speichern\" class=\"formular persona-form\" data-modelle=\"{models}\">\
<input type=\"hidden\" name=\"csrf\" value=\"{}\"><input type=\"hidden\" name=\"id\" value=\"{}\">\
<label>Name <input name=\"name\" maxlength=\"100\" required value=\"{}\"></label>\
<label>Systemprompt <textarea name=\"systemprompt\" maxlength=\"32000\" rows=\"5\">{}</textarea></label>\
<label>Stil-Text <textarea name=\"stil\" maxlength=\"16000\" rows=\"3\">{}</textarea></label>\
<label>Stimme (optional; nur persönlich freigegebene Stimmen) <select name=\"stimme\"><option value=\"\">Keine</option>{}</select></label>\
<label class=\"haken\"><input type=\"checkbox\" name=\"standard\" value=\"1\"{}> Als Standard verwenden (im Chat vorgewählt)</label>\
<p class=\"klein\">Eine Persona <b>ersetzt</b> den Systemprompt des Modells und den globalen Standard; sie wird nicht darauf gesetzt. Ohne Text in dieser Persona gelten sie weiter.</p>\
<p class=\"klein persona-hinweis\" role=\"status\">{}</p><button class=\"primary\" type=\"submit\">{}</button></form>",
<h3 id=\"identitaet\" class=\"breite\">Identität</h3>\
<label class=\"breite\">Name <input name=\"name\" maxlength=\"100\" required value=\"{}\"></label>\
<h3 id=\"verhalten\" class=\"breite\">Verhalten</h3>\
<label class=\"breite\">Systemprompt <textarea name=\"systemprompt\" maxlength=\"32000\" rows=\"16\">{}</textarea><span class=\"klein zeichenzahl\" data-fuer=\"systemprompt\" data-max=\"32000\"></span></label>\
<label class=\"breite\">Stil-Text <textarea name=\"stil\" maxlength=\"16000\" rows=\"5\">{}</textarea><span class=\"klein zeichenzahl\" data-fuer=\"stil\" data-max=\"16000\"></span></label>\
<p class=\"klein breite\">Eine Persona <b>ersetzt</b> den Systemprompt des Modells und den globalen Standard; sie wird nicht darauf gesetzt. Ohne Text in dieser Persona gelten sie weiter.</p>\
<h3 id=\"technik\" class=\"breite\">Technische Einstellungen</h3>\
<label>Modell für den Längenhinweis <select id=\"persona-modell\">{options}</select></label>\
<p class=\"klein breite persona-hinweis\" role=\"status\">{}</p>\
<label class=\"haken breite\"><input type=\"checkbox\" name=\"standard\" value=\"1\"{}> Als Standard verwenden (im Chat vorgewählt)</label>\
<h3 id=\"stimme\" class=\"breite\">Stimme</h3>\
<label class=\"breite\">Stimme (optional; nur persönlich freigegebene Stimmen) <select name=\"stimme\"><option value=\"\">Keine</option>{}</select></label>\
<div class=\"zeile breite persona-leiste\"><button class=\"primary\" type=\"submit\">{}</button><span class=\"chip warn persona-dirty\" role=\"status\" hidden>Nicht gespeicherte Änderungen</span><a href=\"/ui/personas\">Zur Übersicht</a></div></form>",
esc(csrf),
p.map(|p| p.id.to_string()).unwrap_or_default(),
esc(get(|p| &p.name)),
esc(get(|p| &p.systemprompt)),
esc(get(|p| &p.style)),
esc(initial_hint),
if p.is_some_and(|p| p.standard) {
" checked"
} else {
""
},
voices
.iter()
.map(|(name, saved)| format!(
@ -69,12 +82,6 @@ fn fields(
esc(name)
))
.collect::<String>(),
if p.is_some_and(|p| p.standard) {
" checked"
} else {
""
},
esc(initial_hint),
if p.is_some() {
"Neue Version speichern"
} else {
@ -83,6 +90,68 @@ fn fields(
)
}
/// Übersicht (→ #1199, R1): Kennzahlen aus echten Daten, Suche, eine Karte je Persona. Ohne Prompt-Texte.
fn overview(list: &[Persona], store: &nexus_store::Store, user: &str) -> String {
let versions: Vec<usize> = list
.iter()
.map(|p| {
store
.persona_versions(user, p.id)
.map(|v| v.len())
.unwrap_or(1)
})
.collect();
let tile = |label: &str, value: String| {
format!(
"<div class=\"kennzahl\"><span class=\"klein\">{label}</span><b>{}</b></div>",
esc(&value)
)
};
let standard = list
.iter()
.find(|p| p.standard)
.map(|p| p.name.clone())
.unwrap_or_else(|| "keine".into());
let mut out = format!(
"<section class=\"card\"><div class=\"zeile\"><h2>Meine Personas</h2><div class=\"rechts\"><a class=\"primary\" role=\"button\" href=\"/ui/personas?neu=1\">Neue Persona</a></div></div>\
<p class=\"klein\">Nur du siehst diese Texte, auch Admins nicht. Jede Bearbeitung legt eine neue Version an.</p>\
<div class=\"kennzahlen\">{}{}{}{}</div></section>",
tile("Personas", list.len().to_string()),
tile(
"Gespeicherte Versionen",
versions.iter().sum::<usize>().to_string()
),
tile(
"Mit Stimme",
list.iter()
.filter(|p| p.voice.is_some())
.count()
.to_string()
),
tile("Standard", standard),
);
if list.is_empty() {
out.push_str("<section class=\"card\"><p>Noch keine Persona. Lege die erste mit „Neue Persona“ an.</p></section>");
return out;
}
out.push_str("<section class=\"card\"><label class=\"persona-suche\"><span class=\"vh\">Personas durchsuchen</span><input type=\"search\" id=\"persona-suche\" placeholder=\"Personas durchsuchen\" autocomplete=\"off\"></label><div class=\"persona-karten\">");
for (p, n) in list.iter().zip(versions) {
out.push_str(&format!(
"<article class=\"persona-karte\" data-name=\"{}\"><h3>{}</h3><div class=\"chips\"><span class=\"chip\">Version {}</span><span class=\"chip\">{} gespeichert</span><span class=\"chip\">Privat</span>{}{}</div>\
<div class=\"zeile\"><a href=\"/ui/personas?id={}\">Bearbeiten</a><a href=\"/ui/personas?id={}#versionen\">Versionen</a><a href=\"/ui/chat?persona={}\">Testen</a></div></article>",
esc(&p.name.to_lowercase()),
esc(&p.name),
p.version,
n,
if p.standard { "<span class=\"chip accent\">Standard</span>" } else { "" },
p.voice.as_deref().map(|v| format!("<span class=\"chip\">Stimme: {}</span>", esc(v))).unwrap_or_default(),
p.id, p.id, p.id,
));
}
out.push_str("</div><p class=\"klein\" id=\"persona-leer\" hidden>Keine Persona passt zur Suche.</p></section>");
out
}
pub(super) async fn page(
State(state): State<Arc<AppState>>,
headers: HeaderMap,
@ -95,6 +164,10 @@ pub(super) async fn page(
.as_deref()
.and_then(|q| form_field(q.as_bytes(), "id"))
.and_then(|v| v.parse::<i64>().ok());
let neu = query
.as_deref()
.and_then(|q| form_field(q.as_bytes(), "neu"))
.is_some();
let store = state.store();
let list = store.personas(&user.user).unwrap_or_default();
let selected = id.and_then(|id| store.persona(&user.user, id, None).ok().flatten());
@ -145,31 +218,48 @@ pub(super) async fn page(
.iter()
.map(|(name, _, _)| format!("<option value=\"{}\">{}</option>", esc(name), esc(name)))
.collect();
let mut body = format!(
"<section class=\"card\"><h2>Meine Personas</h2><p class=\"klein\">Nur du siehst diese Texte, auch Admins nicht. Jede Bearbeitung legt eine neue Version an.</p><ul>{}</ul></section>",
list.iter()
.map(|p| format!(
"<li><a href=\"/ui/personas?id={}\">{}</a> · Version {}{}</li>",
p.id,
esc(&p.name),
p.version,
if p.standard {
" · <b>Standard</b>"
let mut body = String::new();
if selected.is_none() && !neu {
body.push_str(&overview(&list, &store, &user.user));
} else {
let titel = selected
.as_ref()
.map_or("Neue Persona".to_string(), |p| p.name.clone());
body.push_str(&format!(
"<p><a href=\"/ui/personas\">← Alle Personas</a></p><div class=\"persona-layout\"><nav class=\"persona-nav card\" aria-label=\"Abschnitte\"><a href=\"#identitaet\">Identität</a><a href=\"#verhalten\">Verhalten</a><a href=\"#technik\">Technisch</a><a href=\"#stimme\">Stimme</a>{}</nav><div>",
if selected.is_some() { "<a href=\"#versionen\">Versionen</a>" } else { "" }
));
body.push_str(&format!(
"<section class=\"card\"><h2>{}</h2>{}</section>",
esc(&titel),
fields(
selected.as_ref(),
&user.csrf,
&model_data,
&store.approved_voices(&user.user).unwrap_or_default(),
&initial_hint,
&options
)
));
if let Some(p) = selected {
body.push_str(&format!("<section class=\"card\" id=\"versionen\"><h2>Versionen von {}</h2><p class=\"klein\">Ältere Versionen bleiben lesbar und unverändert. „Als neue Version wiederherstellen“ legt den alten Stand als neueste Version an; nichts wird überschrieben.</p>", esc(&p.name)));
for v in versions {
let restore = if v.version == p.version {
"<p class=\"klein\">Das ist die aktuelle Version.</p>".to_string()
} else {
""
}
))
.collect::<String>()
);
body.push_str(&format!("<section class=\"card\"><h2>{}</h2><label>Modell für Längenhinweis <select id=\"persona-modell\">{options}</select></label>{}</section>",
if selected.is_some() {"Bearbeiten"} else {"Neue Persona"}, fields(selected.as_ref(), &user.csrf, &model_data, &store.approved_voices(&user.user).unwrap_or_default(), &initial_hint)));
if let Some(p) = selected {
body.push_str(&format!("<section class=\"card\"><h2>Versionen von {}</h2><p class=\"klein\">Ältere Versionen bleiben lesbar und unverändert.</p>", esc(&p.name)));
for v in versions {
body.push_str(&format!("<details><summary>Version {} · {}</summary><dl class=\"daten\"><dt>Systemprompt</dt><dd class=\"pfad\">{}</dd><dt>Stil-Text</dt><dd class=\"pfad\">{}</dd><dt>Stimme</dt><dd>{}</dd></dl></details>",
v.version, esc(&v.name), esc(&v.systemprompt), esc(&v.style), esc(v.voice.as_deref().unwrap_or("Keine"))));
format!(
"<form method=\"post\" action=\"/ui/personas/wiederherstellen\"><input type=\"hidden\" name=\"csrf\" value=\"{}\"><input type=\"hidden\" name=\"id\" value=\"{}\"><input type=\"hidden\" name=\"version\" value=\"{}\"><button type=\"submit\">Als neue Version wiederherstellen</button></form>",
esc(&user.csrf),
p.id,
v.version
)
};
body.push_str(&format!("<details><summary>Version {} · {}</summary><dl class=\"daten\"><dt>Systemprompt</dt><dd class=\"pfad\">{}</dd><dt>Stil-Text</dt><dd class=\"pfad\">{}</dd><dt>Stimme</dt><dd>{}</dd></dl>{restore}</details>",
v.version, esc(&v.name), esc(&v.systemprompt), esc(&v.style), esc(v.voice.as_deref().unwrap_or("Keine"))));
}
body.push_str("</section>");
}
body.push_str("</section>");
body.push_str("</div></div>");
}
body.push_str("<script src=\"/ui/personas.js\"></script>");
html(
@ -242,6 +332,52 @@ pub(super) async fn save(
}
}
/// Alte Version als neue Version speichern (→ #1199, R1). Es wird nichts überschrieben; die Standard-Markierung bleibt.
pub(super) async fn restore(
State(state): State<Arc<AppState>>,
headers: HeaderMap,
body: Bytes,
) -> Response {
let user = match guard(
&state,
&headers,
form_field(&body, "csrf").as_deref(),
false,
) {
Ok(u) => u,
Err(e) => return *e,
};
let number = |name| form_field(&body, name).and_then(|v| v.parse::<i64>().ok());
let (Some(id), Some(version)) = (number("id"), number("version")) else {
return super::refused(StatusCode::BAD_REQUEST, "Ungültige Persona oder Version.");
};
let old = match state.store().persona(&user.user, id, Some(version)) {
Ok(Some(p)) => p,
_ => {
return super::refused(
StatusCode::NOT_FOUND,
"Persona oder Version nicht gefunden.",
);
}
};
let voice = old.voice.as_deref().map(|v| (v, old.saved_voice));
match state.store().save_persona(
&user.user,
Some(id),
&old.name,
&old.systemprompt,
&old.style,
voice,
) {
Ok(Some(p)) => redirect(&format!("/ui/personas?id={}#versionen", p.id)),
Ok(None) => super::refused(StatusCode::NOT_FOUND, "Persona nicht gefunden."),
Err(_) => super::refused(
StatusCode::BAD_REQUEST,
"Wiederherstellen nicht möglich: Die Stimme der alten Version ist nicht mehr freigegeben.",
),
}
}
pub(super) async fn script() -> Response {
super::secure(Response::builder())
.header(