Files
Athena-Deck/chat-test-ui.js
T

59 lines
16 KiB
JavaScript

window.ChatTestUI=(()=>{
const e=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
const gib=v=>v==null?'unbekannt':(v/1024).toFixed(2)+' GiB';
async function api(path,data){const r=await fetch('/api/v1/'+path,data===undefined?{}:{method:'POST',headers:{'Content-Type':'application/json','X-Athena-Deck':'1'},body:JSON.stringify(data)});const v=await r.json();if(!r.ok)throw Error(v.error||'Anfrage fehlgeschlagen');return v;}
function put(el,html){if(el._chatHtml!==html){el.innerHTML=html;el._chatHtml=html;}}
function html(){return `<section id="chat-test"><h2>Sprachmodell testen</h2><p>Chat mit deinem gespeicherten Profil, bei unterstützter Laufzeit auch mit Bildern, Dokumenten und Videos. Nutzt denselben Worker wie die API; keine öffentliche Profilfreigabe erforderlich.</p>
<form id="chat-test-form" class="card"><div class="form-grid"><label>Chatprofil<select id="chat-profile" required></select></label><label>Maximale Antwort-Token<input id="chat-limit" type="number" min="1" max="4096" value="1024" required></label><label>Denkstufe<select id="chat-effort"><option value="">Profilvorgabe</option value="none">Ohne Denken</option><option value="low">Wenig</option><option value="medium">Mittel</option><option value="high">Viel</option><option value="xhigh">Sehr viel</option></select></label></div>
<p id="chat-profile-info"></p><p id="chat-features" role="status"></p><div id="chat-transcript" aria-live="polite"></div><label>Nachricht<textarea id="chat-prompt" rows="4" maxlength="8000" required placeholder="Stelle eine Frage, optional zu angehängten Dateien …"></textarea></label>
<details><summary>Anhänge & Diagnoseoptionen</summary><div class="form-grid"><label>Dateien anhängen<input id="chat-files" type="file" multiple disabled></label><label>PDF-Seiten für neue Anhänge<input id="chat-pages" placeholder="Alle oder z. B. 1-5,8" maxlength="256"></label><label><input id="chat-logprobs" type="checkbox" disabled>Token-Wahrscheinlichkeiten mitliefern</label></div><div id="chat-attachments" aria-live="polite"></div><p class="small">Nur eingebettete Dateien, keine Serverpfade oder externen URLs. Höchstens 8 Anhänge und 32 MiB im gesamten Verlauf; Dokument je 16 MiB. Video: maximal 2 Bilder/s und 128 Frames, keine Tonspur. Token-Wahrscheinlichkeiten sind kein Fakten- oder Wahrheitsnachweis.</p></details>
<div class="card-actions"><button id="chat-send" disabled>Senden</button><button type="button" class="secondary" id="chat-clear">Neuer Chat</button></div><p class="small">Verlauf und Anhänge bleiben nur in dieser Ansicht und werden bei Profilwechsel oder Neuladen verworfen. Keine Chatdatei wird gespeichert.</p></form>
<p id="chat-message" role="alert"></p><section class="card"><h3>Laufzeit & Diagnose</h3><div id="chat-state" role="status"></div><div class="card-actions"><button class="secondary" id="chat-answer-now" disabled>Jetzt antworten</button><button class="secondary" id="chat-cancel" disabled>Test abbrechen</button><button class="secondary" id="chat-unload" disabled>Modell entladen</button></div><p>Jetzt antworten beendet nur das Denken dieses Tests und lässt seine Antwort weiterlaufen. Abbrechen beendet nur diesen Test. Entladen ist nur ohne aktive oder wartende Arbeit möglich.</p></section><section class="card"><h3>Speicherprüfung</h3><div id="chat-memory"></div><p class="small">Konfiguration und Prognose sind keine Vollkontext- oder Lastgarantie. <a class="link" href="#hardware">Hardware-Messwerte →</a></p></section></section>`;}
function metrics(j){
const t=j?.timings||{},u=j?.usage||{},num=(v,d=0)=>typeof v==='number'?v.toLocaleString('de-DE',{maximumFractionDigits:d}):'—',sec=v=>v==null?'—':num(v/1000,3)+' s';
return `<h4>Token & Geschwindigkeit · letzter Test</h4><table><thead><tr><th>Phase</th><th>Token</th><th>Dauer</th><th>Token/s</th></tr></thead><tbody><tr><td>Eingabe / Prefill (berechnet)</td><td>${num(t.prompt_n)}</td><td>${sec(t.prompt_ms)}</td><td>${num(t.prompt_per_second,2)}</td></tr><tr><td>Ausgabe / Generierung</td><td>${num(t.predicted_n)}</td><td>${sec(t.predicted_ms)}</td><td>${num(t.predicted_per_second,2)}</td></tr></tbody></table><p>Eingabe gesamt: ${num(u.prompt_tokens)} Token · Ausgabe gesamt: ${num(u.completion_tokens)} Token</p><p class="small">Messwerte des Modell-Backends. Prefill zählt neu berechnete Eingabe-Token; wiederverwendeter Kontext kann die Arbeit reduzieren. Ausgabe umfasst auch Reasoning. Modellladen und Wartezeit sind nicht Teil der Token/s. — = noch nicht verfügbar.</p>${j?.logprobs?.length?`<details><summary>Letzte Token-Wahrscheinlichkeiten</summary><p>Modellwahrscheinlichkeiten, kein Wahrheitsnachweis.</p><pre>${e(JSON.stringify(j.logprobs.slice(-20),null,2))}</pre></details>`:''}`;
}
function bind(){
const root=document.querySelector('#chat-test'),el=id=>root.querySelector('#'+id);let profiles=[],messages=[],turns=[],ownJob=null,finished=null,status=null,pending=false,caps={},attachments=[],filePending=false,controlPending=false,epoch=0,historyBytes=0,capabilityStamp=null;
const newSession=()=>`test-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;let session=newSession();
const notice=t=>{if(root.isConnected)el('chat-message').textContent=t;};
function transcript(){put(el('chat-transcript'),turns.map(t=>`<div class="note"><strong>${t.role==='user'?'Du':'Modell'}</strong><p class="chat-text">${e(t.content)}</p>${t.files?.length?`<p class="small">Anhänge: ${t.files.map(e).join(' · ')}</p>`:''}${t.reasoning?`<details><summary>Reasoning-Ausgabe</summary><pre>${e(t.reasoning)}</pre></details>`:''}</div>`).join(''));}
function pendingFiles(){put(el('chat-attachments'),attachments.map((a,n)=>`<p>${e(a.name)} · ${(a.size/1024).toFixed(1)} KiB <button type="button" class="secondary" data-remove="${n}">Entfernen</button></p>`).join(''));el('chat-attachments').querySelectorAll('[data-remove]').forEach(b=>b.onclick=()=>{if(pending||filePending||status?.job?.state==='running')return;attachments.splice(Number(b.dataset.remove),1);pendingFiles();});}
function selection(){const p=profiles.find(p=>p.id===el('chat-profile').value),running=status?.job?.state==='running',busy=pending||filePending||running,features=caps.available||[];
el('chat-profile-info').textContent=p?`${(p.parameters.context||0).toLocaleString('de-DE')} Token ${['basalt','strata'].includes(p.parameters.chat_runtime)?'pro Slot':'gesamt'} · ${p.parameters.slots} Slot(s)${p.blockers.length?' · '+p.blockers.join(' '):''}`:'Zuerst ein Sprachmodellprofil anlegen.';
el('chat-features').textContent=p?`${caps.runtime||p.parameters.chat_runtime||'llama.cpp'}${caps.version?' '+caps.version:''} · ${caps.loaded?'Modell geladen':'nicht geladen / installierte Möglichkeiten'} · ${features.join(', ')||'keine erweiterten Fähigkeiten bestätigt'}`:'';
el('chat-send').disabled=busy||!p?.runnable;['chat-profile','chat-clear','chat-effort','chat-pages'].forEach(id=>el(id).disabled=busy);
el('chat-cancel').disabled=!running||status?.job?.id!==ownJob;el('chat-answer-now').disabled=controlPending||!running||status?.job?.id!==ownJob||!status?.job?.can_answer_now;
const s=status?.scheduler;el('chat-unload').disabled=!s||!Number.isInteger(s.active_requests)||!Number.isInteger(s.waiting_requests)||s.active_requests!==0||s.waiting_requests!==0||s.switching===true||running;
el('chat-logprobs').disabled=busy||!features.includes('logprobs');if(!features.includes('logprobs'))el('chat-logprobs').checked=false;
let accept=[];if(p?.parameters.vision_projector)accept.push('.png','.jpg','.jpeg','.webp');if(features.includes('documents'))accept.push('.pdf','.docx','.pptx','.xlsx','.txt','.md','.csv','.json','.yaml','.yml','.xml');if(features.includes('video'))accept.push('.mp4','.webm','.mov','.mkv');el('chat-files').accept=accept.join(',');el('chat-files').disabled=busy||!accept.length;
}
async function capabilities(reset=true){const id=el('chat-profile').value,version=epoch;if(reset)caps={};selection();if(!id)return;try{const value=await api('chat-tests/capabilities?profile_id='+encodeURIComponent(id));if(root.isConnected&&version===epoch&&id===el('chat-profile').value){caps=value;selection();}}catch(error){notice(error.message);}}
function memory(plan,w,h){if(!plan)return '<p>Noch keine Speicherprognose vorhanden.</p>';if(['basalt','strata'].includes(plan.runtime))return `<p>${e(plan.runtime)} · ${(plan.context||0).toLocaleString('de-DE')} Token pro Slot · ${plan.slots} Slot(s) · KV ${e(plan.kv)} · Experten ${e(plan.experts)}</p><p>GPU(s): ${(plan.gpus||[]).map(g=>e((h.gpus||[]).find(x=>x.uuid===g)?.name||g)).join(', ')}</p><p>Konfigurierte CPU-Freigabe: ${(w.cpu_allowed||[]).map(e).join(', ')||'nicht gemeldet'}. Keine exklusive Reservierung.</p>`;return `<p><strong>${plan.fits?'Prognose passt einschließlich Reserve':'Prognose passt nicht in den verfügbaren Speicher'}</strong> · ${(plan.context||0).toLocaleString('de-DE')} Token / ${plan.slots} Slots</p>${(plan.gpus||[]).map(g=>`<p>${e(g.name)}: geschätzt ${gib(g.required_mib)} + ${gib(g.reserve_mib)} Reserve / ${gib(g.free_mib)} frei</p>`).join('')}<p>RAM: ${gib(plan.host_required_mib)} benötigt / ${gib(plan.host_available_mib)} verfügbar</p>`;}
async function refresh(){try{const [s,h]=await Promise.all([api('chat-tests'),api('hardware').catch(()=>({gpus:[]}))]);if(!root.isConnected)return;status=s;const j=s.job,w=s.worker,plan=w.memory_plan;
const stamp=[w.generation,w.state,w.profile_id,el('chat-profile').value].join('/');if(el('chat-profile').value&&stamp!==capabilityStamp){capabilityStamp=stamp;capabilities(false);}
put(el('chat-state'),`<p><strong>${e(j?.phase||'Noch kein Chat-Test gestartet.')}</strong></p><p>Worker: ${e(w.phase||w.state)} · ${e(w.profile_name||'kein Modell geladen')}<br>${s.scheduler.active_requests} laufende / ${s.scheduler.waiting_requests} wartende Anfragen</p>${j?.error?`<p role="alert">${e(j.error)}</p>`:''}${w.error?`<p>${e(w.error)}</p>`:''}${metrics(j)}${j?`<p>Dauer: ${Math.max(0,Math.round((j.finished_at||Date.now()/1000)-j.started_at))} s</p>`:''}`);
put(el('chat-memory'),memory(plan,w,h)+`<h4>Aktuelle GPU-Belegung</h4>${(h.gpus||[]).map(g=>`<p>${e(g.name)}: ${gib(g.used_mib)} / ${gib(g.total_mib)} belegt · ${g.percent??'—'} % Auslastung</p>`).join('')||'<p>GPU-Messwerte nicht verfügbar.</p>'}`);
if(j&&j.id===ownJob){let response=turns[turns.length-1];if(response?.role!=='assistant'){response={role:'assistant',content:'',reasoning:''};turns.push(response);}response.content=j.answer;response.reasoning=j.reasoning;transcript();
if(j.state!=='running'&&finished!==j.id){finished=j.id;if(j.state==='complete'&&j.answer)messages.push({role:'assistant',content:j.answer});else{messages=[];historyBytes=0;session=newSession();notice('Der nächste Prompt beginnt einen neuen Kontext; der letzte Test wurde nicht vollständig beantwortet.');}if(j.finish_reason==='length')notice('Antwort am Tokenlimit beendet. Bei Bedarf das Antwortlimit erhöhen.');}
}selection();
}catch(error){notice(error.message);}finally{if(root.isConnected)setTimeout(refresh,1500);}}
api('profiles').then(s=>{if(!root.isConnected)return;profiles=s.profiles.filter(p=>p.kind==='chat');el('chat-profile').innerHTML=profiles.map(p=>`<option value="${e(p.id)}">${e(p.name)}${p.runnable?'':' · nicht ausführbar'}</option>`).join('')||'<option value="">Zuerst ein Chatprofil anlegen</option>';selection();capabilities();}).catch(err=>notice(err.message));
const clear=()=>{epoch++;messages=[];turns=[];attachments=[];historyBytes=0;capabilityStamp=null;ownJob=null;finished=null;session=newSession();pendingFiles();transcript();notice('Neuer Chat.');};el('chat-clear').onclick=()=>{clear();capabilities();};el('chat-profile').onchange=()=>{clear();capabilities();};
const read=file=>new Promise((resolve,reject)=>{const r=new FileReader();r.onerror=()=>reject(Error('Datei konnte nicht gelesen werden.'));r.onload=()=>resolve(String(r.result).split(',')[1]);r.readAsDataURL(file);});
el('chat-files').onchange=async()=>{const version=epoch,selected=[...el('chat-files').files],features=caps.available||[],loaded=[];filePending=true;selection();try{
const historyCount=messages.reduce((n,m)=>n+(Array.isArray(m.content)?m.content.filter(p=>p.type!=='text').length:0),0);if(historyCount+attachments.length+selected.length>8)throw Error('Maximal acht Anhänge im gesamten Verlauf.');
if(historyBytes+attachments.reduce((n,a)=>n+a.size,0)+selected.reduce((n,f)=>n+f.size,0)>32*1024**2)throw Error('Anhänge überschreiten zusammen 32 MiB. Neuen Chat beginnen oder Dateien verkleinern.');
const docs={pdf:'application/pdf',docx:'application/vnd.openxmlformats-officedocument.wordprocessingml.document',pptx:'application/vnd.openxmlformats-officedocument.presentationml.presentation',xlsx:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',txt:'text/plain',md:'text/markdown',csv:'text/csv',json:'application/json',yaml:'application/yaml',yml:'application/yaml',xml:'application/xml'},images={png:'image/png',jpg:'image/jpeg',jpeg:'image/jpeg',webp:'image/webp'},videos={mp4:'video/mp4',webm:'video/webm',mov:'video/quicktime',mkv:'video/x-matroska'};
for(const f of selected){const ext=f.name.split('.').pop().toLowerCase(),p=profiles.find(x=>x.id===el('chat-profile').value);let kind,mime;if(images[ext]&&p?.parameters.vision_projector){kind='image';mime=images[ext];}else if(docs[ext]&&features.includes('documents')){kind='document';mime=docs[ext];}else if(videos[ext]&&features.includes('video')){kind='video';mime=videos[ext];}else throw Error('Dieser Dateityp ist für das gewählte Profil nicht verfügbar.');if(!f.size||f.size>(kind==='document'?16:32)*1024**2)throw Error('Datei leer oder über dem Größenlimit.');const url=`data:${mime};base64,${await read(f)}`;let part=kind==='image'?{type:'image_url',image_url:{url}}:kind==='video'?{type:'video_url',video_url:{url},fps:2,max_frames:128}:{type:'file',file:{filename:f.name,file_data:url}};if(kind==='document'&&ext==='pdf'&&el('chat-pages').value.trim())part.file.pages=el('chat-pages').value.trim();loaded.push({name:f.name,size:f.size,part});}
if(version===epoch&&root.isConnected){attachments.push(...loaded);pendingFiles();notice('Dateien angehängt; sie werden erst mit Senden übertragen.');}
}catch(error){notice(error.message);}finally{el('chat-files').value='';filePending=false;selection();}};
el('chat-test-form').onsubmit=async event=>{event.preventDefault();if(pending||filePending||status?.job?.state==='running')return;pending=true;selection();const text=el('chat-prompt').value.trim();try{const content=attachments.length?[{type:'text',text},...attachments.map(a=>a.part)]:text,next=[...messages,{role:'user',content}],body={profile_id:el('chat-profile').value,messages:next,max_tokens:Number(el('chat-limit').value),session_id:session};if(el('chat-effort').value)body.reasoning_effort=el('chat-effort').value;if(el('chat-logprobs').checked){body.logprobs=true;body.top_logprobs=5;}const job=await api('chat-tests/start',body);messages=next;historyBytes+=attachments.reduce((n,a)=>n+a.size,0);turns.push({role:'user',content:text,files:attachments.map(a=>a.name)});attachments=[];pendingFiles();ownJob=job.id;finished=null;status={...status,job};el('chat-prompt').value='';transcript();notice('Test gestartet. Speicherprüfung, Modellstart und Antwort erscheinen unter Diagnose.');}catch(error){notice(error.message);}finally{pending=false;selection();}};
el('chat-answer-now').onclick=async()=>{controlPending=true;selection();try{await api('chat-tests/answer-now',{job_id:ownJob});notice('Denken beenden angefordert; die Antwort läuft im selben Test weiter.');}catch(error){notice(error.message);}finally{controlPending=false;selection();}};
el('chat-cancel').onclick=async()=>{try{await api('chat-tests/cancel',{job_id:ownJob});notice('Abbruch dieses Tests angefordert.');}catch(error){notice(error.message);}};
el('chat-unload').onclick=async()=>{try{await api('chat-tests/unload',{});notice('Eigener Modellprozess entladen.');}catch(error){notice(error.message);}};
refresh();
}
return {html,bind};
})();