diff --git a/main.py b/main.py index d1ecd37..6bfaa53 100644 --- a/main.py +++ b/main.py @@ -136,7 +136,7 @@ MAX_MESSAGE_LEN = 10_000 # ⚠️ Версия UI — единый источник. БАМПАТЬ ПРИ КАЖДОМ ДЕПЛОЕ (формат: YYYY-MM-DD + буква). # Фронт берёт её через GET /api/version (chat.html + admin.html, элемент .app-version). -APP_VERSION = "2026-06-25" +APP_VERSION = "2026-07-03" # Audit: path → action name mapping _AUDIT_MAP = [ @@ -424,9 +424,23 @@ async def register_page(): return Path("static/register.html").read_text(encoding="utf-8") +def _work_dir_snapshot(work_dir: Path) -> dict: + """Map filename -> (mtime_ns, size) for visible files in work_dir.""" + snap = {} + for f in work_dir.iterdir(): + if f.is_file() and not f.name.startswith("."): + st = f.stat() + snap[f.name] = (st.st_mtime_ns, st.st_size) + return snap + + async def _stream_and_save(message: str, user: str, tab_id: str): """Wrap stream_claude to save messages to DB.""" save_message(user, tab_id, "user", message) + # Снимок work_dir ДО ответа: после ответа diff покажет файлы, которые + # агент создал/изменил, и пользователь получит кнопки скачивания в чате. + work_dir = get_work_dir(user, tab_id) + before = _work_dir_snapshot(work_dir) full_response = "" async for chunk in stream_claude(message, user, tab_id): yield chunk @@ -452,6 +466,20 @@ async def _stream_and_save(message: str, user: str, tab_id: str): pass if full_response: save_message(user, tab_id, "assistant", full_response) + # Новые/изменённые файлы за время ответа → кнопки скачивания в чате. + # .md включён: агент отдаёт отчёты и в markdown. Служебные *_csv/ — + # директории, отсекаются is_file(). + new_files = [] + for name, (mtime_ns, size) in sorted(_work_dir_snapshot(work_dir).items()): + if not (is_allowed_file(name) or name.lower().endswith(".md")): + continue + if before.get(name) != (mtime_ns, size): + new_files.append({"name": name, "size": size}) + if new_files: + # role='files' — не попадает в history_recap (там только user/assistant), + # но восстанавливает кнопки при перезагрузке истории. + save_message(user, tab_id, "files", json.dumps(new_files, ensure_ascii=False)) + yield f"event: files\ndata: {json.dumps({'files': new_files}, ensure_ascii=False)}\n\n" @app.post("/api/chat") diff --git a/static/chat.html b/static/chat.html index 50b77da..7abfade 100644 --- a/static/chat.html +++ b/static/chat.html @@ -76,6 +76,8 @@ button { font-family: inherit; } .msg-file { align-self: flex-start; background: var(--file-bg); border: 1px solid var(--file-border); font-size: .85rem; } .msg-file a { color: #16a34a; text-decoration: none; font-weight: 500; } .msg-file a:hover { text-decoration: underline; } +.dl-btn { display: block; width: fit-content; margin: .35rem 0 0; padding: .45rem .8rem; background: #16a34a; color: #fff !important; border-radius: var(--radius); font-weight: 600; } +.dl-btn:hover { background: #15803d; text-decoration: none !important; } .msg-error { align-self: center; background: var(--error-bg); border: 1px solid var(--error-border); color: #e03131; font-size: .85rem; box-shadow: none; } .msg-system { align-self: center; background: var(--system-bg); border: none; font-size: .8rem; color: var(--system-text); box-shadow: none; padding: .4rem .8rem; } .typing { align-self: flex-start; color: var(--text-light); font-style: italic; font-size: .85rem; padding: .4rem 0; } @@ -978,6 +980,9 @@ async function sendMessage() { if (!aiText && data.result) { aiDiv = addMsg('ai', data.result); } + } else if (eventType === 'files') { + // Агент подготовил файлы — кнопки скачивания прямо в чате + if (data.files && data.files.length) addFilesMsg(data.files); } eventType = ''; } @@ -1019,29 +1024,44 @@ function closeSidebar() { document.getElementById('sidebar-backdrop').classList.remove('show'); } +function downloadWorkFile(name) { + fetch(API + '/api/files/' + encodeURIComponent(name), {headers: authHeaders()}) + .then(r => { if (!r.ok) throw new Error(r.status); return r.blob(); }) + .then(b => { + const u = URL.createObjectURL(b); + const l = document.createElement('a'); + l.href = u; l.download = name; l.click(); + // Немедленный revoke в Firefox может оборвать ещё не начавшееся скачивание + setTimeout(() => URL.revokeObjectURL(u), 30000); + }) + .catch(() => addMsg('error', 'Не удалось скачать «' + name + '» — файл больше не существует.')); +} + +function fmtSize(size) { + return size >= 1048576 ? (size / 1048576).toFixed(1) + ' МБ' : (size / 1024).toFixed(1) + ' КБ'; +} + +// Message with download buttons for files the agent prepared. files: [{name, size}] +function addFilesMsg(files, ts, title) { + const div = addMsg('file', title || 'Готовые файлы:', ts); + const copyBtn = div.querySelector('.copy-btn'); // кнопки файлов — над «Копировать» + files.forEach(f => { + const a = document.createElement('a'); + a.className = 'dl-btn'; + a.textContent = '⬇ ' + f.name + ' (' + fmtSize(f.size) + ')'; + a.href = API + '/api/files/' + encodeURIComponent(f.name); + a.onclick = e => { e.preventDefault(); downloadWorkFile(f.name); }; + div.insertBefore(a, copyBtn); + }); + return div; +} + async function listFiles() { const r = await fetch(API + '/api/files', {headers: authHeaders()}); if (!r.ok) return; const files = await r.json(); if (files.length === 0) { addMsg('system', 'Файлов нет.'); return; } - const list = files.map(f => { - const kb = (f.size / 1024).toFixed(1); - return f.name + ' (' + kb + ' KB)'; - }).join('\n'); - const div = addMsg('file', 'Файлы в рабочей директории:\n' + list); - // Add download links - files.forEach(f => { - const a = document.createElement('a'); - a.textContent = ' [скачать ' + f.name + ']'; - a.href = API + '/api/files/' + encodeURIComponent(f.name); - a.onclick = e => { - e.preventDefault(); - fetch(a.href, {headers: authHeaders()}) - .then(r => r.blob()) - .then(b => { const u = URL.createObjectURL(b); const l = document.createElement('a'); l.href = u; l.download = f.name; l.click(); }); - }; - div.appendChild(a); - }); + addFilesMsg(files, null, 'Файлы в рабочей директории:'); } // --- History --- @@ -1056,6 +1076,9 @@ async function loadHistory() { if (m.role === 'user') addMsg('user', m.content, m.timestamp); else if (m.role === 'assistant') addMsg('ai', m.content, m.timestamp); else if (m.role === 'system') addMsg('system', m.content, m.timestamp); + else if (m.role === 'files') { + try { addFilesMsg(JSON.parse(m.content), m.timestamp); } catch {} + } } } catch {} } diff --git a/tests/test_files_event.py b/tests/test_files_event.py new file mode 100644 index 0000000..08d2d20 --- /dev/null +++ b/tests/test_files_event.py @@ -0,0 +1,129 @@ +"""Files-event tests: agent-created files must reach the user as chat download buttons. + +_stream_and_save diffs the work dir around the stream and emits `event: files` +with new/changed files + persists a role='files' row for history reload. +No GLM/Docker/.env needed: stream_claude is stubbed. +""" + +import asyncio +import importlib +import json +import os +import sys + +import pytest + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +if ROOT not in sys.path: + sys.path.insert(0, ROOT) + + +@pytest.fixture() +def env(tmp_path, monkeypatch): + """main.py bound to isolated temp DB + DATA_DIR, real bridges untouched.""" + monkeypatch.setenv("DB_PATH", str(tmp_path / "t.db")) + monkeypatch.setenv("DATA_DIR", str(tmp_path / "data")) + monkeypatch.setenv("AI_BACKEND", "claude") + monkeypatch.chdir(ROOT) # main.py mounts ./static at import + import db + importlib.reload(db) + import claude_bridge + importlib.reload(claude_bridge) + import main + importlib.reload(main) + db.init_db() + return db, main + + +def _run(main_mod, message="сделай смету", user="u", tab="tab"): + async def collect(): + return [c async for c in main_mod._stream_and_save(message, user, tab)] + return asyncio.run(collect()) + + +def _files_events(chunks): + out = [] + for c in chunks: + if c.startswith("event: files\n"): + out.append(json.loads(c.split("data: ", 1)[1].strip())) + return out + + +def test_agent_created_file_emits_files_event_and_persists(env, monkeypatch): + db, main = env + + async def fake_stream(message, user, tab_id): + wd = main.get_work_dir(user, tab_id) + (wd / "смета_готовая.xlsx").write_bytes(b"x" * 100) + yield 'event: text\ndata: {"text": "Готово"}\n\n' + yield 'event: done\ndata: {"result": "Готово"}\n\n' + + monkeypatch.setattr(main, "stream_claude", fake_stream) + chunks = _run(main) + + events = _files_events(chunks) + assert events == [{"files": [{"name": "смета_готовая.xlsx", "size": 100}]}] + + # role='files' row persisted so history reload re-renders the buttons + rows = db.get_history("u", "tab") + files_rows = [r for r in rows if r["role"] == "files"] + assert len(files_rows) == 1 + assert json.loads(files_rows[0]["content"]) == [ + {"name": "смета_готовая.xlsx", "size": 100} + ] + + +def test_preexisting_upload_not_reannounced(env, monkeypatch): + """A file uploaded before the turn (unchanged) must NOT get a button again.""" + db, main = env + wd = main.get_work_dir("u", "tab") + (wd / "загруженная.xlsm").write_bytes(b"y" * 50) + + async def fake_stream(message, user, tab_id): + yield 'event: done\ndata: {"result": "ответ без файлов"}\n\n' + + monkeypatch.setattr(main, "stream_claude", fake_stream) + chunks = _run(main) + + assert _files_events(chunks) == [] + assert all(r["role"] != "files" for r in db.get_history("u", "tab")) + + +def test_modified_upload_is_reannounced(env, monkeypatch): + """Agent editing an uploaded file in place → user gets the fresh version.""" + db, main = env + wd = main.get_work_dir("u", "tab") + (wd / "реестр.xlsm").write_bytes(b"old") + + async def fake_stream(message, user, tab_id): + f = main.get_work_dir(user, tab_id) / "реестр.xlsm" + f.write_bytes(b"new-longer-content") + yield 'event: done\ndata: {"result": "заполнил"}\n\n' + + monkeypatch.setattr(main, "stream_claude", fake_stream) + chunks = _run(main) + + events = _files_events(chunks) + assert len(events) == 1 + assert events[0]["files"][0]["name"] == "реестр.xlsm" + + +def test_service_files_excluded(env, monkeypatch): + """Scratch .py/.log and hidden files are noise — no download buttons.""" + db, main = env + + async def fake_stream(message, user, tab_id): + wd = main.get_work_dir(user, tab_id) + (wd / "script.py").write_text("print(1)") + (wd / "debug.log").write_text("...") + (wd / ".hidden").write_text("...") + (wd / "отчёт.md").write_text("# Отчёт") # .md — валидный артефакт + yield 'event: done\ndata: {"result": "ok"}\n\n' + + monkeypatch.setattr(main, "stream_claude", fake_stream) + chunks = _run(main) + + events = _files_events(chunks) + assert len(events) == 1 + names = [f["name"] for f in events[0]["files"]] + assert names == ["отчёт.md"]