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
+10
View File
@@ -179,6 +179,14 @@ function reqAiStatus(v, fallback) {
return AI_STATUSES.has(s) ? s : fallback; return AI_STATUSES.has(s) ? s : fallback;
} }
function normalizeAiStatus(v) {
if (v === null || v === undefined) return 'none';
const s = String(v);
if (s === 'none' || s === 'pending') return s;
if (s === 'processing') return 'pending';
return ['done', 'skipped', 'error'].includes(s) ? s : 'none';
}
const PROFILE_HREF_RE = /^(https?:\/\/|mailto:|tel:|\/|#)/i; const PROFILE_HREF_RE = /^(https?:\/\/|mailto:|tel:|\/|#)/i;
const PROFILE_EMAIL_RE = /^[\w.+-]+@[\w-]+\.[\w.-]{2,}$/; const PROFILE_EMAIL_RE = /^[\w.+-]+@[\w-]+\.[\w.-]{2,}$/;
@@ -557,6 +565,7 @@ function normalizeRestoreData(data) {
tags: optText(x.tags, 50000) || '', tags: optText(x.tags, 50000) || '',
color: optText(x.color, 7) || '#2563eb', color: optText(x.color, 7) || '#2563eb',
sort_order: optInt(x.sort_order, -10000000, 10000000) ?? 0, sort_order: optInt(x.sort_order, -10000000, 10000000) ?? 0,
ai_status: normalizeAiStatus(x.ai_status),
created_at: optTs(x.created_at), created_at: optTs(x.created_at),
updated_at: optTs(x.updated_at), updated_at: optTs(x.updated_at),
})); }));
@@ -575,6 +584,7 @@ module.exports = {
optInt, optInt,
reqStr, reqStr,
optStr, optStr,
optText,
optTs, optTs,
reqTs, reqTs,
optDate, optDate,
+4
View File
@@ -232,9 +232,11 @@ CREATE TABLE IF NOT EXISTS user_notes (
tags TEXT NOT NULL DEFAULT '', tags TEXT NOT NULL DEFAULT '',
color VARCHAR(7) NOT NULL DEFAULT '#2563eb', color VARCHAR(7) NOT NULL DEFAULT '#2563eb',
sort_order INT NOT NULL DEFAULT 0, sort_order INT NOT NULL DEFAULT 0,
ai_status VARCHAR(20) NOT NULL DEFAULT 'none',
created_at TIMESTAMPTZ DEFAULT now(), created_at TIMESTAMPTZ DEFAULT now(),
updated_at TIMESTAMPTZ DEFAULT now() updated_at TIMESTAMPTZ DEFAULT now()
); );
CREATE INDEX IF NOT EXISTS idx_user_notes_pending ON user_notes(ai_status, id) WHERE ai_status = 'pending';
CREATE TABLE IF NOT EXISTS sessions ( CREATE TABLE IF NOT EXISTS sessions (
id SERIAL PRIMARY KEY, id SERIAL PRIMARY KEY,
@@ -432,6 +434,8 @@ ON CONFLICT (key) DO NOTHING;
INSERT INTO settings (key, value) VALUES ('lesson_ai_enabled', 'true') INSERT INTO settings (key, value) VALUES ('lesson_ai_enabled', 'true')
ON CONFLICT (key) DO NOTHING; ON CONFLICT (key) DO NOTHING;
INSERT INTO settings (key, value) VALUES ('notes_ai_enabled', 'true')
ON CONFLICT (key) DO NOTHING;
INSERT INTO settings (key, value) VALUES ('lesson_ai_prompt', 'Ты — редактор сообщений тьютора детской IT-школы. INSERT INTO settings (key, value) VALUES ('lesson_ai_prompt', 'Ты — редактор сообщений тьютора детской IT-школы.
Переработай исходный текст занятия так, чтобы он звучал естественно и грамотно, как будто его написал живой тьютор родителю, а не нейросеть. Переработай исходный текст занятия так, чтобы он звучал естественно и грамотно, как будто его написал живой тьютор родителю, а не нейросеть.
+3
View File
@@ -190,6 +190,9 @@ CREATE TABLE IF NOT EXISTS user_notes (
); );
ALTER TABLE user_notes ADD COLUMN IF NOT EXISTS sort_order INT NOT NULL DEFAULT 0; ALTER TABLE user_notes ADD COLUMN IF NOT EXISTS sort_order INT NOT NULL DEFAULT 0;
ALTER TABLE user_notes ADD COLUMN IF NOT EXISTS ai_status VARCHAR(20) NOT NULL DEFAULT 'none';
CREATE INDEX IF NOT EXISTS idx_user_notes_pending ON user_notes(ai_status, id) WHERE ai_status = 'pending';
INSERT INTO settings (key, value) VALUES ('notes_ai_enabled', 'true') ON CONFLICT (key) DO NOTHING;
CREATE TABLE IF NOT EXISTS api_keys ( CREATE TABLE IF NOT EXISTS api_keys (
id SERIAL PRIMARY KEY, id SERIAL PRIMARY KEY,
+5
View File
@@ -97,6 +97,11 @@ const ACTION_LABELS = {
'feedback.update': 'Изменён отзыв', 'feedback.update': 'Изменён отзыв',
'feedback.ai.run': 'ИИ сформировал отзыв', 'feedback.ai.run': 'ИИ сформировал отзыв',
'feedback.ai.error': 'Ошибка ИИ при формировании отзыва', 'feedback.ai.error': 'Ошибка ИИ при формировании отзыва',
'note.reorder': 'Изменён порядок заметок',
'note.delete': 'Удалена заметка',
'note.ai.title': 'ИИ придумал заголовок заметки',
'note.ai.error': 'Ошибка ИИ при генерации заголовка заметки',
'note.ai.retry': 'ИИ повторил генерацию заголовка заметки',
}; };
const AUDIT_PAGE_SIZE = 50; const AUDIT_PAGE_SIZE = 50;
+40 -3
View File
@@ -5,6 +5,11 @@
let editingId = null; let editingId = null;
let dragId = null; let dragId = null;
let saving = false; let saving = false;
const NOTE_COLORS = ['#2563eb', '#4f46e5', '#7c3aed', '#db2777', '#dc2626', '#ea580c', '#ca8a04', '#16a34a', '#0d9488', '#0891b2'];
function randomColor() {
return NOTE_COLORS[Math.floor(Math.random() * NOTE_COLORS.length)];
}
function hdr() { function hdr() {
const t = sessionStorage.getItem('authToken'); const t = sessionStorage.getItem('authToken');
@@ -29,6 +34,12 @@
const body = n.note const body = n.note
? esc(n.note) ? esc(n.note)
: '<span class="note-empty-note">Без текста</span>'; : '<span class="note-empty-note">Без текста</span>';
const generating = !n.title && (n.ai_status === 'pending' || n.ai_status === 'processing');
const titleHtml = n.title
? esc(n.title)
: generating
? '<span class="note-empty-note">Заголовок генерируется…</span>'
: esc('Без заголовка');
return '<div class="note-card" data-id="' + n.id + '" style="--ncolor:' + color + '">' + return '<div class="note-card" data-id="' + n.id + '" style="--ncolor:' + color + '">' +
'<div class="note-card-head">' + '<div class="note-card-head">' +
'<span class="note-drag" draggable="true" title="Перетащите, чтобы изменить порядок">⠿</span>' + '<span class="note-drag" draggable="true" title="Перетащите, чтобы изменить порядок">⠿</span>' +
@@ -36,7 +47,7 @@
'<input type="color" id="noteColorPicker-' + n.id + '" value="' + color + '" style="display:none">' + '<input type="color" id="noteColorPicker-' + n.id + '" value="' + color + '" style="display:none">' +
'<span class="note-color-swatch" style="background:' + color + '" title="Изменить цвет"></span>' + '<span class="note-color-swatch" style="background:' + color + '" title="Изменить цвет"></span>' +
'</div>' + '</div>' +
'<div class="note-card-title">' + esc(n.title || 'Без заголовка') + '</div>' + '<div class="note-card-title">' + titleHtml + '</div>' +
tagsHtml + tagsHtml +
'</div>' + '</div>' +
'<div class="note-card-note">' + body + '</div>' + '<div class="note-card-note">' + body + '</div>' +
@@ -127,14 +138,14 @@
document.getElementById('notesTitle').value = note ? note.title : ''; document.getElementById('notesTitle').value = note ? note.title : '';
document.getElementById('notesNote').value = note ? note.note : ''; document.getElementById('notesNote').value = note ? note.note : '';
document.getElementById('notesTags').value = note ? note.tags : ''; document.getElementById('notesTags').value = note ? note.tags : '';
const color = note && /^#[0-9a-fA-F]{6}$/.test(note.color || '') ? note.color : '#2563eb'; const color = note && /^#[0-9a-fA-F]{6}$/.test(note.color || '') ? note.color : randomColor();
document.getElementById('notesColor').value = color; document.getElementById('notesColor').value = color;
document.getElementById('notesColorPreview').style.background = color; document.getElementById('notesColorPreview').style.background = color;
const row = document.getElementById('notesColorRow'); const row = document.getElementById('notesColorRow');
if (row) row.style.setProperty('--ncolor', color); if (row) row.style.setProperty('--ncolor', color);
document.getElementById('notesModal').classList.add('open'); document.getElementById('notesModal').classList.add('open');
renderIcons(); renderIcons();
setTimeout(() => document.getElementById('notesTitle').focus(), 50); setTimeout(() => document.getElementById('notesNote').focus(), 50);
} }
function closeModal() { function closeModal() {
@@ -291,6 +302,31 @@
} }
} }
let liveSource = null;
let liveReconnectTimer = null;
let liveReloadTimer = null;
function connectNotesLive() {
if (liveSource) { liveSource.close(); liveSource = null; }
const connect = () => {
const t = sessionStorage.getItem('authToken');
if (!t) return;
liveSource = new EventSource(`${API}/api/events?token=${encodeURIComponent(t)}`);
const scheduleReload = () => {
if (liveReloadTimer) clearTimeout(liveReloadTimer);
liveReloadTimer = setTimeout(() => { liveReloadTimer = null; loadNotes(); }, 300);
};
liveSource.addEventListener('notes_changed', scheduleReload);
liveSource.onerror = () => {
if (liveSource) { liveSource.close(); liveSource = null; }
if (liveReconnectTimer) clearTimeout(liveReconnectTimer);
liveReconnectTimer = setTimeout(connect, 5000);
};
};
connect();
window.addEventListener('beforeunload', () => { if (liveSource) liveSource.close(); });
}
async function init() { async function init() {
if (!(await checkAuth())) return; if (!(await checkAuth())) return;
buildSidebar(document.body.dataset.page); buildSidebar(document.body.dataset.page);
@@ -298,6 +334,7 @@
bindPage(); bindPage();
renderIcons(); renderIcons();
await loadNotes(); await loadNotes();
connectNotesLive();
} }
init(); init();
+4 -2
View File
@@ -1,6 +1,6 @@
const DIRTY_FIELDS = ['systemName', 'timezone', 'timeFormat', 'spamInterval', 'footerLeft', 'footerRight', 'aiPrompt', 'aiAutoCheck', 'lessonAiPrompt', 'lessonAiEnabled', 'shareShowMessage', 'shareShowDate', 'shareShowNames', 'shareShowPhotos', 'cookieNoticeText', 'photoResolution', 'photoQuality', 'photoEngine', 'camEnabled', 'photoAiFaceMode', 'photoAiFaceModel', 'photoAiDevicePref', 'trashPurgeDays', 'notifyEnabled', 'notifyRetentionDays']; const DIRTY_FIELDS = ['systemName', 'timezone', 'timeFormat', 'spamInterval', 'footerLeft', 'footerRight', 'aiPrompt', 'aiAutoCheck', 'lessonAiPrompt', 'lessonAiEnabled', 'notesAiEnabled', 'shareShowMessage', 'shareShowDate', 'shareShowNames', 'shareShowPhotos', 'cookieNoticeText', 'photoResolution', 'photoQuality', 'photoEngine', 'camEnabled', 'photoAiFaceMode', 'photoAiFaceModel', 'photoAiDevicePref', 'trashPurgeDays', 'notifyEnabled', 'notifyRetentionDays'];
const NOTIFY_IDS = []; const NOTIFY_IDS = [];
const SECTION_IDS = ['sec-system', 'sec-stack', 'sec-brand', 'sec-datetime', 'sec-antispam', 'sec-share', 'sec-ai', 'sec-lesson-ai', 'sec-backup', 'sec-trash', 'sec-form', 'sec-notify', 'sec-photo', 'sec-photo-ai', 'sec-bans']; const SECTION_IDS = ['sec-system', 'sec-stack', 'sec-brand', 'sec-datetime', 'sec-antispam', 'sec-share', 'sec-ai', 'sec-lesson-ai', 'sec-notes-ai', 'sec-backup', 'sec-trash', 'sec-form', 'sec-notify', 'sec-photo', 'sec-photo-ai', 'sec-bans'];
const SPAM_MAX = 10080; const SPAM_MAX = 10080;
const BAN_REASONS = { const BAN_REASONS = {
'honeypot': 'Антиспам-поле', 'honeypot': 'Антиспам-поле',
@@ -285,6 +285,7 @@ async function loadSettings() {
document.getElementById('aiAutoCheck').checked = s.ai_autocheck_enabled !== 'false'; document.getElementById('aiAutoCheck').checked = s.ai_autocheck_enabled !== 'false';
document.getElementById('lessonAiEnabled').checked = s.lesson_ai_enabled !== 'false'; document.getElementById('lessonAiEnabled').checked = s.lesson_ai_enabled !== 'false';
document.getElementById('lessonAiPrompt').value = s.lesson_ai_prompt || ''; document.getElementById('lessonAiPrompt').value = s.lesson_ai_prompt || '';
document.getElementById('notesAiEnabled').checked = s.notes_ai_enabled !== 'false';
document.getElementById('shareShowMessage').checked = s.share_show_student_message === 'true'; document.getElementById('shareShowMessage').checked = s.share_show_student_message === 'true';
document.getElementById('shareShowDate').checked = s.share_show_entry_date === 'true'; document.getElementById('shareShowDate').checked = s.share_show_entry_date === 'true';
document.getElementById('shareShowNames').checked = s.share_show_student_names !== 'false'; document.getElementById('shareShowNames').checked = s.share_show_student_names !== 'false';
@@ -890,6 +891,7 @@ async function saveSettings() {
ai_autocheck_enabled: document.getElementById('aiAutoCheck').checked ? 'true' : 'false', ai_autocheck_enabled: document.getElementById('aiAutoCheck').checked ? 'true' : 'false',
lesson_ai_enabled: document.getElementById('lessonAiEnabled').checked ? 'true' : 'false', lesson_ai_enabled: document.getElementById('lessonAiEnabled').checked ? 'true' : 'false',
lesson_ai_prompt: document.getElementById('lessonAiPrompt').value.trim(), lesson_ai_prompt: document.getElementById('lessonAiPrompt').value.trim(),
notes_ai_enabled: document.getElementById('notesAiEnabled').checked ? 'true' : 'false',
share_show_student_message: document.getElementById('shareShowMessage').checked ? 'true' : 'false', share_show_student_message: document.getElementById('shareShowMessage').checked ? 'true' : 'false',
share_show_entry_date: document.getElementById('shareShowDate').checked ? 'true' : 'false', share_show_entry_date: document.getElementById('shareShowDate').checked ? 'true' : 'false',
share_show_student_names: document.getElementById('shareShowNames').checked ? 'true' : 'false', share_show_student_names: document.getElementById('shareShowNames').checked ? 'true' : 'false',
+3 -1
View File
@@ -57,6 +57,8 @@
.note-empty { text-align: center; color: var(--muted); padding: 32px 16px; font-size: .9rem; border: 1px dashed var(--border); border-radius: 12px; } .note-empty { text-align: center; color: var(--muted); padding: 32px 16px; font-size: .9rem; border: 1px dashed var(--border); border-radius: 12px; }
.note-modal-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; } .note-modal-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
.note-modal-head h3 { margin: 0; font-size: 1.05rem; } .note-modal-head h3 { margin: 0; font-size: 1.05rem; }
.settings-field .hint { font-size: .78rem; color: var(--muted); line-height: 1.5; }
.settings-field label .hint { font-weight: 400; margin-left: 6px; }
</style> </style>
</head> </head>
<body data-page="notes"> <body data-page="notes">
@@ -83,7 +85,7 @@
<input id="notesTitle" class="settings-input" maxlength="200" placeholder="Краткое название заметки"> <input id="notesTitle" class="settings-input" maxlength="200" placeholder="Краткое название заметки">
</div> </div>
<div class="settings-field"> <div class="settings-field">
<label>Заметка</label> <label>Заметка<span class="hint">ctrl+enter отправить</span></label>
<textarea id="notesNote" class="settings-input" rows="6" placeholder="Текст заметки"></textarea> <textarea id="notesNote" class="settings-input" rows="6" placeholder="Текст заметки"></textarea>
</div> </div>
<div class="settings-field"> <div class="settings-field">
+14
View File
@@ -31,6 +31,7 @@
<a href="#sec-notify" data-nav="sec-notify"><i data-lucide="bell"></i> Уведомления</a> <a href="#sec-notify" data-nav="sec-notify"><i data-lucide="bell"></i> Уведомления</a>
<a href="#sec-ai" data-nav="sec-ai"><i data-lucide="bot"></i> ИИ</a> <a href="#sec-ai" data-nav="sec-ai"><i data-lucide="bot"></i> ИИ</a>
<a href="#sec-lesson-ai" data-nav="sec-lesson-ai"><i data-lucide="notebook-pen"></i> Шаблон отчёта</a> <a href="#sec-lesson-ai" data-nav="sec-lesson-ai"><i data-lucide="notebook-pen"></i> Шаблон отчёта</a>
<a href="#sec-notes-ai" data-nav="sec-notes-ai"><i data-lucide="sticky-note"></i> Заголовки заметок</a>
<a href="#sec-backup" data-nav="sec-backup"><i data-lucide="database"></i> Бэкапы</a> <a href="#sec-backup" data-nav="sec-backup"><i data-lucide="database"></i> Бэкапы</a>
<a href="#sec-trash" data-nav="sec-trash"><i data-lucide="trash-2"></i> Корзина</a> <a href="#sec-trash" data-nav="sec-trash"><i data-lucide="trash-2"></i> Корзина</a>
<a href="#sec-bans" data-nav="sec-bans"><i data-lucide="shield-off"></i> Блокировки</a> <a href="#sec-bans" data-nav="sec-bans"><i data-lucide="shield-off"></i> Блокировки</a>
@@ -209,6 +210,19 @@
</div> </div>
</div> </div>
<div class="settings-card" id="sec-notes-ai">
<div class="card-head">
<div class="ic"><i data-lucide="sticky-note"></i></div>
<h3>Заголовки заметок</h3>
</div>
<p class="hint">Если заголовок не заполнен при создании заметки, модель сама придумает его по тексту. Заголовок можно вручную заменить в любой момент.</p>
<label class="toggle">
<input type="checkbox" id="notesAiEnabled">
<span class="toggle-track"><span class="toggle-thumb"></span></span>
<span class="toggle-text"><b>Генерировать заголовок автоматически</b><small>Работает в фоне — карточка обновится сама</small></span>
</label>
</div>
<div class="settings-card"> <div class="settings-card">
<div class="card-head"> <div class="card-head">
<div class="ic"><i data-lucide="boxes"></i></div> <div class="ic"><i data-lucide="boxes"></i></div>
+84 -27
View File
@@ -6,7 +6,7 @@ const { ipKeyGenerator } = require('express-rate-limit');
const helmet = require('helmet'); const helmet = require('helmet');
const bcrypt = require('bcrypt'); const bcrypt = require('bcrypt');
const heicConvert = require('heic-convert'); const heicConvert = require('heic-convert');
const { createEntryAutoChecker, createPhotoEnhanceWorker, createLessonReportChecker, createFeedbackWriter } = require('./worker'); const { createEntryAutoChecker, createPhotoEnhanceWorker, createLessonReportChecker, createFeedbackWriter, createNoteTitleWorker } = require('./worker');
const { createZipWriter, renderStudentReport } = require('./student-report'); const { createZipWriter, renderStudentReport } = require('./student-report');
const { createStorage, mimeFor } = require('./storage'); const { createStorage, mimeFor } = require('./storage');
@@ -24,6 +24,7 @@ const {
optInt, optInt,
reqStr, reqStr,
optStr, optStr,
optText,
optTs, optTs,
reqTs, reqTs,
optDate, optDate,
@@ -134,6 +135,7 @@ const AI_WAKE_CHANNEL = 'whatido:wake:ai';
const PHOTO_WAKE_CHANNEL = 'whatido:wake:photo'; const PHOTO_WAKE_CHANNEL = 'whatido:wake:photo';
const LESSON_AI_WAKE_CHANNEL = 'whatido:wake:lesson-ai'; const LESSON_AI_WAKE_CHANNEL = 'whatido:wake:lesson-ai';
const FEEDBACK_WAKE_CHANNEL = 'whatido:wake:feedback'; const FEEDBACK_WAKE_CHANNEL = 'whatido:wake:feedback';
const NOTE_AI_WAKE_CHANNEL = 'whatido:wake:note-ai';
function createWorkerBus(channel) { function createWorkerBus(channel) {
return { return {
@@ -172,7 +174,7 @@ function dispatchEvent(payload) {
writeFrame('feedback_status', payload); writeFrame('feedback_status', payload);
return; return;
} }
if (payload && (payload.type === 'entries_changed' || payload.type === 'lessons_changed' || payload.type === 'shorts_changed')) { if (payload && (payload.type === 'entries_changed' || payload.type === 'lessons_changed' || payload.type === 'shorts_changed' || payload.type === 'notes_changed')) {
writeFrame(payload.type, { ts: Date.now() }); writeFrame(payload.type, { ts: Date.now() });
return; return;
} }
@@ -206,6 +208,11 @@ function broadcastFeedbackChanged() {
.catch(err => console.error('Publish failed:', err.message)); .catch(err => console.error('Publish failed:', err.message));
} }
function broadcastNotesChanged() {
cache.publish(EVENTS_CHANNEL, { type: 'notes_changed' })
.catch(err => console.error('Publish failed:', err.message));
}
function broadcastAiStatus(payload) { function broadcastAiStatus(payload) {
cache.publish(EVENTS_CHANNEL, { type: 'ai_status', ...payload }) cache.publish(EVENTS_CHANNEL, { type: 'ai_status', ...payload })
.catch(err => console.error('Publish failed:', err.message)); .catch(err => console.error('Publish failed:', err.message));
@@ -1747,11 +1754,15 @@ async function ensureUserNotesTable() {
tags TEXT NOT NULL DEFAULT '', tags TEXT NOT NULL DEFAULT '',
color VARCHAR(7) NOT NULL DEFAULT '#2563eb', color VARCHAR(7) NOT NULL DEFAULT '#2563eb',
sort_order INT NOT NULL DEFAULT 0, sort_order INT NOT NULL DEFAULT 0,
ai_status VARCHAR(20) NOT NULL DEFAULT 'none',
created_at TIMESTAMPTZ DEFAULT now(), created_at TIMESTAMPTZ DEFAULT now(),
updated_at TIMESTAMPTZ DEFAULT now() updated_at TIMESTAMPTZ DEFAULT now()
)`); )`);
await pool.query('ALTER TABLE user_notes ADD COLUMN IF NOT EXISTS sort_order INT NOT NULL DEFAULT 0'); await pool.query('ALTER TABLE user_notes ADD COLUMN IF NOT EXISTS sort_order INT NOT NULL DEFAULT 0');
await pool.query("ALTER TABLE user_notes ADD COLUMN IF NOT EXISTS ai_status VARCHAR(20) NOT NULL DEFAULT 'none'");
await pool.query('CREATE INDEX IF NOT EXISTS idx_user_notes_user_id ON user_notes(user_id)'); await pool.query('CREATE INDEX IF NOT EXISTS idx_user_notes_user_id ON user_notes(user_id)');
await pool.query(`CREATE INDEX IF NOT EXISTS idx_user_notes_pending ON user_notes(ai_status, id) WHERE ai_status = 'pending'`);
await pool.query("INSERT INTO settings (key, value) VALUES ('notes_ai_enabled', 'true') ON CONFLICT (key) DO NOTHING");
} }
async function ensureApiKeysTable() { async function ensureApiKeysTable() {
@@ -3288,15 +3299,22 @@ app.put('/api/users/:id', requireAuth, requireAdmin, async (req, res) => {
const NOTE_TITLE_MAX = 200; const NOTE_TITLE_MAX = 200;
const NOTE_TEXT_MAX = 100000; const NOTE_TEXT_MAX = 100000;
const NOTE_TAGS_MAX = 10; const NOTE_TAGS_MAX = 10;
const NOTES_AI_DEFAULT_PROMPT = 'Ты придумываешь короткий заголовок для личной заметки пользователя. Тебе дадут текст заметки и, возможно, теги.\n' +
'Требования к заголовку:\n' +
'- 2–6 слов, максимум 60 символов\n' +
'- отражает суть заметки, без воды и общих слов\n' +
'- пишется с большой буквы, без кавычек, без точки в конце\n' +
'- язык заголовка совпадает с языком заметки\n' +
'Верни только сам заголовок, ничего больше.';
async function findNote(user, id) { async function findNote(user, id) {
const { rows } = await pool.query( const { rows } = await pool.query(
`SELECT id, user_id, title, note, tags, color, created_at, updated_at `SELECT id, user_id, title, note, tags, color, ai_status, created_at, updated_at
FROM user_notes WHERE id = $1`, [id] FROM user_notes WHERE id = $1`, [id]
); );
const note = rows[0]; const note = rows[0];
if (!note) return null; if (!note) return null;
if (user.role !== 'admin' && note.user_id !== user.id) { if (note.user_id !== user.id) {
const e = new Error('Forbidden'); const e = new Error('Forbidden');
e.forbidden = true; e.forbidden = true;
throw e; throw e;
@@ -3306,14 +3324,12 @@ async function findNote(user, id) {
app.get('/api/notes', requireAuth, async (req, res) => { app.get('/api/notes', requireAuth, async (req, res) => {
try { try {
const where = req.user.role === 'admin' ? '' : 'user_id = $1';
const params = req.user.role === 'admin' ? [] : [req.user.id];
const { rows } = await pool.query( const { rows } = await pool.query(
`SELECT id, user_id, title, note, tags, color, sort_order, created_at, updated_at `SELECT id, user_id, title, note, tags, color, sort_order, ai_status, created_at, updated_at
FROM user_notes FROM user_notes
${where ? `WHERE ${where}` : ''} WHERE user_id = $1
ORDER BY sort_order ASC, updated_at DESC`, ORDER BY sort_order ASC, updated_at DESC`,
params [req.user.id]
); );
res.json({ items: rows }); res.json({ items: rows });
} catch (e) { } catch (e) {
@@ -3324,8 +3340,9 @@ app.get('/api/notes', requireAuth, async (req, res) => {
app.post('/api/notes', requireAuth, async (req, res) => { app.post('/api/notes', requireAuth, async (req, res) => {
try { try {
const title = optStr(req.body?.title, NOTE_TITLE_MAX) || ''; const title = optText(req.body?.title, NOTE_TITLE_MAX);
const note = optStr(req.body?.note, NOTE_TEXT_MAX) || ''; const note = optText(req.body?.note, NOTE_TEXT_MAX);
if (!title && !note) return res.status(400).json({ error: 'Заполните текст заметки' });
let tags = ''; let tags = '';
if (req.body?.tags !== undefined && req.body.tags !== null) { if (req.body?.tags !== undefined && req.body.tags !== null) {
const list = String(req.body.tags).split(',').map(t => t.trim()).filter(Boolean); const list = String(req.body.tags).split(',').map(t => t.trim()).filter(Boolean);
@@ -3333,13 +3350,15 @@ app.post('/api/notes', requireAuth, async (req, res) => {
} }
let color = String(req.body?.color || '#2563eb').trim(); let color = String(req.body?.color || '#2563eb').trim();
if (!/^#[0-9a-fA-F]{6}$/.test(color)) color = '#2563eb'; if (!/^#[0-9a-fA-F]{6}$/.test(color)) color = '#2563eb';
const aiWanted = !title && (await getSetting('notes_ai_enabled', 'true')) !== 'false';
const { rows } = await pool.query( const { rows } = await pool.query(
`INSERT INTO user_notes (user_id, title, note, tags, color, sort_order) `INSERT INTO user_notes (user_id, title, note, tags, color, sort_order, ai_status)
VALUES ($1, $2, $3, $4, $5, VALUES ($1, $2, $3, $4, $5,
COALESCE((SELECT MIN(sort_order) FROM user_notes WHERE user_id = $1), 1) - 1) COALESCE((SELECT MIN(sort_order) FROM user_notes WHERE user_id = $1), 1) - 1, $6)
RETURNING id, user_id, title, note, tags, color, sort_order, created_at, updated_at`, RETURNING id, user_id, title, note, tags, color, sort_order, ai_status, created_at, updated_at`,
[req.user.id, title, note, tags, color] [req.user.id, title, note, tags, color, aiWanted ? 'pending' : 'none']
); );
if (aiWanted) wakeNoteAiWorker();
res.json({ item: rows[0] }); res.json({ item: rows[0] });
} catch (e) { } catch (e) {
if (e.message === 'Invalid string length') return res.status(400).json({ error: 'Неверная длина поля' }); if (e.message === 'Invalid string length') return res.status(400).json({ error: 'Неверная длина поля' });
@@ -3363,9 +3382,10 @@ app.put('/api/notes/reorder', requireAuth, async (req, res) => {
try { try {
await client.query('BEGIN'); await client.query('BEGIN');
for (let i = 0; i < ids.length; i++) { for (let i = 0; i < ids.length; i++) {
const { rowCount } = req.user.role === 'admin' const { rowCount } = await client.query(
? await client.query('UPDATE user_notes SET sort_order = $1 WHERE id = $2', [i + 1, ids[i]]) 'UPDATE user_notes SET sort_order = $1 WHERE id = $2 AND user_id = $3',
: await client.query('UPDATE user_notes SET sort_order = $1 WHERE id = $2 AND user_id = $3', [i + 1, ids[i], req.user.id]); [i + 1, ids[i], req.user.id]
);
if (!rowCount) throw { http: 404, message: 'Заметка не найдена' }; if (!rowCount) throw { http: 404, message: 'Заметка не найдена' };
} }
await client.query('COMMIT'); await client.query('COMMIT');
@@ -3391,8 +3411,9 @@ app.put('/api/notes/:id', requireAuth, async (req, res) => {
const note = await findNote(req.user, id); const note = await findNote(req.user, id);
if (!note) return res.status(404).json({ error: 'Not found' }); if (!note) return res.status(404).json({ error: 'Not found' });
if (note.forbidden) return res.status(403).json({ error: 'Нет доступа' }); if (note.forbidden) return res.status(403).json({ error: 'Нет доступа' });
const title = optStr(req.body?.title, NOTE_TITLE_MAX) || ''; const title = optText(req.body?.title, NOTE_TITLE_MAX);
const text = optStr(req.body?.note, NOTE_TEXT_MAX) || ''; const text = optText(req.body?.note, NOTE_TEXT_MAX);
if (!title && !text) return res.status(400).json({ error: 'Заполните текст заметки' });
let tags = ''; let tags = '';
if (req.body?.tags !== undefined && req.body.tags !== null) { if (req.body?.tags !== undefined && req.body.tags !== null) {
const list = String(req.body.tags).split(',').map(t => t.trim()).filter(Boolean); const list = String(req.body.tags).split(',').map(t => t.trim()).filter(Boolean);
@@ -3400,12 +3421,14 @@ app.put('/api/notes/:id', requireAuth, async (req, res) => {
} }
let color = String(req.body?.color || note.color).trim(); let color = String(req.body?.color || note.color).trim();
if (!/^#[0-9a-fA-F]{6}$/.test(color)) color = note.color; if (!/^#[0-9a-fA-F]{6}$/.test(color)) color = note.color;
const aiWanted = !title && (await getSetting('notes_ai_enabled', 'true')) !== 'false';
const { rows } = await pool.query( const { rows } = await pool.query(
`UPDATE user_notes SET title=$1, note=$2, tags=$3, color=$4, updated_at=now() `UPDATE user_notes SET title=$1, note=$2, tags=$3, color=$4, ai_status=$6, updated_at=now()
WHERE id=$5 WHERE id=$5 AND user_id=$7
RETURNING id, user_id, title, note, tags, color, created_at, updated_at`, RETURNING id, user_id, title, note, tags, color, ai_status, created_at, updated_at`,
[title, text, tags, color, id] [title, text, tags, color, id, title ? 'none' : (aiWanted ? 'pending' : 'none'), req.user.id]
); );
if (aiWanted) wakeNoteAiWorker();
res.json({ item: rows[0] }); res.json({ item: rows[0] });
} catch (e) { } catch (e) {
if (e.message === 'Invalid string length') return res.status(400).json({ error: 'Неверная длина поля' }); if (e.message === 'Invalid string length') return res.status(400).json({ error: 'Неверная длина поля' });
@@ -3422,10 +3445,11 @@ app.delete('/api/notes/:id', requireAuth, async (req, res) => {
const note = await findNote(req.user, id); const note = await findNote(req.user, id);
if (!note) return res.status(404).json({ error: 'Not found' }); if (!note) return res.status(404).json({ error: 'Not found' });
if (note.forbidden) return res.status(403).json({ error: 'Нет доступа' }); if (note.forbidden) return res.status(403).json({ error: 'Нет доступа' });
await pool.query('DELETE FROM user_notes WHERE id = $1', [id]); await pool.query('DELETE FROM user_notes WHERE id = $1 AND user_id = $2', [id, req.user.id]);
await logAudit(req, 'note.delete', { id }); await logAudit(req, 'note.delete', { id });
res.json({ ok: true }); res.json({ ok: true });
} catch (e) { } catch (e) {
if (e.forbidden) return res.status(403).json({ error: 'Нет доступа' });
console.error('notes delete:', e); console.error('notes delete:', e);
res.status(500).json({ error: 'Не удалось удалить заметку' }); res.status(500).json({ error: 'Не удалось удалить заметку' });
} }
@@ -3859,6 +3883,9 @@ app.put('/api/settings', requireAdmin, async (req, res) => {
if (key === 'lesson_ai_enabled' && !['true', 'false'].includes(String(value))) { if (key === 'lesson_ai_enabled' && !['true', 'false'].includes(String(value))) {
return res.status(400).json({ error: 'lesson_ai_enabled должен быть true или false' }); return res.status(400).json({ error: 'lesson_ai_enabled должен быть true или false' });
} }
if (key === 'notes_ai_enabled' && !['true', 'false'].includes(String(value))) {
return res.status(400).json({ error: 'notes_ai_enabled должен быть true или false' });
}
if (key === 'lesson_ai_prompt' && String(value).length > 8000) { if (key === 'lesson_ai_prompt' && String(value).length > 8000) {
return res.status(400).json({ error: 'lesson_ai_prompt длиннее 8000 символов' }); return res.status(400).json({ error: 'lesson_ai_prompt длиннее 8000 символов' });
} }
@@ -4143,6 +4170,7 @@ let entryAutoChecker = null;
let photoWorker = null; let photoWorker = null;
let lessonAiChecker = null; let lessonAiChecker = null;
let feedbackWorker = null; let feedbackWorker = null;
let noteAiWorker = null;
function wakeLessonAiWorker() { function wakeLessonAiWorker() {
if (lessonAiChecker) lessonAiChecker.notify(); if (lessonAiChecker) lessonAiChecker.notify();
@@ -4152,6 +4180,24 @@ function wakeFeedbackWorker() {
if (feedbackWorker) feedbackWorker.notify(); if (feedbackWorker) feedbackWorker.notify();
} }
function wakeNoteAiWorker() {
if (noteAiWorker) noteAiWorker.notify();
}
async function onNoteAiDone({ row, status, title, error }) {
try {
broadcastNotesChanged();
if (!logAudit) return;
if (status === 'done') {
await logAudit(null, 'note.ai.title', { id: row.id, title: String(title || '').slice(0, 200) });
} else if (status === 'error') {
await logAudit(null, 'note.ai.error', { id: row.id, error: String(error || '').slice(0, 500) });
}
} catch (e) {
console.error('Note AI onDone error:', e.message);
}
}
async function onLessonAiDone({ row, status, text, aiText, error }) { async function onLessonAiDone({ row, status, text, aiText, error }) {
invalidateLessonReports(); invalidateLessonReports();
cache.publish(EVENTS_CHANNEL, { cache.publish(EVENTS_CHANNEL, {
@@ -4603,8 +4649,8 @@ app.post('/api/restore', requireAdmin, uploadBackup.single('backup'), async (req
const okUser = (await client.query('SELECT 1 FROM users WHERE id = $1', [x.user_id])).rowCount; const okUser = (await client.query('SELECT 1 FROM users WHERE id = $1', [x.user_id])).rowCount;
if (!okUser) continue; if (!okUser) continue;
await client.query( await client.query(
'INSERT INTO user_notes (id, user_id, title, note, tags, color, sort_order, created_at, updated_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)', 'INSERT INTO user_notes (id, user_id, title, note, tags, color, sort_order, ai_status, created_at, updated_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)',
[x.id, x.user_id, x.title, x.note, x.tags, x.color, x.sort_order, x.created_at || null, x.updated_at || null] [x.id, x.user_id, x.title, x.note, x.tags, x.color, x.sort_order, x.ai_status || 'none', x.created_at || null, x.updated_at || null]
); );
} }
for (const x of ndata.user_branches) { for (const x of ndata.user_branches) {
@@ -9853,4 +9899,15 @@ try { await ensureFeedbacksTable(); } catch (err) { console.error('Feedbacks tab
}); });
feedbackWorker.start(); feedbackWorker.start();
console.log('Feedback AI worker started'); console.log('Feedback AI worker started');
noteAiWorker = createNoteTitleWorker({
pool,
getSetting,
logAudit,
aiUrl: AI_URL,
defaultPrompt: NOTES_AI_DEFAULT_PROMPT,
bus: createWorkerBus(NOTE_AI_WAKE_CHANNEL),
onDone: onNoteAiDone,
});
noteAiWorker.start();
console.log('Note title AI worker started');
})(); })();
+260 -1
View File
@@ -1449,4 +1449,263 @@ function createFeedbackWriter(opts) {
return { start, stop, notify, getInfo }; 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 };