diff --git a/db.py b/db.py index 419fbb8..ec75212 100644 --- a/db.py +++ b/db.py @@ -54,6 +54,16 @@ CREATE TABLE IF NOT EXISTS audit_log ( ); CREATE INDEX IF NOT EXISTS idx_audit_ts ON audit_log(timestamp); CREATE INDEX IF NOT EXISTS idx_audit_user ON audit_log(username); + +CREATE TABLE IF NOT EXISTS feedback ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + timestamp REAL NOT NULL, + username TEXT NOT NULL, + tab_id TEXT, + comment TEXT, + answer TEXT +); +CREATE INDEX IF NOT EXISTS idx_feedback_ts ON feedback(timestamp); """ @@ -76,6 +86,27 @@ def ping(): conn.execute("SELECT 1").fetchone() +def save_feedback(username: str, tab_id: str, comment: str, answer: str): + """Жалоба пользователя на ответ ассистента (кнопка «сообщить об ошибке»).""" + with _conn() as conn: + conn.execute( + "INSERT INTO feedback (timestamp, username, tab_id, comment, answer) " + "VALUES (?, ?, ?, ?, ?)", + (time.time(), username, tab_id, comment, answer), + ) + + +def get_feedback(limit: int = 200) -> list[dict]: + """Последние жалобы — для админ-просмотра.""" + with _conn() as conn: + rows = conn.execute( + "SELECT id, timestamp, username, tab_id, comment, answer " + "FROM feedback ORDER BY id DESC LIMIT ?", + (limit,), + ).fetchall() + return [dict(r) for r in rows] + + def init_db(): with _conn() as conn: conn.executescript(_CREATE) diff --git a/main.py b/main.py index 70710bc..4311e09 100644 --- a/main.py +++ b/main.py @@ -13,7 +13,7 @@ from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, Streamin from fastapi.staticfiles import StaticFiles from auth import authenticate, verify_token, make_download_ticket, verify_download_ticket -from db import clear_history, get_audit_log, get_history, get_history_any_user, init_db, list_sessions, log_action, ping as db_ping, save_message +from db import clear_history, get_audit_log, get_history, get_history_any_user, init_db, list_sessions, log_action, ping as db_ping, save_feedback, save_message from tus_upload import register_tus # Backend: "claude" (Docker sandbox), "glm" (GLM-5 + CAG), "auto" (route by task) @@ -517,6 +517,23 @@ async def chat(request: Request): ) +@app.post("/api/feedback") +async def feedback(request: Request): + """Жалоба на ответ ассистента (кнопка «сообщить об ошибке»). Замыкает + петлю обратной связи — дефекты копятся в БД, а не теряются.""" + user = _get_user(request) + body = await request.json() + comment = (body.get("comment") or "").strip()[:2000] + answer = (body.get("answer") or "")[:8000] + tab_id = _get_tab(request, body) + if not comment and not answer: + raise HTTPException(400, "Empty feedback") + await asyncio.to_thread(save_feedback, user, tab_id, comment, answer) + ip = request.client.host if request.client else None + log_action(user, "feedback", "POST", "/api/feedback", comment[:120], ip, 200) + return {"ok": True} + + @app.get("/api/history") async def history(request: Request): user = _get_user(request) diff --git a/static/chat.html b/static/chat.html index 130bddc..50b77da 100644 --- a/static/chat.html +++ b/static/chat.html @@ -707,6 +707,27 @@ function addMsg(type, text, ts) { }; div.appendChild(btn); } + if (type === 'ai') { + const rep = document.createElement('button'); + rep.className = 'copy-btn report-btn'; + rep.textContent = 'Сообщить об ошибке'; + rep.onclick = async () => { + const comment = prompt('Что не так с этим ответом? (можно оставить пустым)'); + if (comment === null) return; // отмена + rep.disabled = true; + try { + const r = await authFetch('/api/feedback', { + method: 'POST', + headers: {'Content-Type': 'application/json'}, + body: JSON.stringify({comment: comment || '', answer: div._rawText || ''}) + }); + rep.textContent = r.ok ? 'Спасибо, отправлено' : 'Ошибка отправки'; + if (r.ok) rep.classList.add('copied'); + } catch (e) { rep.textContent = 'Ошибка отправки'; } + setTimeout(() => { rep.textContent = 'Сообщить об ошибке'; rep.classList.remove('copied'); rep.disabled = false; }, 2200); + }; + div.appendChild(rep); + } msgs.appendChild(div); msgs.scrollTop = msgs.scrollHeight; return div; @@ -937,12 +958,13 @@ async function sendMessage() { } aiText += data.text; aiDiv._rawText = aiText; - // Re-render markdown (keep time + copy button) - const copyBtn = aiDiv.querySelector('.copy-btn'); + // Re-render markdown, сохраняя время и ВСЕ контрол-кнопки + // (копирование + «сообщить об ошибке» — обе .copy-btn). + const ctrlBtns = Array.from(aiDiv.querySelectorAll('.copy-btn')); const timeEl = aiDiv.querySelector('.msg-time'); aiDiv.innerHTML = renderMarkdown(aiText); if (timeEl) aiDiv.prepend(timeEl); - if (copyBtn) aiDiv.appendChild(copyBtn); + ctrlBtns.forEach(b => aiDiv.appendChild(b)); msgs.scrollTop = msgs.scrollHeight; } else if (eventType === 'tool') { // Show minimal status, not raw code