notes: AI titles for new notes, personal-only access, modal polish

- new note created without a title gets one generated by a background
  worker (createNoteTitleWorker, ai_status column, wake channel,
  notes_changed SSE event, settings toggle notes_ai_enabled)
- notes are strictly personal: list/update/delete/reorder always scoped
  to req.user.id, admin no longer sees other users' notes (403)
- notes modal: focus goes to the text body, random color for new notes,
  ctrl+enter hint, tags hint styling, empty-title 400 fix (optText)
- backup/restore: user_notes.ai_status normalized and restored
This commit is contained in:
dev
2026-10-08 21:47:37 +03:00
parent f226c3f144
commit b5d1fd0948
10 changed files with 427 additions and 34 deletions
+260 -1
View File
@@ -1449,4 +1449,263 @@ function createFeedbackWriter(opts) {
return { start, stop, notify, getInfo };
}
module.exports = { createEntryAutoChecker, createPhotoEnhanceWorker, createLessonReportChecker, createFeedbackWriter, lessonTopicPosition };
function createNoteTitleWorker({ pool, getSetting, logAudit, aiUrl, model, defaultPrompt, bus, onDone }) {
const AI_URL = aiUrl || process.env.AI_URL || 'http://text-corrector:8080';
const MODEL = model || process.env.AI_MODEL || 'qwen2.5-1.5b-instruct-q4_k_m.gguf';
const DEFAULT_PROMPT = defaultPrompt || '';
const TIMEOUT_MS = Math.max(5000, parseInt(process.env.NOTE_AI_TIMEOUT_MS || '60000', 10) || 60000);
const MIN_CHARS = 10;
const MAX_INPUT_CHARS = 2000;
const TITLE_MAX = 100;
const MAX_ATTEMPTS = 3;
let started = false;
let stopped = false;
let idleMs = IDLE_MIN_MS;
let wake = null;
let processing = false;
let currentId = null;
let startedAt = null;
const stats = { checks: 0, generated: 0, skipped: 0, errors: 0, last_at: null, last_error: null };
const attempts = new Map();
function sleep(ms) {
return new Promise((resolve) => {
const t = setTimeout(() => { wake = null; resolve(); }, ms);
wake = () => { clearTimeout(t); wake = null; resolve(); };
});
}
function notify() {
if (wake) wake();
if (bus) bus.publish();
}
if (bus) bus.subscribe(() => notify());
async function isEnabled() {
return String(await getSetting('notes_ai_enabled', 'true')) !== 'false';
}
async function claimNext() {
const client = await pool.connect();
try {
await client.query('BEGIN');
const { rows } = await client.query(
`SELECT id, user_id, note, tags
FROM user_notes
WHERE ai_status = 'pending' AND title = ''
ORDER BY id ASC LIMIT 1 FOR UPDATE SKIP LOCKED`
);
if (!rows.length) {
await client.query('COMMIT');
return null;
}
await client.query(`UPDATE user_notes SET ai_status = 'processing' WHERE id = $1`, [rows[0].id]);
await client.query('COMMIT');
return rows[0];
} catch (e) {
await client.query('ROLLBACK').catch(() => {});
throw e;
} finally {
client.release();
}
}
async function resolveActiveProfile() {
try {
const active = await getSetting('ai_active_profile', 'native');
if (active && active !== 'native') {
const raw = await getSetting('ai_profiles', '[]');
const list = JSON.parse(raw || '[]');
if (Array.isArray(list)) {
return list.find(p => p && p.id === active && p.base_url && p.model) || null;
}
}
} catch (e) {}
return null;
}
function normalizeOpenAiBase(base) {
const b = String(base || '').trim().replace(/\/+$/, '');
if (!/^https?:\/\//i.test(b)) return null;
if (!/\/v1$/i.test(b)) return b + '/v1';
return b;
}
async function callModel(userText, systemPrompt) {
const profile = await resolveActiveProfile();
const headers = { 'Content-Type': 'application/json' };
let url;
let modelName;
let maxTokens;
if (profile) {
const base = normalizeOpenAiBase(profile.base_url);
if (!base) throw new Error('Некорректный base_url профиля ИИ');
url = `${base}/chat/completions`;
modelName = profile.model;
if (profile.api_key) headers.Authorization = `Bearer ${profile.api_key}`;
maxTokens = parseInt(profile.max_tokens, 10) || Math.min(4096, Math.max(1024, userText.length * 2 + 512));
} else {
url = `${AI_URL.replace(/\/+$/, '')}/v1/chat/completions`;
modelName = MODEL;
maxTokens = Math.min(512, Math.max(128, userText.length + 256));
}
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
try {
const res = await fetch(url, {
method: 'POST',
headers,
signal: controller.signal,
body: JSON.stringify({
model: modelName,
messages: [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: userText },
],
temperature: 0.2,
max_tokens: maxTokens,
}),
});
if (!res.ok) throw new Error(`AI service error: ${res.status}`);
const data = await res.json();
const choice = data.choices && data.choices[0];
return (choice && choice.message && choice.message.content || '').trim();
} finally {
clearTimeout(timer);
}
}
function normalizeTitle(out) {
let s = String(out || '').trim();
if (!s) return '';
s = s.replace(/^```[a-zA-Z]*\s*/, '').replace(/```$/, '').trim();
s = s.split(/\r?\n/).map(l => l.trim()).filter(Boolean)[0] || '';
s = s.replace(/^(?:заголовок|title)\s*[:—-]\s*/i, '').trim();
s = s.replace(/^["'«”]+/, '').replace(/["'«»"]+$/, '').trim();
if (s.length > TITLE_MAX) s = s.slice(0, TITLE_MAX).trim();
return s;
}
async function finish(row, status, title, error) {
await pool.query(
`UPDATE user_notes SET
title = CASE WHEN $1 <> '' THEN $1 ELSE title END,
ai_status = $2, updated_at = now()
WHERE id = $3 AND ai_status = 'processing'`,
[title || '', status, row.id]
);
attempts.delete(row.id);
stats.last_at = new Date().toISOString();
stats.last_error = error || null;
if (onDone) await onDone({ row, status, title: title || '', error: error || null });
}
async function processOne(row) {
const text = String(row.note || '').trim();
if (text.length < MIN_CHARS) {
await finish(row, 'skipped', '', null);
stats.skipped++;
return true;
}
const prompt = DEFAULT_PROMPT;
const tags = String(row.tags || '').trim();
const input = text.length > MAX_INPUT_CHARS ? text.slice(0, MAX_INPUT_CHARS) : text;
const context = [tags ? `Теги: ${tags}` : '', 'Текст заметки:', input].filter(l => l !== '').join('\n');
try {
const title = normalizeTitle(await callModel(context, prompt));
if (!title) {
const reason = 'Модель вернула пустой ответ';
await finish(row, 'error', '', reason);
stats.errors++;
return true;
}
await finish(row, 'done', title, null);
stats.checks++;
stats.generated++;
return true;
} catch (e) {
const message = (e && e.message ? e.message : 'error').slice(0, 500);
const tries = (attempts.get(row.id) || 0) + 1;
if (tries < MAX_ATTEMPTS) {
attempts.set(row.id, tries);
await pool.query(`UPDATE user_notes SET ai_status = 'pending' WHERE id = $1`, [row.id]);
if (logAudit) await logAudit(null, 'note.ai.retry', { id: row.id, attempt: tries, error: message });
return false;
}
await finish(row, 'error', '', message);
stats.errors++;
if (logAudit) await logAudit(null, 'note.ai.error', { id: row.id, error: message });
return true;
}
}
async function loop() {
while (!stopped) {
let row = null;
try {
if (!(await isEnabled())) {
await sleep(IDLE_MAX_MS);
continue;
}
row = await claimNext();
} catch (e) {
console.error('Note title AI claim error:', e.message);
await sleep(IDLE_MAX_MS);
continue;
}
if (!row) {
await sleep(idleMs);
idleMs = Math.min(idleMs * 2, IDLE_MAX_MS);
continue;
}
idleMs = IDLE_MIN_MS;
processing = true;
currentId = row.id;
let ok = true;
try {
ok = await processOne(row);
} catch (e) {
console.error('Note title AI process error:', e.message);
} finally {
processing = false;
currentId = null;
}
if (!ok) await sleep(IDLE_MAX_MS);
}
}
function resetStale() {
return pool.query(`UPDATE user_notes SET ai_status = 'pending' WHERE ai_status = 'processing'`);
}
function start() {
if (started) return;
started = true;
startedAt = Date.now();
resetStale()
.catch((e) => console.error('Note title AI reset error:', e.message))
.finally(() => { loop().catch((e) => console.error('Note title AI loop error:', e.message)); });
}
function stop() {
stopped = true;
notify();
}
function getInfo() {
return {
started_at: startedAt ? new Date(startedAt).toISOString() : null,
uptime_ms: startedAt ? Date.now() - startedAt : 0,
processing,
current_id: currentId,
config: { idle_min_ms: IDLE_MIN_MS, idle_max_ms: IDLE_MAX_MS, timeout_ms: TIMEOUT_MS, model: MODEL, ai_url: AI_URL },
...stats,
};
}
return { start, stop, notify, getInfo };
}
module.exports = { createEntryAutoChecker, createPhotoEnhanceWorker, createLessonReportChecker, createFeedbackWriter, createNoteTitleWorker, lessonTopicPosition };