Files
smeta-web/tests/test_chat_context.py
anorandClaude Opus 4.8 cacc2b59c7 fix: контекст диалога из БД — единый источник для обоих движков
Агент терял контекст: история жила в двух in-memory хранилищах
(Claude --resume / GLM _conversations), которые расщеплялись при
переключении движков в одной вкладке и обнулялись при рестарте/деплое.
Теперь оба движка реконструируют историю из таблицы messages, которую
сервер и так пишет для обоих путей (chat_context — единый источник истины).

- chat_context.py: history_messages (GLM messages[]) / history_recap (Claude)
- GLM-путь: prior из БД вместо in-memory _conversations
- Claude-путь: recap-префикс из БД вместо хрупкого --resume
- reset/clear-files теперь чистят историю и в БД
- tests/test_chat_context.py: cross-engine видимость + исключение текущего хода

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-10 01:20:55 +10:00

106 lines
4.0 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Unit tests for chat_context — DB-sourced conversation history for both engines.
No GLM/Docker/.env needed: only db.py + a temp SQLite file.
"""
import importlib
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 ctx(tmp_path, monkeypatch):
"""Fresh db + chat_context bound to an isolated temp DB."""
monkeypatch.setenv("DB_PATH", str(tmp_path / "t.db"))
import db
importlib.reload(db)
import chat_context
importlib.reload(chat_context)
db.init_db()
return db, chat_context
def test_history_messages_skips_system_and_drops_current(ctx):
db, cc = ctx
db.save_message("u", "tab", "user", "составь смету на туалет")
db.save_message("u", "tab", "assistant", "Готово, смета в файле.")
db.save_message("u", "tab", "system", "Загружен файл: smeta.xlsx")
# The live user message that _stream_and_save persists before streaming:
db.save_message("u", "tab", "user", "а какой там НР?")
msgs = cc.history_messages("u", "tab")
# system row skipped, current ("а какой там НР?") dropped
assert msgs == [
{"role": "user", "content": "составь смету на туалет"},
{"role": "assistant", "content": "Готово, смета в файле."},
]
def test_cross_engine_turns_all_visible(ctx):
"""The core fix: a turn produced by the Claude engine must be visible to the
GLM engine and vice versa. Persistence is engine-agnostic, so history holds
every turn regardless of which path produced it."""
db, cc = ctx
# Claude-engine turn:
db.save_message("u", "tab", "user", "составь смету")
db.save_message("u", "tab", "assistant", "[Claude] смета готова")
# GLM-engine turn:
db.save_message("u", "tab", "user", "какой НР?")
db.save_message("u", "tab", "assistant", "[GLM] НР 95%")
# current live message:
db.save_message("u", "tab", "user", "примени к смете")
msgs = cc.history_messages("u", "tab")
contents = [m["content"] for m in msgs]
assert "[Claude] смета готова" in contents
assert "[GLM] НР 95%" in contents
assert "примени к смете" not in contents # current msg excluded
def test_history_recap_format_for_claude(ctx):
db, cc = ctx
db.save_message("u", "tab", "user", "составь смету на туалет")
db.save_message("u", "tab", "assistant", "Готово.")
db.save_message("u", "tab", "user", "поменяй НР") # current
recap = cc.history_recap("u", "tab")
assert recap == "Пользователь: составь смету на туалет\n\nАссистент: Готово."
assert "поменяй НР" not in recap # current msg excluded
def test_truncation_bounds_long_messages(ctx):
db, cc = ctx
big = "x" * 10_000
db.save_message("u", "tab", "assistant", big)
db.save_message("u", "tab", "user", "next") # current
msgs = cc.history_messages("u", "tab")
assert len(msgs) == 1
assert len(msgs[0]["content"]) == cc.MAX_CHARS_PER_MSG
def test_empty_history_for_new_tab(ctx):
db, cc = ctx
db.save_message("u", "fresh", "user", "первый вопрос") # only the current msg
assert cc.history_messages("u", "fresh") == []
assert cc.history_recap("u", "fresh") == ""
def test_only_last_user_row_dropped_not_earlier_duplicates(ctx):
db, cc = ctx
db.save_message("u", "tab", "user", "дубль")
db.save_message("u", "tab", "assistant", "ответ")
db.save_message("u", "tab", "user", "дубль") # current — identical text
msgs = cc.history_messages("u", "tab")
# earlier identical "дубль" must survive; only the trailing current one drops
assert msgs == [
{"role": "user", "content": "дубль"},
{"role": "assistant", "content": "ответ"},
]