Chat: stop the AI on looping text or when too slow, answer from the knowledge base
Browse filesFiles changed (3)
111 unmodified lines112113114115116117118119120121122123124111 unmodified linesreturn [{ role: 'system', content: CHAT_SYSTEM_PROMPT }, ...history.slice(-4), { role: 'user', content: user }];}// Grounding rules for a chat answer (same as check_chat() in training/build_chat.py).const NUMBER = /(?<![\w.])\d+(?:\.\d+)?(?!\w)/g;export function chatProblems(userPrompt, answer) {const problems = [];// Degenerate output from a broken engine ("QUITQUITQUIT…", "warmth warmth warmth…") has no numbers or citations to catch.const words = answer.match(/\S+/g) || [];if (/(.{2,30}?)\1{9,}/s.test(answer) || (words.length >= 30 && new Set(words).size / words.length < 0.2)) problems.push('repeated text');const passages = (userPrompt.split('MY AUDIT:')[0].match(/^\[\d+\] /gm) || []).length;for (const m of answer.matchAll(/\[(\d+)\]/g)) if (+m[1] < 1 || +m[1] > passages) problems.push(`citation [${m[1]}] out of range`);const allowed = new Set(userPrompt.match(NUMBER) || []);111 unmodified lines112113114115116117118119120121122123124125126127128111 unmodified linesreturn [{ role: 'system', content: CHAT_SYSTEM_PROMPT }, ...history.slice(-4), { role: 'user', content: user }];}// Degenerate output from a broken engine ("QUITQUITQUIT…", "warmth warmth warmth…") has no numbers or citations to catch.export function repeatedText(answer) {const words = answer.match(/\S+/g) || [];return /(.{2,30}?)\1{9,}/s.test(answer) || (words.length >= 30 && new Set(words).size / words.length < 0.2);}// Grounding rules for a chat answer (same as check_chat() in training/build_chat.py).const NUMBER = /(?<![\w.])\d+(?:\.\d+)?(?!\w)/g;export function chatProblems(userPrompt, answer) {const problems = [];if (repeatedText(answer)) problems.push('repeated text');const passages = (userPrompt.split('MY AUDIT:')[0].match(/^\[\d+\] /gm) || []).length;for (const m of answer.matchAll(/\[(\d+)\]/g)) if (+m[1] < 1 || +m[1] > passages) problems.push(`citation [${m[1]}] out of range`);const allowed = new Set(userPrompt.match(NUMBER) || []);
151 unmodified lines152153154151 unmodified lines}@keyframes sheet-up { from { transform: translateY(100%); } to { transform: none; } }@media (prefers-reduced-motion: reduce) { .device-panel { animation: none; } .input-pill.loading::after { transition: none; } }151 unmodified lines152153154155151 unmodified lines}@keyframes sheet-up { from { transform: translateY(100%); } to { transform: none; } }@media (prefers-reduced-motion: reduce) { .device-panel { animation: none; } .input-pill.loading::after { transition: none; } }.device-retry { width: 100%; margin-bottom: 8px; }
123456718 unmodified lines26272829303145 unmodified lines77787980818283843 unmodified lines88899091929394132 unmodified lines2272282292302312322332342352362372382397 unmodified lines247248249250251252253254139 unmodified lines3943953963973983994008 unmodified lines40941041141241341420 unmodified lines4354364374384394403 unmodified lines44444544644744844945053 unmodified lines504505506507508509510// Devseis Security Assistant: chat about endpoint security with the Devseis model running on the device (WebLLM),// grounded in the Devseis knowledge base (library/knowledge.json), plus audits: the phone check on phones, the desktop// app (or its report file) on computers. Conversations are stored only in this browser.import { Knowledge, chatMessages, auditBrief, chatProblems, searchWithAudit } from '../app/renderer/knowledge.js';import { Library, findingPrompt, findingTemplate, summaryPrompt, summaryTemplate, aiPrompt, aiTemplate, writeAnswer, ANSWER_SCHEMAS } from '../app/renderer/auditor-core.js';import { buildReportHtml } from '../app/renderer/report.js';import { detectDevice } from '../mobile/detect.js';18 unmodified lines// The model never blocks a question: until it is ready, answers come straight from the knowledge base.// It downloads in the background after the user agrees once (about 1 GB), and starts by itself when already stored.const AI_CONSENT = 'devseis.aiConsent';let webllmPromise = null;const loadWebllm = () => (webllmPromise ||= import(WEBLLM_URL));45 unmodified lines}function enableAi() {try { localStorage.setItem(AI_CONSENT, 'yes'); } catch { /* ignore */ }state.consent = true; state.kbOnly = false;getEngine();}3 unmodified linesif (!chip) return;if (state.engine) { chip.textContent = '✨ AI ready'; chip.title = state.modelLabel; chip.dataset.state = 'ready'; }else if (state.loading) { chip.textContent = `⬇ AI ${Math.round((state.progress || 0) * 100)}%`; chip.title = 'The AI assistant is getting ready'; chip.dataset.state = 'loading'; }else if (state.engine === false) { chip.textContent = '📚 Knowledge base'; chip.title = state.modelLabel; chip.dataset.state = 'off'; }else { chip.textContent = '⚡ Enable AI'; chip.title = 'Download the AI assistant (about 1 GB, one time)'; chip.dataset.state = 'off'; }updateSend();if (!$('devicePanel').classList.contains('hidden')) renderDevicePanel();132 unmodified linesfor (let attempt = 0; attempt < 2 && engine; attempt++) {try {const stream = await engine.chat.completions.create({ messages, temperature: 0, max_tokens: 700, stream: true });let last = 0, started = false;for await (const chunk of stream) {const delta = chunk.choices[0]?.delta?.content || '';if (!started && delta) { started = true; reply.pending = false; reply.content = ''; reply.quick = false; reply.writing = false; reply.note = ''; }reply.content += delta;if (Date.now() - last > 120) { last = Date.now(); const el = $(`m${index}`); if (el) el.innerHTML = markdown(clean(reply.content), passages, index); }}if (!started) throw new Error('The AI returned no answer');reply.content = clean(reply.content);reply.noSources = !/\[\d+\]/.test(reply.content) && /can only help|don't have|do not have|not able to|can't answer|cannot answer|sorry/i.test(reply.content);7 unmodified linesengine = attempt === 0 ? await getEngine() : null;}}reply.pending = false; reply.content = quickAnswer(passages); reply.cited = true; reply.quick = true; reply.writing = false;reply.note = 'Quick answer from the knowledge base (the AI could not run just now).';}async function rewriteWithAi(index) {139 unmodified linesconst d = activeDevice();const row = (label, value, hint = '') => value ? `<div class="drow"><dt>${label}</dt><dd>${esc(value)}${hint ? `<small>${esc(hint)}</small>` : ''}</dd></div>` : '';const unlock = real.platform_authenticator === true ? 'Available (fingerprint, face or PIN)' : real.platform_authenticator === false ? 'None found by the browser' : '';const ai = state.engine ? `Ready · ${state.modelLabel}` : state.loading ? `Downloading · ${Math.round((state.progress || 0) * 100)}%`: 'gpu' in navigator && state.engine !== false ? 'Supported (WebGPU)' : 'Not supported here: answers come from the knowledge base';let html;if (audit) {8 unmodified lineshtml = `<dl>${row('Device', d.device_model ? `${d.device_model}${d.arch ? ` (${d.arch})` : ''}` : '')}${row('System', d.os_family ? osLabel(d) : 'Not recognised', version)}${d.chosen ? '' : row('Browser', real.browser) + row('Screen unlock', unlock) + row('Connection', real.cellular ? 'Mobile data' : '')}${row('On-device AI', ai)}</dl><p class="device-note">🔒 Read by your browser and never uploaded. Arx uses it to give steps for this system. A web page can't see settings such as encryption or the firewall: an audit checks those.</p><button type="button" class="primary-btn device-audit" id="deviceAudit">🛡 Audit ${d.chosen ? 'a device' : 'this device'}</button><div class="device-switch"><span class="muted tiny">Asking about another device?</span><div class="seg"><button type="button" data-os="" aria-pressed="${!state.deviceChoice}">${deviceIcon(real)} This device</button>20 unmodified linesrenderDevice(); renderDevicePanel(); return;}if (e.target.closest('#deviceAudit')) { toggleDevicePanel(false); openAuditModal(); }});function closeSidebar() { $('sidebar').classList.remove('open'); $('overlay').classList.add('hidden'); }3 unmodified lines$('input').addEventListener('keydown', e => { if (e.key === 'Enter' && !e.shiftKey && !e.isComposing) { e.preventDefault(); $('composer').requestSubmit(); } });document.querySelectorAll('.chip').forEach(c => c.addEventListener('click', () => (c.dataset.action === 'audit' ? openAuditModal() : ask(c.dataset.prompt))));$('auditBtn').addEventListener('click', openAuditModal);$('aiChip').addEventListener('click', () => { if (!state.engine && !state.loading && state.engine !== false) enableAi(); else if (state.engine) status(`AI assistant ready: ${state.modelLabel}`, 1) || setTimeout(() => status(''), 2500); });$('aiCardYes').addEventListener('click', () => { state.showAiCard = false; enableAi(); });$('aiCardNo').addEventListener('click', () => { state.showAiCard = false; state.kbOnly = true; aiChip(); try { localStorage.setItem(AI_CONSENT, 'later'); } catch { /* ignore */ } render(); });$('auditClose').addEventListener('click', () => $('auditModal').classList.add('hidden'));53 unmodified linesrender(); aiChip();if ('gpu' in navigator) {let consent = null; try { consent = localStorage.getItem(AI_CONSENT); } catch { /* ignore */ }modelCached().then(cached => {if (cached || consent === 'yes') { state.cachedStart = cached; getEngine(); }else if (consent === 'later') { state.kbOnly = true; aiChip(); }else {123456718 unmodified lines26272829303132333445 unmodified lines80818283848586873 unmodified lines91929394959697132 unmodified lines2302312322332342352362372382392402412422432442452462472482492502512522537 unmodified lines261262263264265266267268269270271272273274275276277278279280281282139 unmodified lines4224234244254264274288 unmodified lines43743843944044144244320 unmodified lines4644654664674684694703 unmodified lines47447547647747847948053 unmodified lines534535536537538539540541542// Devseis Security Assistant: chat about endpoint security with the Devseis model running on the device (WebLLM),// grounded in the Devseis knowledge base (library/knowledge.json), plus audits: the phone check on phones, the desktop// app (or its report file) on computers. Conversations are stored only in this browser.import { Knowledge, chatMessages, auditBrief, chatProblems, searchWithAudit, repeatedText } from '../app/renderer/knowledge.js';import { Library, findingPrompt, findingTemplate, summaryPrompt, summaryTemplate, aiPrompt, aiTemplate, writeAnswer, ANSWER_SCHEMAS } from '../app/renderer/auditor-core.js';import { buildReportHtml } from '../app/renderer/report.js';import { detectDevice } from '../mobile/detect.js';18 unmodified lines// The model never blocks a question: until it is ready, answers come straight from the knowledge base.// It downloads in the background after the user agrees once (about 1 GB), and starts by itself when already stored.const AI_CONSENT = 'devseis.aiConsent';// Set when the AI wrote unreadable text on this device (a faulty graphics chip or driver); holds the model version, so a new one is tried again.const AI_FAULT = 'devseis.aiFault';const FIRST_WORDS_LIMIT = 60000, ANSWER_LIMIT = 180000;let webllmPromise = null;const loadWebllm = () => (webllmPromise ||= import(WEBLLM_URL));45 unmodified lines}function enableAi() {try { localStorage.setItem(AI_CONSENT, 'yes'); localStorage.removeItem(AI_FAULT); } catch { /* ignore */ }state.consent = true; state.kbOnly = false; state.aiFault = false;getEngine();}3 unmodified linesif (!chip) return;if (state.engine) { chip.textContent = '✨ AI ready'; chip.title = state.modelLabel; chip.dataset.state = 'ready'; }else if (state.loading) { chip.textContent = `⬇ AI ${Math.round((state.progress || 0) * 100)}%`; chip.title = 'The AI assistant is getting ready'; chip.dataset.state = 'loading'; }else if (state.engine === false || state.aiFault) { chip.textContent = '📚 Knowledge base'; chip.title = state.modelLabel; chip.dataset.state = 'off'; }else { chip.textContent = '⚡ Enable AI'; chip.title = 'Download the AI assistant (about 1 GB, one time)'; chip.dataset.state = 'off'; }updateSend();if (!$('devicePanel').classList.contains('hidden')) renderDevicePanel();132 unmodified linesfor (let attempt = 0; attempt < 2 && engine; attempt++) {try {const stream = await engine.chat.completions.create({ messages, temperature: 0, max_tokens: 700, stream: true });let last = 0, started = false, fault = null;// A weak graphics chip can take minutes; stop and use the knowledge base instead of leaving the visitor waiting.const t0 = Date.now();const watchdog = setInterval(() => {if (Date.now() - t0 > (started ? ANSWER_LIMIT : FIRST_WORDS_LIMIT)) { fault = 'slow'; engine.interruptGenerate(); }}, 1000);try {for await (const chunk of stream) {const delta = chunk.choices[0]?.delta?.content || '';if (!started && delta) { started = true; reply.pending = false; reply.content = ''; reply.quick = false; reply.writing = false; reply.note = ''; }reply.content += delta;// Looping text means the engine is broken on this device: stop at once, it only gets worse.if (reply.content.length > 40 && repeatedText(reply.content)) { fault = 'junk'; engine.interruptGenerate(); break; }if (Date.now() - last > 120) { last = Date.now(); const el = $(`m${index}`); if (el) el.innerHTML = markdown(clean(reply.content), passages, index); }}} finally { clearInterval(watchdog); }if (fault === 'junk') { turnOffBrokenAi(); return fallback(reply, passages, 'The AI wrote unreadable text on this device, so Arx switched to answers from the knowledge base. Details: tap the device bar.'); }if (fault === 'slow') return fallback(reply, passages, 'The AI was too slow on this device, so this answer comes from the knowledge base.');if (!started) throw new Error('The AI returned no answer');reply.content = clean(reply.content);reply.noSources = !/\[\d+\]/.test(reply.content) && /can only help|don't have|do not have|not able to|can't answer|cannot answer|sorry/i.test(reply.content);7 unmodified linesengine = attempt === 0 ? await getEngine() : null;}}fallback(reply, passages, 'Quick answer from the knowledge base (the AI could not run just now).');}function fallback(reply, passages, note) {reply.pending = false; reply.content = quickAnswer(passages); reply.cited = true; reply.quick = true; reply.writing = false; reply.noSources = false;reply.note = note;}// The AI wrote junk: free the graphics chip (a broken driver can hang the whole computer) and stay on the knowledge base here.function turnOffBrokenAi() {const engine = state.engine;state.engine = null; state.enginePromise = null; state.loading = false; state.kbOnly = true; state.aiFault = true;state.modelLabel = 'Turned off: it wrote unreadable text on this device'; $('modelName').textContent = 'Knowledge base only';try { localStorage.setItem(AI_FAULT, state.config?.chat?.version || 'base'); } catch { /* ignore */ }if (engine && engine.unload) engine.unload().catch(() => {});aiChip();}async function rewriteWithAi(index) {139 unmodified linesconst d = activeDevice();const row = (label, value, hint = '') => value ? `<div class="drow"><dt>${label}</dt><dd>${esc(value)}${hint ? `<small>${esc(hint)}</small>` : ''}</dd></div>` : '';const unlock = real.platform_authenticator === true ? 'Available (fingerprint, face or PIN)' : real.platform_authenticator === false ? 'None found by the browser' : '';const ai = state.aiFault ? 'Turned off: it wrote unreadable text on this device\'s graphics chip' : state.engine ? `Ready · ${state.modelLabel}` : state.loading ? `Downloading · ${Math.round((state.progress || 0) * 100)}%`: 'gpu' in navigator && state.engine !== false ? 'Supported (WebGPU)' : 'Not supported here: answers come from the knowledge base';let html;if (audit) {8 unmodified lineshtml = `<dl>${row('Device', d.device_model ? `${d.device_model}${d.arch ? ` (${d.arch})` : ''}` : '')}${row('System', d.os_family ? osLabel(d) : 'Not recognised', version)}${d.chosen ? '' : row('Browser', real.browser) + row('Screen unlock', unlock) + row('Connection', real.cellular ? 'Mobile data' : '')}${row('On-device AI', ai)}</dl><p class="device-note">🔒 Read by your browser and never uploaded. Arx uses it to give steps for this system. A web page can't see settings such as encryption or the firewall: an audit checks those.</p>${state.aiFault && !d.chosen ? '<button type="button" class="small-btn device-retry" id="aiRetry">↻ Try the AI again (it may be slow or fail again)</button>' : ''}<button type="button" class="primary-btn device-audit" id="deviceAudit">🛡 Audit ${d.chosen ? 'a device' : 'this device'}</button><div class="device-switch"><span class="muted tiny">Asking about another device?</span><div class="seg"><button type="button" data-os="" aria-pressed="${!state.deviceChoice}">${deviceIcon(real)} This device</button>20 unmodified linesrenderDevice(); renderDevicePanel(); return;}if (e.target.closest('#deviceAudit')) { toggleDevicePanel(false); openAuditModal(); }if (e.target.closest('#aiRetry')) { toggleDevicePanel(false); enableAi(); }});function closeSidebar() { $('sidebar').classList.remove('open'); $('overlay').classList.add('hidden'); }3 unmodified lines$('input').addEventListener('keydown', e => { if (e.key === 'Enter' && !e.shiftKey && !e.isComposing) { e.preventDefault(); $('composer').requestSubmit(); } });document.querySelectorAll('.chip').forEach(c => c.addEventListener('click', () => (c.dataset.action === 'audit' ? openAuditModal() : ask(c.dataset.prompt))));$('auditBtn').addEventListener('click', openAuditModal);$('aiChip').addEventListener('click', () => { if (state.aiFault) toggleDevicePanel(true); else if (!state.engine && !state.loading && state.engine !== false) enableAi(); else if (state.engine) status(`AI assistant ready: ${state.modelLabel}`, 1) || setTimeout(() => status(''), 2500); });$('aiCardYes').addEventListener('click', () => { state.showAiCard = false; enableAi(); });$('aiCardNo').addEventListener('click', () => { state.showAiCard = false; state.kbOnly = true; aiChip(); try { localStorage.setItem(AI_CONSENT, 'later'); } catch { /* ignore */ } render(); });$('auditClose').addEventListener('click', () => $('auditModal').classList.add('hidden'));53 unmodified linesrender(); aiChip();if ('gpu' in navigator) {let consent = null; try { consent = localStorage.getItem(AI_CONSENT); } catch { /* ignore */ }let fault = null; try { fault = localStorage.getItem(AI_FAULT); } catch { /* ignore */ }if (fault && fault === (state.config?.chat?.version || 'base')) { state.kbOnly = true; state.aiFault = true; state.modelLabel = 'Turned off: it wrote unreadable text on this device'; $('modelName').textContent = 'Knowledge base only'; aiChip(); }else modelCached().then(cached => {if (cached || consent === 'yes') { state.cachedStart = cached; getEngine(); }else if (consent === 'later') { state.kbOnly = true; aiChip(); }else {
app/renderer/knowledge.js+7-3
chat/chat.css+1
chat/chat.js+48-16