feat: edit validated per-model engine start profiles (#1070)

This commit is contained in:
2026-11-17 15:08:41 +01:00
parent 51604eebf6
commit 8ec8d6af7f
22 changed files with 1404 additions and 16 deletions

View File

@ -35,6 +35,7 @@ struct FixedEngine {
stops: AtomicUsize,
health_checks: AtomicUsize,
health_timeout: std::sync::atomic::AtomicBool,
measured_vram: std::sync::atomic::AtomicU64,
delay: Duration,
fail: bool,
}
@ -91,7 +92,11 @@ impl Engine for FixedEngine {
}
}
async fn measure(&self, _i: &InstanceHandle) -> Usage {
Usage::default()
let mb = self.measured_vram.load(Ordering::SeqCst);
Usage {
vram_mb: (mb > 0).then_some(mb),
..Usage::default()
}
}
}
@ -269,6 +274,7 @@ async fn gateway_with(
stops: AtomicUsize::new(0),
health_checks: AtomicUsize::new(0),
health_timeout: std::sync::atomic::AtomicBool::new(false),
measured_vram: std::sync::atomic::AtomicU64::new(0),
delay: Duration::from_millis(delay_ms),
fail,
});
@ -3375,3 +3381,323 @@ async fn logs_zeitraum_key_engine_abbruch_und_freitext_filtern() {
400
);
}
#[tokio::test]
async fn startprofile_nur_admin_audit_typpruefung_und_standard_ohne_neustart() {
let gw = gateway(0, false).await;
let (user, csrf_user) = ui_session(&gw, &gw.key_ui).await;
let (_, _, page) = ui_get(&gw, "/ui/modelle", Some(&user)).await;
assert!(!page.contains("Startparameter speichern"));
assert_eq!(
ui_post(
&gw,
"/ui/modelle/startparameter",
&user,
&format!("csrf={csrf_user}&name=bonsai&p.context=8192")
)
.await
.0,
403
);
let (admin, csrf) = ui_session(&gw, &gw.key_admin).await;
let (_, _, page) = ui_get(&gw, "/ui/modelle", Some(&admin)).await;
assert!(page.contains("Startparameter speichern"));
assert!(page.contains("Standard wiederherstellen"));
assert!(page.contains("name=\"p.context\""));
let _ = gw
.chat(Some(&gw.key), None, &chat_body("bonsai", false))
.await
.text()
.await;
gw.state.store().set_measured_vram("bonsai", 777).unwrap();
let (status, _, _) = ui_post(
&gw,
"/ui/modelle/startparameter",
&admin,
&format!("csrf={csrf}&name=bonsai&p.context=8192&p.slots=4&p.kv_key=q8_0"),
)
.await;
assert_eq!(status, 303);
let plan = gw.state.store().start_plan("bonsai").unwrap().unwrap();
assert_eq!(
plan.start_parameters.get("context").map(String::as_str),
Some("8192")
);
assert_eq!(
plan.start_parameters.get("slots").map(String::as_str),
Some("4")
);
assert_eq!((starts(&gw), stops(&gw)), (1, 0));
assert!(
gw.state
.store()
.planning_overview()
.unwrap()
.iter()
.find(|r| r.0 == "bonsai")
.unwrap()
.2
.is_none()
);
for input in [
"p.context=511",
"p.slots=17",
"p.cpu_moe=true&p.cpu_moe_layers=1",
"p.host=0.0.0.0",
"args=--api-key+nx-secret",
"p.batch=32&p.ubatch=64",
"p.context=8192&p.context=4096",
] {
let (status, _, body) = ui_post(
&gw,
"/ui/modelle/startparameter",
&admin,
&format!("csrf={csrf}&name=bonsai&{input}"),
)
.await;
assert_eq!(status, 400, "{input}: {body}");
assert!(!body.contains("nx-secret"));
assert_eq!(
gw.state
.store()
.start_parameters("bonsai")
.unwrap()
.unwrap()
.get("context")
.map(String::as_str),
Some("8192")
);
}
assert_eq!(
ui_post(
&gw,
"/ui/modelle/startparameter",
&admin,
&format!("csrf={csrf}&name=unbekannt&p.context=8192")
)
.await
.0,
404
);
assert_eq!(
ui_post(
&gw,
"/ui/modelle/startparameter",
&admin,
"csrf=falsch&name=bonsai"
)
.await
.0,
403
);
let (status, _, _) = ui_post(
&gw,
"/ui/modelle/startparameter",
&admin,
&format!("csrf={csrf}&name=bonsai&modus=standard"),
)
.await;
assert_eq!(status, 303);
assert!(
gw.state
.store()
.start_parameters("bonsai")
.unwrap()
.unwrap()
.is_empty()
);
let audit = gw.state.store().recent_audit(100).unwrap();
for action in [
"model.profile.set",
"model.profile.restore",
"model.profile.rejected",
] {
assert!(
audit
.iter()
.any(|r| r.action == action && r.target.as_deref() == Some("bonsai"))
);
}
assert!(
audit
.iter()
.all(|r| !r.target.as_deref().unwrap_or("").contains("nx-secret"))
);
}
#[tokio::test]
async fn strata_startprofil_wird_mit_eigener_parameterliste_gespeichert() {
let gw = gateway(0, false).await;
gw.state
.store()
.register_llm(&NewLlm {
name: "strata-modell".into(),
engine: "strata".into(),
path: "/secret/config.json".into(),
quantization: None,
size_bytes: None,
gpus: vec![0, 1],
context: None,
vram_mb: None,
ram_mb: None,
idle_secs: None,
enabled: true,
})
.unwrap();
let (admin, csrf) = ui_session(&gw, &gw.key_admin).await;
let (status, _, _) = ui_post(
&gw,
"/ui/modelle/startparameter",
&admin,
&format!(
"csrf={csrf}&name=strata-modell&p.context=131072&p.kv=int8&p.slots=2&p.spec_min_p=0.5"
),
)
.await;
assert_eq!(status, 303);
let p = gw
.state
.store()
.start_plan("strata-modell")
.unwrap()
.unwrap()
.start_parameters;
assert_eq!(p.get("kv").map(String::as_str), Some("int8"));
assert_eq!(
ui_post(
&gw,
"/ui/modelle/startparameter",
&admin,
&format!("csrf={csrf}&name=strata-modell&p.gpu=1")
)
.await
.0,
303
);
assert_eq!(
gw.state
.store()
.start_plan("strata-modell")
.unwrap()
.unwrap()
.gpus,
vec![1]
);
assert_eq!(
ui_post(
&gw,
"/ui/modelle/startparameter",
&admin,
&format!("csrf={csrf}&name=strata-modell&p.gpu=1,1")
)
.await
.0,
400
);
assert_eq!(
ui_post(
&gw,
"/ui/modelle/startparameter",
&admin,
&format!("csrf={csrf}&name=strata-modell&p.kv_resident=1024")
)
.await
.0,
400
);
assert_eq!(
ui_post(
&gw,
"/ui/modelle/startparameter",
&admin,
&format!("csrf={csrf}&name=strata-modell&p.spec_min_p=2")
)
.await
.0,
400
);
}
#[tokio::test]
#[ignore = "Benötigt Chromium und Node.js; separat ausführen."]
async fn verwaltung_im_chromium_prueft_startprofile_und_logsuche() {
let gw = gateway(0, false).await;
let (cookie, _) = ui_session(&gw, &gw.key_admin).await;
let output = tokio::process::Command::new("node")
.arg(concat!(
env!("CARGO_MANIFEST_DIR"),
"/tests/chat_browser.mjs"
))
.env("NEXUS_TEST_BASE", &gw.base)
.env("NEXUS_TEST_COOKIE", cookie)
.env("NEXUS_TEST_ADMIN", "1")
.output()
.await
.unwrap();
assert!(
output.status.success(),
"{}{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
println!("{}", String::from_utf8_lossy(&output.stdout));
}
#[tokio::test]
async fn profilwechsel_waehrend_des_ladens_uebernimmt_nicht_den_alten_vram_messwert() {
let gw = Arc::new(gateway(300, false).await);
gw.engine.measured_vram.store(777, Ordering::SeqCst);
let running = {
let gw = gw.clone();
tokio::spawn(async move {
gw.chat(Some(&gw.key), None, &chat_body("bonsai", false))
.await
.text()
.await
.unwrap()
})
};
wait_until("Alter Start läuft", || starts(&gw) == 1).await;
gw.state
.store()
.save_start_parameters(
"bonsai",
&nexus_core::startparams::StartParameters::from([("context".into(), "8192".into())]),
"test",
false,
)
.unwrap();
running.await.unwrap();
assert!(
gw.state
.store()
.planning_overview()
.unwrap()
.iter()
.find(|r| r.0 == "bonsai")
.unwrap()
.2
.is_none()
);
gw.state.runtime.unload("bonsai").unwrap();
wait_until("Entladen", || {
gw.state.runtime.scheduler_view().instances.is_empty()
})
.await;
let _ = gw
.chat(Some(&gw.key), None, &chat_body("bonsai", false))
.await
.text()
.await;
assert_eq!(
gw.state
.store()
.planning_overview()
.unwrap()
.iter()
.find(|r| r.0 == "bonsai")
.unwrap()
.2,
Some(777)
);
}

View File

@ -26,12 +26,15 @@ try {
let id = 0;
const pending = new Map();
const requests = [];
const loaded = new Set();
socket.onmessage = event => {
const data = JSON.parse(event.data);
if (data.id) {
const call = pending.get(data.id);
pending.delete(data.id);
if (data.error) { call.reject(new Error(data.error.message)); } else { call.resolve(data.result); }
} else if (data.method === 'Page.lifecycleEvent' && data.params.name === 'load') {
loaded.add(data.params.loaderId);
} else if (data.method === 'Network.requestWillBeSent' && data.params.request.url.endsWith('/ui/chat/senden')) {
requests.push(JSON.parse(data.params.request.postData));
}
@ -48,7 +51,7 @@ try {
const page = (method, params) => call(method, params, sessionId);
const evaluate = async expression => {
const result = await page('Runtime.evaluate', { expression, returnByValue: true });
if (result.exceptionDetails) { throw new Error(result.exceptionDetails.text); }
if (result.exceptionDetails) { throw new Error(result.exceptionDetails.exception?.description || result.exceptionDetails.text); }
return result.result.value;
};
async function until(expression) {
@ -61,10 +64,47 @@ try {
}
await page('Network.enable');
await page('Page.enable');
await page('Page.setLifecycleEventsEnabled', { enabled: true });
async function navigate(url) {
const nav = await page('Page.navigate', { url });
const deadline = Date.now() + 15000;
while (!loaded.has(nav.loaderId)) {
if (Date.now() > deadline) { throw new Error('Browserseite lädt nicht vollständig'); }
await new Promise(resolve => setTimeout(resolve, 20));
}
}
const cookie = process.env.NEXUS_TEST_COOKIE.split('=');
await page('Network.setCookie', { name: cookie[0], value: cookie.slice(1).join('='),
url: `${process.env.NEXUS_TEST_BASE}/ui`, path: '/ui', httpOnly: true, sameSite: 'Strict' });
await page('Page.navigate', { url: `${process.env.NEXUS_TEST_BASE}/ui/chat` });
if (process.env.NEXUS_TEST_ADMIN === '1') {
const goModels = async () => {
await navigate(`${process.env.NEXUS_TEST_BASE}/ui/modelle`);
await until(`!!document.querySelector('button[title="Bearbeiten"]')`);
await evaluate(`document.querySelector('button[title="Bearbeiten"]').click(); Array.from(document.querySelectorAll('dialog[open] summary')).find(s=>s.textContent==='Startparameter').click()`);
await until(`!!document.querySelector('dialog[open] input[name="p.context"]')`);
};
await goModels();
await evaluate(`var input=document.querySelector('dialog[open] input[name="p.context"]'); input.value='511'; input.form.requestSubmit()`);
await until(`document.body.textContent.includes('Typ oder Wertebereich')`);
await goModels();
await evaluate(`var input=document.querySelector('dialog[open] input[name="p.context"]'); input.value='8192'; document.querySelector('dialog[open] input[name="p.slots"]').value='4'; input.form.requestSubmit()`);
await until(`location.search.includes('startprofil') && !!document.querySelector('button[title="Bearbeiten"]')`);
await goModels();
assert.equal(await evaluate(`document.querySelector('dialog[open] input[name="p.context"]').value`), '8192');
await evaluate(`document.querySelector('dialog[open] input[name="modus"][value="standard"]').form.requestSubmit()`);
await until(`location.search.includes('startprofil') && !!document.querySelector('button[title="Bearbeiten"]')`);
await goModels();
assert.equal(await evaluate(`document.querySelector('dialog[open] input[name="p.context"]').value`), '');
await navigate(`${process.env.NEXUS_TEST_BASE}/ui/logs?quelle=audit&q=model.profile`);
await until(`!!document.querySelector('table[data-filtern="logs"]') && !!document.querySelector('.tabellenleiste')`);
assert.ok(await evaluate(`document.querySelector('table[data-filtern="logs"]').textContent.includes('model.profile.rejected')`));
assert.ok(await evaluate(`document.querySelector('table[data-filtern="logs"]').textContent.includes('model.profile.set')`));
assert.ok(await evaluate(`document.querySelector('table[data-filtern="logs"]').textContent.includes('model.profile.restore')`));
await evaluate(`document.querySelector('.tabellenleiste input').value='model.profile.set'; document.querySelector('.tabellenleiste input').dispatchEvent(new Event('input'))`);
assert.ok(await evaluate(`Array.from(document.querySelectorAll('table[data-filtern="logs"] tbody tr')).filter(r=>!r.hidden).every(r=>r.textContent.includes('model.profile.set'))`));
console.log('Chromium: Startprofil bearbeiten, ungültige Eingabe, Standard wiederherstellen, Audit und vorhandene Tabellenfilter geprüft.');
} else {
await navigate(`${process.env.NEXUS_TEST_BASE}/ui/chat`);
await until('!!document.getElementById("chat-denkstufe")');
assert.equal(await evaluate('document.getElementById("chat-denkstufe").value'), 'medium');
for (const effort of ['medium', 'none', 'low', 'high', '']) {
@ -80,12 +120,18 @@ try {
await until('!document.getElementById("chat-senden").disabled && document.getElementById("chat-status").textContent.includes("Denkstufe nicht unterstützt")');
assert.equal(requests.at(-1).reasoning_effort, 'medium');
console.log('Chromium: Ladephase, alle Denkstufen, fehlendes Feld, eingeklappte Denkphase und Fallback geprüft.');
}
} finally {
socket?.close();
if (chrome.pid && chrome.exitCode === null && chrome.signalCode === null) {
const ended = new Promise(resolve => chrome.once('exit', resolve));
chrome.kill('SIGTERM');
// Chromium soll Profil-Schreiber zuerst selbst beenden und leeren.
if (socket?.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify({ id: 0, method: 'Browser.close' }));
}
const fallback = setTimeout(() => chrome.kill('SIGTERM'), 3000);
await ended;
clearTimeout(fallback);
}
await rm(profile, { recursive: true, force: true });
socket?.close();
await rm(profile, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
}