Chat: stop the AI on looping text or when too slow, answer from the knowledge base
Browse files- app/renderer/knowledge.js +7 -3
- chat/chat.css +1 -0
- chat/chat.js +48 -16
app/renderer/knowledge.js
CHANGED
|
@@ -112,13 +112,17 @@ export function chatMessages(question, passages, audit = 'none', history = [], d
|
|
| 112 |
return [{ role: 'system', content: CHAT_SYSTEM_PROMPT }, ...history.slice(-4), { role: 'user', content: user }];
|
| 113 |
}
|
| 114 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
// Grounding rules for a chat answer (same as check_chat() in training/build_chat.py).
|
| 116 |
const NUMBER = /(?<![\w.])\d+(?:\.\d+)?(?!\w)/g;
|
| 117 |
export function chatProblems(userPrompt, answer) {
|
| 118 |
const problems = [];
|
| 119 |
-
|
| 120 |
-
const words = answer.match(/\S+/g) || [];
|
| 121 |
-
if (/(.{2,30}?)\1{9,}/s.test(answer) || (words.length >= 30 && new Set(words).size / words.length < 0.2)) problems.push('repeated text');
|
| 122 |
const passages = (userPrompt.split('MY AUDIT:')[0].match(/^\[\d+\] /gm) || []).length;
|
| 123 |
for (const m of answer.matchAll(/\[(\d+)\]/g)) if (+m[1] < 1 || +m[1] > passages) problems.push(`citation [${m[1]}] out of range`);
|
| 124 |
const allowed = new Set(userPrompt.match(NUMBER) || []);
|
|
|
|
| 112 |
return [{ role: 'system', content: CHAT_SYSTEM_PROMPT }, ...history.slice(-4), { role: 'user', content: user }];
|
| 113 |
}
|
| 114 |
|
| 115 |
+
// Degenerate output from a broken engine ("QUITQUITQUIT…", "warmth warmth warmth…") has no numbers or citations to catch.
|
| 116 |
+
export function repeatedText(answer) {
|
| 117 |
+
const words = answer.match(/\S+/g) || [];
|
| 118 |
+
return /(.{2,30}?)\1{9,}/s.test(answer) || (words.length >= 30 && new Set(words).size / words.length < 0.2);
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
// Grounding rules for a chat answer (same as check_chat() in training/build_chat.py).
|
| 122 |
const NUMBER = /(?<![\w.])\d+(?:\.\d+)?(?!\w)/g;
|
| 123 |
export function chatProblems(userPrompt, answer) {
|
| 124 |
const problems = [];
|
| 125 |
+
if (repeatedText(answer)) problems.push('repeated text');
|
|
|
|
|
|
|
| 126 |
const passages = (userPrompt.split('MY AUDIT:')[0].match(/^\[\d+\] /gm) || []).length;
|
| 127 |
for (const m of answer.matchAll(/\[(\d+)\]/g)) if (+m[1] < 1 || +m[1] > passages) problems.push(`citation [${m[1]}] out of range`);
|
| 128 |
const allowed = new Set(userPrompt.match(NUMBER) || []);
|
chat/chat.css
CHANGED
|
@@ -152,3 +152,4 @@ main { flex: 1; overflow-y: auto; padding: 18px 14px 8px; }
|
|
| 152 |
}
|
| 153 |
@keyframes sheet-up { from { transform: translateY(100%); } to { transform: none; } }
|
| 154 |
@media (prefers-reduced-motion: reduce) { .device-panel { animation: none; } .input-pill.loading::after { transition: none; } }
|
|
|
|
|
|
| 152 |
}
|
| 153 |
@keyframes sheet-up { from { transform: translateY(100%); } to { transform: none; } }
|
| 154 |
@media (prefers-reduced-motion: reduce) { .device-panel { animation: none; } .input-pill.loading::after { transition: none; } }
|
| 155 |
+
.device-retry { width: 100%; margin-bottom: 8px; }
|
chat/chat.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
// Devseis Security Assistant: chat about endpoint security with the Devseis model running on the device (WebLLM),
|
| 2 |
// grounded in the Devseis knowledge base (library/knowledge.json), plus audits: the phone check on phones, the desktop
|
| 3 |
// app (or its report file) on computers. Conversations are stored only in this browser.
|
| 4 |
-
import { Knowledge, chatMessages, auditBrief, chatProblems, searchWithAudit } from '../app/renderer/knowledge.js';
|
| 5 |
import { Library, findingPrompt, findingTemplate, summaryPrompt, summaryTemplate, aiPrompt, aiTemplate, writeAnswer, ANSWER_SCHEMAS } from '../app/renderer/auditor-core.js';
|
| 6 |
import { buildReportHtml } from '../app/renderer/report.js';
|
| 7 |
import { detectDevice } from '../mobile/detect.js';
|
|
@@ -26,6 +26,9 @@ function newChat() {
|
|
| 26 |
// The model never blocks a question: until it is ready, answers come straight from the knowledge base.
|
| 27 |
// It downloads in the background after the user agrees once (about 1 GB), and starts by itself when already stored.
|
| 28 |
const AI_CONSENT = 'devseis.aiConsent';
|
|
|
|
|
|
|
|
|
|
| 29 |
let webllmPromise = null;
|
| 30 |
const loadWebllm = () => (webllmPromise ||= import(WEBLLM_URL));
|
| 31 |
|
|
@@ -77,8 +80,8 @@ function getEngine() {
|
|
| 77 |
}
|
| 78 |
|
| 79 |
function enableAi() {
|
| 80 |
-
try { localStorage.setItem(AI_CONSENT, 'yes'); } catch { /* ignore */ }
|
| 81 |
-
state.consent = true; state.kbOnly = false;
|
| 82 |
getEngine();
|
| 83 |
}
|
| 84 |
|
|
@@ -88,7 +91,7 @@ function aiChip() {
|
|
| 88 |
if (!chip) return;
|
| 89 |
if (state.engine) { chip.textContent = '✨ AI ready'; chip.title = state.modelLabel; chip.dataset.state = 'ready'; }
|
| 90 |
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'; }
|
| 91 |
-
else if (state.engine === false) { chip.textContent = '📚 Knowledge base'; chip.title = state.modelLabel; chip.dataset.state = 'off'; }
|
| 92 |
else { chip.textContent = '⚡ Enable AI'; chip.title = 'Download the AI assistant (about 1 GB, one time)'; chip.dataset.state = 'off'; }
|
| 93 |
updateSend();
|
| 94 |
if (!$('devicePanel').classList.contains('hidden')) renderDevicePanel();
|
|
@@ -227,13 +230,24 @@ async function aiAnswer(chat, reply, messages, passages) {
|
|
| 227 |
for (let attempt = 0; attempt < 2 && engine; attempt++) {
|
| 228 |
try {
|
| 229 |
const stream = await engine.chat.completions.create({ messages, temperature: 0, max_tokens: 700, stream: true });
|
| 230 |
-
let last = 0, started = false;
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
if (!started) throw new Error('The AI returned no answer');
|
| 238 |
reply.content = clean(reply.content);
|
| 239 |
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);
|
|
@@ -247,8 +261,22 @@ async function aiAnswer(chat, reply, messages, passages) {
|
|
| 247 |
engine = attempt === 0 ? await getEngine() : null;
|
| 248 |
}
|
| 249 |
}
|
| 250 |
-
reply
|
| 251 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 252 |
}
|
| 253 |
|
| 254 |
async function rewriteWithAi(index) {
|
|
@@ -394,7 +422,7 @@ function renderDevicePanel() {
|
|
| 394 |
const d = activeDevice();
|
| 395 |
const row = (label, value, hint = '') => value ? `<div class="drow"><dt>${label}</dt><dd>${esc(value)}${hint ? `<small>${esc(hint)}</small>` : ''}</dd></div>` : '';
|
| 396 |
const unlock = real.platform_authenticator === true ? 'Available (fingerprint, face or PIN)' : real.platform_authenticator === false ? 'None found by the browser' : '';
|
| 397 |
-
const ai = state.engine ? `Ready · ${state.modelLabel}` : state.loading ? `Downloading · ${Math.round((state.progress || 0) * 100)}%`
|
| 398 |
: 'gpu' in navigator && state.engine !== false ? 'Supported (WebGPU)' : 'Not supported here: answers come from the knowledge base';
|
| 399 |
let html;
|
| 400 |
if (audit) {
|
|
@@ -409,6 +437,7 @@ function renderDevicePanel() {
|
|
| 409 |
html = `<dl>${row('Device', d.device_model ? `${d.device_model}${d.arch ? ` (${d.arch})` : ''}` : '')}${row('System', d.os_family ? osLabel(d) : 'Not recognised', version)}
|
| 410 |
${d.chosen ? '' : row('Browser', real.browser) + row('Screen unlock', unlock) + row('Connection', real.cellular ? 'Mobile data' : '')}${row('On-device AI', ai)}</dl>
|
| 411 |
<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>
|
|
|
|
| 412 |
<button type="button" class="primary-btn device-audit" id="deviceAudit">🛡 Audit ${d.chosen ? 'a device' : 'this device'}</button>
|
| 413 |
<div class="device-switch"><span class="muted tiny">Asking about another device?</span><div class="seg">
|
| 414 |
<button type="button" data-os="" aria-pressed="${!state.deviceChoice}">${deviceIcon(real)} This device</button>
|
|
@@ -435,6 +464,7 @@ $('deviceBody').addEventListener('click', e => {
|
|
| 435 |
renderDevice(); renderDevicePanel(); return;
|
| 436 |
}
|
| 437 |
if (e.target.closest('#deviceAudit')) { toggleDevicePanel(false); openAuditModal(); }
|
|
|
|
| 438 |
});
|
| 439 |
|
| 440 |
function closeSidebar() { $('sidebar').classList.remove('open'); $('overlay').classList.add('hidden'); }
|
|
@@ -444,7 +474,7 @@ $('input').addEventListener('input', () => { const t = $('input'); t.style.heigh
|
|
| 444 |
$('input').addEventListener('keydown', e => { if (e.key === 'Enter' && !e.shiftKey && !e.isComposing) { e.preventDefault(); $('composer').requestSubmit(); } });
|
| 445 |
document.querySelectorAll('.chip').forEach(c => c.addEventListener('click', () => (c.dataset.action === 'audit' ? openAuditModal() : ask(c.dataset.prompt))));
|
| 446 |
$('auditBtn').addEventListener('click', openAuditModal);
|
| 447 |
-
$('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); });
|
| 448 |
$('aiCardYes').addEventListener('click', () => { state.showAiCard = false; enableAi(); });
|
| 449 |
$('aiCardNo').addEventListener('click', () => { state.showAiCard = false; state.kbOnly = true; aiChip(); try { localStorage.setItem(AI_CONSENT, 'later'); } catch { /* ignore */ } render(); });
|
| 450 |
$('auditClose').addEventListener('click', () => $('auditModal').classList.add('hidden'));
|
|
@@ -504,7 +534,9 @@ async function init() {
|
|
| 504 |
render(); aiChip();
|
| 505 |
if ('gpu' in navigator) {
|
| 506 |
let consent = null; try { consent = localStorage.getItem(AI_CONSENT); } catch { /* ignore */ }
|
| 507 |
-
|
|
|
|
|
|
|
| 508 |
if (cached || consent === 'yes') { state.cachedStart = cached; getEngine(); }
|
| 509 |
else if (consent === 'later') { state.kbOnly = true; aiChip(); }
|
| 510 |
else {
|
|
|
|
| 1 |
// Devseis Security Assistant: chat about endpoint security with the Devseis model running on the device (WebLLM),
|
| 2 |
// grounded in the Devseis knowledge base (library/knowledge.json), plus audits: the phone check on phones, the desktop
|
| 3 |
// app (or its report file) on computers. Conversations are stored only in this browser.
|
| 4 |
+
import { Knowledge, chatMessages, auditBrief, chatProblems, searchWithAudit, repeatedText } from '../app/renderer/knowledge.js';
|
| 5 |
import { Library, findingPrompt, findingTemplate, summaryPrompt, summaryTemplate, aiPrompt, aiTemplate, writeAnswer, ANSWER_SCHEMAS } from '../app/renderer/auditor-core.js';
|
| 6 |
import { buildReportHtml } from '../app/renderer/report.js';
|
| 7 |
import { detectDevice } from '../mobile/detect.js';
|
|
|
|
| 26 |
// The model never blocks a question: until it is ready, answers come straight from the knowledge base.
|
| 27 |
// It downloads in the background after the user agrees once (about 1 GB), and starts by itself when already stored.
|
| 28 |
const AI_CONSENT = 'devseis.aiConsent';
|
| 29 |
+
// 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.
|
| 30 |
+
const AI_FAULT = 'devseis.aiFault';
|
| 31 |
+
const FIRST_WORDS_LIMIT = 60000, ANSWER_LIMIT = 180000;
|
| 32 |
let webllmPromise = null;
|
| 33 |
const loadWebllm = () => (webllmPromise ||= import(WEBLLM_URL));
|
| 34 |
|
|
|
|
| 80 |
}
|
| 81 |
|
| 82 |
function enableAi() {
|
| 83 |
+
try { localStorage.setItem(AI_CONSENT, 'yes'); localStorage.removeItem(AI_FAULT); } catch { /* ignore */ }
|
| 84 |
+
state.consent = true; state.kbOnly = false; state.aiFault = false;
|
| 85 |
getEngine();
|
| 86 |
}
|
| 87 |
|
|
|
|
| 91 |
if (!chip) return;
|
| 92 |
if (state.engine) { chip.textContent = '✨ AI ready'; chip.title = state.modelLabel; chip.dataset.state = 'ready'; }
|
| 93 |
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'; }
|
| 94 |
+
else if (state.engine === false || state.aiFault) { chip.textContent = '📚 Knowledge base'; chip.title = state.modelLabel; chip.dataset.state = 'off'; }
|
| 95 |
else { chip.textContent = '⚡ Enable AI'; chip.title = 'Download the AI assistant (about 1 GB, one time)'; chip.dataset.state = 'off'; }
|
| 96 |
updateSend();
|
| 97 |
if (!$('devicePanel').classList.contains('hidden')) renderDevicePanel();
|
|
|
|
| 230 |
for (let attempt = 0; attempt < 2 && engine; attempt++) {
|
| 231 |
try {
|
| 232 |
const stream = await engine.chat.completions.create({ messages, temperature: 0, max_tokens: 700, stream: true });
|
| 233 |
+
let last = 0, started = false, fault = null;
|
| 234 |
+
// A weak graphics chip can take minutes; stop and use the knowledge base instead of leaving the visitor waiting.
|
| 235 |
+
const t0 = Date.now();
|
| 236 |
+
const watchdog = setInterval(() => {
|
| 237 |
+
if (Date.now() - t0 > (started ? ANSWER_LIMIT : FIRST_WORDS_LIMIT)) { fault = 'slow'; engine.interruptGenerate(); }
|
| 238 |
+
}, 1000);
|
| 239 |
+
try {
|
| 240 |
+
for await (const chunk of stream) {
|
| 241 |
+
const delta = chunk.choices[0]?.delta?.content || '';
|
| 242 |
+
if (!started && delta) { started = true; reply.pending = false; reply.content = ''; reply.quick = false; reply.writing = false; reply.note = ''; }
|
| 243 |
+
reply.content += delta;
|
| 244 |
+
// Looping text means the engine is broken on this device: stop at once, it only gets worse.
|
| 245 |
+
if (reply.content.length > 40 && repeatedText(reply.content)) { fault = 'junk'; engine.interruptGenerate(); break; }
|
| 246 |
+
if (Date.now() - last > 120) { last = Date.now(); const el = $(`m${index}`); if (el) el.innerHTML = markdown(clean(reply.content), passages, index); }
|
| 247 |
+
}
|
| 248 |
+
} finally { clearInterval(watchdog); }
|
| 249 |
+
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.'); }
|
| 250 |
+
if (fault === 'slow') return fallback(reply, passages, 'The AI was too slow on this device, so this answer comes from the knowledge base.');
|
| 251 |
if (!started) throw new Error('The AI returned no answer');
|
| 252 |
reply.content = clean(reply.content);
|
| 253 |
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);
|
|
|
|
| 261 |
engine = attempt === 0 ? await getEngine() : null;
|
| 262 |
}
|
| 263 |
}
|
| 264 |
+
fallback(reply, passages, 'Quick answer from the knowledge base (the AI could not run just now).');
|
| 265 |
+
}
|
| 266 |
+
|
| 267 |
+
function fallback(reply, passages, note) {
|
| 268 |
+
reply.pending = false; reply.content = quickAnswer(passages); reply.cited = true; reply.quick = true; reply.writing = false; reply.noSources = false;
|
| 269 |
+
reply.note = note;
|
| 270 |
+
}
|
| 271 |
+
|
| 272 |
+
// The AI wrote junk: free the graphics chip (a broken driver can hang the whole computer) and stay on the knowledge base here.
|
| 273 |
+
function turnOffBrokenAi() {
|
| 274 |
+
const engine = state.engine;
|
| 275 |
+
state.engine = null; state.enginePromise = null; state.loading = false; state.kbOnly = true; state.aiFault = true;
|
| 276 |
+
state.modelLabel = 'Turned off: it wrote unreadable text on this device'; $('modelName').textContent = 'Knowledge base only';
|
| 277 |
+
try { localStorage.setItem(AI_FAULT, state.config?.chat?.version || 'base'); } catch { /* ignore */ }
|
| 278 |
+
if (engine && engine.unload) engine.unload().catch(() => {});
|
| 279 |
+
aiChip();
|
| 280 |
}
|
| 281 |
|
| 282 |
async function rewriteWithAi(index) {
|
|
|
|
| 422 |
const d = activeDevice();
|
| 423 |
const row = (label, value, hint = '') => value ? `<div class="drow"><dt>${label}</dt><dd>${esc(value)}${hint ? `<small>${esc(hint)}</small>` : ''}</dd></div>` : '';
|
| 424 |
const unlock = real.platform_authenticator === true ? 'Available (fingerprint, face or PIN)' : real.platform_authenticator === false ? 'None found by the browser' : '';
|
| 425 |
+
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)}%`
|
| 426 |
: 'gpu' in navigator && state.engine !== false ? 'Supported (WebGPU)' : 'Not supported here: answers come from the knowledge base';
|
| 427 |
let html;
|
| 428 |
if (audit) {
|
|
|
|
| 437 |
html = `<dl>${row('Device', d.device_model ? `${d.device_model}${d.arch ? ` (${d.arch})` : ''}` : '')}${row('System', d.os_family ? osLabel(d) : 'Not recognised', version)}
|
| 438 |
${d.chosen ? '' : row('Browser', real.browser) + row('Screen unlock', unlock) + row('Connection', real.cellular ? 'Mobile data' : '')}${row('On-device AI', ai)}</dl>
|
| 439 |
<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>
|
| 440 |
+
${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>' : ''}
|
| 441 |
<button type="button" class="primary-btn device-audit" id="deviceAudit">🛡 Audit ${d.chosen ? 'a device' : 'this device'}</button>
|
| 442 |
<div class="device-switch"><span class="muted tiny">Asking about another device?</span><div class="seg">
|
| 443 |
<button type="button" data-os="" aria-pressed="${!state.deviceChoice}">${deviceIcon(real)} This device</button>
|
|
|
|
| 464 |
renderDevice(); renderDevicePanel(); return;
|
| 465 |
}
|
| 466 |
if (e.target.closest('#deviceAudit')) { toggleDevicePanel(false); openAuditModal(); }
|
| 467 |
+
if (e.target.closest('#aiRetry')) { toggleDevicePanel(false); enableAi(); }
|
| 468 |
});
|
| 469 |
|
| 470 |
function closeSidebar() { $('sidebar').classList.remove('open'); $('overlay').classList.add('hidden'); }
|
|
|
|
| 474 |
$('input').addEventListener('keydown', e => { if (e.key === 'Enter' && !e.shiftKey && !e.isComposing) { e.preventDefault(); $('composer').requestSubmit(); } });
|
| 475 |
document.querySelectorAll('.chip').forEach(c => c.addEventListener('click', () => (c.dataset.action === 'audit' ? openAuditModal() : ask(c.dataset.prompt))));
|
| 476 |
$('auditBtn').addEventListener('click', openAuditModal);
|
| 477 |
+
$('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); });
|
| 478 |
$('aiCardYes').addEventListener('click', () => { state.showAiCard = false; enableAi(); });
|
| 479 |
$('aiCardNo').addEventListener('click', () => { state.showAiCard = false; state.kbOnly = true; aiChip(); try { localStorage.setItem(AI_CONSENT, 'later'); } catch { /* ignore */ } render(); });
|
| 480 |
$('auditClose').addEventListener('click', () => $('auditModal').classList.add('hidden'));
|
|
|
|
| 534 |
render(); aiChip();
|
| 535 |
if ('gpu' in navigator) {
|
| 536 |
let consent = null; try { consent = localStorage.getItem(AI_CONSENT); } catch { /* ignore */ }
|
| 537 |
+
let fault = null; try { fault = localStorage.getItem(AI_FAULT); } catch { /* ignore */ }
|
| 538 |
+
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(); }
|
| 539 |
+
else modelCached().then(cached => {
|
| 540 |
if (cached || consent === 'yes') { state.cachedStart = cached; getEngine(); }
|
| 541 |
else if (consent === 'later') { state.kbOnly = true; aiChip(); }
|
| 542 |
else {
|