Агент создавал файлы в work_dir, но UI о них не узнавал — скачать было нечем (только скрытая кнопка «Файлы»). Теперь _stream_and_save диффит work_dir до/после ответа, шлёт event: files и пишет role='files' в историю — кнопки переживают перезагрузку. Служебные файлы (.py/.log/ скрытые) отфильтрованы, .md разрешён. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
130 lines
4.4 KiB
Python
130 lines
4.4 KiB
Python
"""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"]
|