From 312eaddb7462f70ed5924f9c2187e395c67a4672 Mon Sep 17 00:00:00 2001 From: anor Date: Fri, 17 Jul 2026 22:30:17 +1000 Subject: [PATCH] =?UTF-8?q?feat(ui):=20=D1=81=D1=80=D0=B5=D0=B7=D1=8B=20?= =?UTF-8?q?=D0=A4=D0=B0=D0=B7=D0=B02=20(a11y/=D0=BC=D0=BE=D0=B1=D0=B0?= =?UTF-8?q?=D0=B9=D0=BB)=20+=20=D0=A4=D0=B0=D0=B7=D0=B03=20(=D1=87=D0=B0?= =?UTF-8?q?=D1=82=D1=8B:=20=D0=BF=D0=BE=D0=B8=D1=81=D0=BA/=D0=BF=D0=B5?= =?UTF-8?q?=D1=80=D0=B5=D0=B8=D0=BC=D0=B5=D0=BD=D0=BE=D0=B2=D0=B0=D0=BD?= =?UTF-8?q?=D0=B8=D0=B5/=D1=83=D0=B4=D0=B0=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Фаза2 a11y WCAG2.2: sr-status live-регион (на уровне body), role=log aria-live=off (без спама стримом), skip-link, landmark-роли, aria-label иконкам/полям, role=alert на ошибках, клавиатурная доступность списка чатов, мобайл (тач-таргет 44px, шапка не переполняется). Фаза3: таблица session_titles + эндпоинты DELETE/POST title; поиск-фильтр, инлайн-переименование, удаление с confirm. Fable-фиксы (9): единый канал озвучки ошибок; sr-status вне скрытого контейнера; озвучка логина; srAnnounce clearTimeout; удаление чистит файлы на диске; удаление прерывает стрим (чат не воскресает); перерисовка не убивает переименование; rename 400 на кривой JSON; reset/clear стирают title. --- db.py | 46 +++++++++++- main.py | 47 +++++++++++- static/chat.html | 150 ++++++++++++++++++++++++++++++++------ tests/test_session_ops.py | 61 ++++++++++++++++ tests/ui_smoke_harness.py | 27 ++++++- 5 files changed, 299 insertions(+), 32 deletions(-) create mode 100644 tests/test_session_ops.py diff --git a/db.py b/db.py index 61437b4..b10d151 100644 --- a/db.py +++ b/db.py @@ -64,6 +64,13 @@ CREATE TABLE IF NOT EXISTS feedback ( answer TEXT ); CREATE INDEX IF NOT EXISTS idx_feedback_ts ON feedback(timestamp); + +CREATE TABLE IF NOT EXISTS session_titles ( + username TEXT NOT NULL, + tab_id TEXT NOT NULL, + title TEXT NOT NULL, + PRIMARY KEY (username, tab_id) +); """ @@ -148,6 +155,11 @@ def clear_history(username: str, tab_id: str): "DELETE FROM messages WHERE username = ? AND tab_id = ?", (username, tab_id), ) + # кастомное имя не должно переживать содержимое (reset/clear-files) — Fable Ф3 + conn.execute( + "DELETE FROM session_titles WHERE username = ? AND tab_id = ?", + (username, tab_id), + ) # === Users === @@ -315,13 +327,39 @@ def get_audit_log(limit: int = 100, offset: int = 0, def list_sessions(username: str) -> list[dict]: - """List all chat sessions for a user with last message preview.""" + """List all chat sessions for a user with last message preview. + Поле `title` — кастомное имя из session_titles (или None, тогда фронт берёт last_question).""" with _conn() as conn: rows = conn.execute( - "SELECT tab_id, MAX(timestamp) as last_ts, COUNT(*) as msg_count, " + "SELECT messages.tab_id as tab_id, MAX(timestamp) as last_ts, COUNT(*) as msg_count, " "(SELECT content FROM messages m2 WHERE m2.username = messages.username " - " AND m2.tab_id = messages.tab_id AND m2.role = 'user' ORDER BY m2.id DESC LIMIT 1) as last_question " - "FROM messages WHERE username = ? GROUP BY tab_id ORDER BY last_ts DESC", + " AND m2.tab_id = messages.tab_id AND m2.role = 'user' ORDER BY m2.id DESC LIMIT 1) as last_question, " + "(SELECT title FROM session_titles st WHERE st.username = messages.username " + " AND st.tab_id = messages.tab_id) as title " + "FROM messages WHERE username = ? GROUP BY messages.tab_id ORDER BY last_ts DESC", (username,), ).fetchall() return [dict(r) for r in rows] + + +def set_session_title(username: str, tab_id: str, title: str): + """Задать/сменить кастомное имя диалога (переименование в панели чатов).""" + with _conn() as conn: + conn.execute( + "INSERT INTO session_titles (username, tab_id, title) VALUES (?, ?, ?) " + "ON CONFLICT(username, tab_id) DO UPDATE SET title = excluded.title", + (username, tab_id, title), + ) + + +def delete_session(username: str, tab_id: str) -> int: + """Удалить диалог целиком (сообщения + кастомное имя). Скоуп строго по владельцу. + Возвращает число удалённых сообщений.""" + with _conn() as conn: + cur = conn.execute( + "DELETE FROM messages WHERE username = ? AND tab_id = ?", (username, tab_id) + ) + conn.execute( + "DELETE FROM session_titles WHERE username = ? AND tab_id = ?", (username, tab_id) + ) + return cur.rowcount diff --git a/main.py b/main.py index cc398a8..79b6a2b 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_feedback, get_history, get_history_any_user, init_db, list_sessions, log_action, ping as db_ping, save_feedback, save_message +from db import clear_history, delete_session, get_audit_log, get_feedback, get_history, get_history_any_user, init_db, list_sessions, log_action, ping as db_ping, save_feedback, save_message, set_session_title from tus_upload import register_tus from error_mask import looks_like_provider_error, PROVIDER_ERROR_MESSAGE from archive_host import extract_archive_async @@ -138,7 +138,7 @@ MAX_MESSAGE_LEN = 10_000 # ⚠️ Версия UI — единый источник. БАМПАТЬ ПРИ КАЖДОМ ДЕПЛОЕ (формат: YYYY-MM-DD + буква). # Фронт берёт её через GET /api/version (chat.html + admin.html, элемент .app-version). -APP_VERSION = "2026-07-17i" +APP_VERSION = "2026-07-17j" # Audit: path → action name mapping _AUDIT_MAP = [ @@ -572,6 +572,46 @@ async def sessions(request: Request): return list_sessions(user) +@app.delete("/api/sessions/{tab_id}") +async def delete_session_ep(tab_id: str, request: Request): + """Удалить свой диалог ЦЕЛИКОМ (история в БД + загруженные файлы на диске). + Скоуп строго по владельцу из JWT — чужой не тронуть. confirm в UI обещает + «необратимо целиком» — поэтому чистим и work_dir, а не только строки (Fable Ф3).""" + user = _get_user(request) + removed = delete_session(user, tab_id) + try: + work_dir = get_work_dir(user, tab_id) + for f in work_dir.iterdir(): + if f.name.startswith("."): + continue + if f.is_file(): + f.unlink() + elif f.is_dir(): + shutil.rmtree(f) + clear_session(user, tab_id) + except Exception: # noqa: BLE001 — файлов могло не быть; строки БД уже удалены + pass + return {"ok": True, "removed": removed} + + +@app.post("/api/sessions/{tab_id}/title") +async def rename_session_ep(tab_id: str, request: Request): + """Переименовать свой диалог. Пустой/слишком длинный заголовок отклоняем.""" + user = _get_user(request) + try: + body = await request.json() + assert isinstance(body, dict) + except Exception: # noqa: BLE001 — кривой JSON → честный 400, не 500 + raise HTTPException(400, "Некорректный запрос") + title = (body.get("title") or "").strip() + if not title: + raise HTTPException(400, "Пустое название") + if len(title) > 120: + title = title[:120] + set_session_title(user, tab_id, title) + return {"ok": True, "title": title} + + @app.post("/api/upload") async def upload(request: Request, file: UploadFile): user = _get_user(request) @@ -952,8 +992,9 @@ async def admin_sessions(request: Request): rows = conn.execute( "SELECT username, tab_id, MAX(timestamp) as last_ts, COUNT(*) as msg_count, " "(SELECT content FROM messages m2 WHERE m2.tab_id = messages.tab_id " + " AND m2.username = messages.username " " AND m2.role = 'user' ORDER BY m2.id DESC LIMIT 1) as last_question " - "FROM messages GROUP BY tab_id ORDER BY last_ts DESC LIMIT 50", + "FROM messages GROUP BY username, tab_id ORDER BY last_ts DESC LIMIT 50", ).fetchall() return [dict(r) for r in rows] diff --git a/static/chat.html b/static/chat.html index a822353..4d41f8f 100644 --- a/static/chat.html +++ b/static/chat.html @@ -30,6 +30,10 @@ body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Robo /* Видимый фокус для клавиатуры — Ководство: состояния обязательны */ :focus-visible { outline: none; box-shadow: var(--focus-ring); border-radius: var(--radius-sm); } button { font-family: inherit; } +/* Только для скринридеров (срез 2.1): визуально скрыто, доступно ассистивным технологиям */ +.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0,0,0,0); white-space: nowrap; border: 0; } +.skip-link { position: absolute; left: -999px; top: 0; z-index: 200; background: var(--accent); color: #fff; padding: .5rem .9rem; border-radius: 0 0 var(--radius) 0; } +.skip-link:focus { left: 0; } ::selection { background: rgba(192,69,58,.18); } /* Тихий скроллбар */ @@ -163,6 +167,13 @@ button { font-family: inherit; } .chat-item.active { background: var(--accent-light); } .chat-item.active::before { content: ""; position: absolute; left: 0; top: 6px; bottom: 6px; width: 3px; border-radius: 3px; background: var(--accent); } .chat-item.active .ci-title { color: var(--accent); font-weight: 600; } +#chat-search { width: 100%; margin-top: .5rem; padding: .4rem .6rem; border: 1.5px solid var(--border); border-radius: var(--radius-sm); font-size: .85rem; background: var(--bg-sunken); color: var(--text); outline: none; } +#chat-search:focus { border-color: var(--accent); } +.ci-actions { position: absolute; right: .35rem; top: .35rem; display: none; gap: .1rem; } +.chat-item:hover .ci-actions, .chat-item:focus-within .ci-actions { display: flex; } +.ci-act { background: var(--bg-card); border: 1px solid var(--border); border-radius: var(--radius-sm); cursor: pointer; font-size: .8rem; line-height: 1; padding: .18rem .3rem; color: var(--text-muted); } +.ci-act:hover { color: var(--accent); border-color: var(--accent); } +.ci-rename { width: 100%; padding: .2rem .35rem; border: 1.5px solid var(--accent); border-radius: var(--radius-sm); font-size: .85rem; font-family: inherit; background: var(--bg-card); color: var(--text); outline: none; } .ci-title { font-size: .82rem; color: var(--text); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .ci-date { font-size: .66rem; color: var(--text-muted); margin-top: .12rem; } .main-col { flex: 1; display: flex; flex-direction: column; min-width: 0; } @@ -171,8 +182,15 @@ button { font-family: inherit; } @media (max-width: 720px) { .sidebar { position: fixed; left: 0; top: 0; bottom: 0; z-index: 60; transform: translateX(-100%); transition: transform .2s; box-shadow: var(--shadow-md); } .sidebar.open { transform: translateX(0); } - #sidebar-toggle { display: inline-block; } + #sidebar-toggle { display: inline-block; padding: .5rem .7rem; min-width: 44px; min-height: 44px; } /* тач-таргет ≥44px */ .sidebar-backdrop.show { display: block; position: fixed; inset: 0; background: rgba(0,0,0,.3); z-index: 55; } + /* Срез 2.2: шапка не переполняется на узком экране — заголовок компактнее, кнопки прокручиваются */ + #header h1 { font-size: 1.05rem; } + .header-actions { flex-wrap: nowrap; overflow-x: auto; -webkit-overflow-scrolling: touch; gap: .3rem; padding: 3px 2px; scroll-padding-inline: 3px; } + .header-actions button { white-space: nowrap; flex: 0 0 auto; } + #messages { padding-left: .7rem; padding-right: .7rem; } + .msg { max-width: 92%; } + .onboarding { margin: 1.2rem auto; padding: 1rem; } } /* ===== Тёмная тема (Ководство: тёплый «не-чёрный» фон, «не-белый» текст, */ @@ -225,14 +243,18 @@ html { color-scheme: light; } + +
+