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>
This commit is contained in:
@@ -0,0 +1,60 @@
|
||||
"""Conversation context from persisted history — single source of truth.
|
||||
|
||||
Both engines (Claude CLI agent + GLM Q&A) reconstruct prior-turn context from
|
||||
the DB `messages` table on every request, instead of per-process in-memory
|
||||
stores that fragment when the router switches engines mid-dialog and vanish on
|
||||
every server restart/deploy. The DB already persists every turn of both engines
|
||||
(via main._stream_and_save), so reading it back unifies the two paths and
|
||||
survives restarts.
|
||||
"""
|
||||
|
||||
from db import get_history
|
||||
|
||||
MAX_TURNS = 16 # recent messages fed back as context
|
||||
MAX_CHARS_PER_MSG = 4000 # cap long estimate tables so the prompt stays bounded
|
||||
|
||||
|
||||
def _recent(username: str, tab_id: str) -> list[dict]:
|
||||
"""Prior turns, oldest→newest, WITHOUT the just-saved current user message.
|
||||
|
||||
main._stream_and_save() persists the live user message before streaming, so
|
||||
it is the last row — drop it to avoid feeding the question back as history.
|
||||
"""
|
||||
rows = get_history(username, tab_id, limit=MAX_TURNS + 1)
|
||||
if rows and rows[-1].get("role") == "user":
|
||||
rows = rows[:-1]
|
||||
return rows[-MAX_TURNS:]
|
||||
|
||||
|
||||
def history_messages(username: str, tab_id: str) -> list[dict]:
|
||||
"""Prior turns as OpenAI-style messages[] for the GLM API.
|
||||
|
||||
System rows (file-upload notices) are skipped — the GLM API takes one
|
||||
leading system prompt, and current file content is injected fresh per turn.
|
||||
"""
|
||||
out = []
|
||||
for r in _recent(username, tab_id):
|
||||
role = r.get("role")
|
||||
if role not in ("user", "assistant"):
|
||||
continue
|
||||
content = (r.get("content") or "")[:MAX_CHARS_PER_MSG]
|
||||
if content:
|
||||
out.append({"role": role, "content": content})
|
||||
return out
|
||||
|
||||
|
||||
def history_recap(username: str, tab_id: str) -> str:
|
||||
"""Prior turns as a readable block prepended to the Claude agent prompt."""
|
||||
lines = []
|
||||
for r in _recent(username, tab_id):
|
||||
role = r.get("role")
|
||||
if role == "user":
|
||||
who = "Пользователь"
|
||||
elif role == "assistant":
|
||||
who = "Ассистент"
|
||||
else:
|
||||
continue
|
||||
content = (r.get("content") or "")[:MAX_CHARS_PER_MSG]
|
||||
if content:
|
||||
lines.append(f"{who}: {content}")
|
||||
return "\n\n".join(lines)
|
||||
+17
-6
@@ -6,6 +6,8 @@ import os
|
||||
from pathlib import Path
|
||||
from typing import AsyncGenerator
|
||||
|
||||
from chat_context import history_recap
|
||||
|
||||
DOCKER_IMAGE = os.environ.get("CLAUDE_DOCKER_IMAGE", "smeta-claude-sandbox")
|
||||
CLAUDE_MODEL = os.environ.get("CLAUDE_MODEL", "sonnet") # агентный расчёт смет
|
||||
DATA_DIR = Path(os.environ.get("DATA_DIR", "./smeta-web-data"))
|
||||
@@ -132,7 +134,6 @@ async def stream_claude(
|
||||
"""Run claude in Docker container, yield SSE-formatted events."""
|
||||
async with _semaphore:
|
||||
work_dir = get_work_dir(username, tab_id)
|
||||
session_id = get_session_id(username, tab_id)
|
||||
|
||||
# Страховочный слой расчёта: для смета-calc запросов пред-инжектим
|
||||
# реальные цены корпуса в промпт — грунтинг гарантирован даже если
|
||||
@@ -149,6 +150,21 @@ async def stream_claude(
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Контекст диалога из БД — единый источник истины для обоих движков.
|
||||
# Заменяет хрупкий --resume: переживает рестарт сервера и видит ходы,
|
||||
# сделанные GLM-путём, поэтому агент понимает ссылки «эта смета»,
|
||||
# «тот файл», «как выше». Файлы-артефакты диалога лежат в /data.
|
||||
recap = history_recap(username, tab_id)
|
||||
if recap:
|
||||
message = (
|
||||
"[Контекст диалога в этой вкладке — предыдущие сообщения. "
|
||||
"Используй их, чтобы понять, на что ссылается пользователь "
|
||||
"(«эта смета», «тот файл», «как выше»). Файлы из диалога — в /data.]\n\n"
|
||||
f"{recap}\n\n"
|
||||
"[Текущий запрос пользователя:]\n"
|
||||
f"{message}"
|
||||
)
|
||||
|
||||
# Pre-process xlsx files that openpyxl can't read → CSV
|
||||
_preprocess_xlsx(work_dir)
|
||||
|
||||
@@ -191,8 +207,6 @@ async def stream_claude(
|
||||
claude_args.extend([
|
||||
"--append-system-prompt-file", "/instructions.md"
|
||||
])
|
||||
if session_id:
|
||||
claude_args.extend(["--resume", session_id])
|
||||
|
||||
# Docker command
|
||||
cmd = [
|
||||
@@ -284,9 +298,6 @@ async def stream_claude(
|
||||
yield f"event: tool\ndata: {json.dumps({'tool': name}, ensure_ascii=False)}\n\n"
|
||||
|
||||
elif etype == "result":
|
||||
sid = event.get("session_id", "")
|
||||
if sid:
|
||||
set_session_id(username, tab_id, sid)
|
||||
result_text = event.get("result", "")
|
||||
yield f"event: done\ndata: {json.dumps({'result': result_text}, ensure_ascii=False)}\n\n"
|
||||
|
||||
|
||||
+17
-19
@@ -19,9 +19,12 @@ ZAI_BASE_URL = os.environ.get("ZAI_BASE_URL", "https://open.bigmodel.cn/api/codi
|
||||
ZAI_MODEL = os.environ.get("ZAI_MODEL", "glm-5.1")
|
||||
DATA_DIR = Path(os.environ.get("DATA_DIR", "./smeta-web-data"))
|
||||
|
||||
# Session tracking: (username, tab_id) -> conversation history
|
||||
from chat_context import history_messages
|
||||
|
||||
# Legacy in-memory map — kept only so clear_session() stays a no-op safe call.
|
||||
# Conversation context now comes from the DB (see chat_context), which both
|
||||
# engines share and which survives server restarts.
|
||||
_conversations: dict[tuple[str, str], list[dict]] = {}
|
||||
MAX_HISTORY = 20 # keep last N messages
|
||||
|
||||
# Preload CAG context and resources
|
||||
_cag_context = ""
|
||||
@@ -373,12 +376,11 @@ async def stream_claude(
|
||||
) -> AsyncGenerator[str, None]:
|
||||
"""Stream GLM-5 response with CAG context."""
|
||||
_load_smeta_data()
|
||||
key = (username, tab_id)
|
||||
|
||||
# Build conversation history
|
||||
if key not in _conversations:
|
||||
_conversations[key] = []
|
||||
history = _conversations[key]
|
||||
# Prior turns from the DB — shared source of truth across both engines,
|
||||
# so a question like "а какой там НР?" still resolves even when the
|
||||
# previous turn was handled by the Claude agent path.
|
||||
prior = history_messages(username, tab_id)
|
||||
|
||||
work_dir = get_work_dir(username, tab_id)
|
||||
|
||||
@@ -468,14 +470,12 @@ async def stream_claude(
|
||||
if normative_context:
|
||||
user_content += f"\n\n[{normative_context}]"
|
||||
|
||||
history.append({"role": "user", "content": user_content})
|
||||
|
||||
# Trim history
|
||||
if len(history) > MAX_HISTORY:
|
||||
history[:] = history[-MAX_HISTORY:]
|
||||
|
||||
# Prepare messages
|
||||
messages = [{"role": "system", "content": _build_system_prompt()}] + history
|
||||
# Prepare messages: system prompt + prior turns (DB) + current question
|
||||
messages = (
|
||||
[{"role": "system", "content": _build_system_prompt()}]
|
||||
+ prior
|
||||
+ [{"role": "user", "content": user_content}]
|
||||
)
|
||||
|
||||
# Stream from GLM API
|
||||
full_response = ""
|
||||
@@ -531,10 +531,8 @@ async def stream_claude(
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Save assistant response to history
|
||||
if full_response:
|
||||
history.append({"role": "assistant", "content": full_response})
|
||||
|
||||
# Assistant response is persisted to the DB by main._stream_and_save —
|
||||
# no separate in-memory history to maintain here.
|
||||
yield f"event: done\ndata: {json.dumps({'result': full_response}, ensure_ascii=False)}\n\n"
|
||||
|
||||
|
||||
|
||||
@@ -94,6 +94,18 @@ def get_history(username: str, tab_id: str, limit: int = 100) -> list[dict]:
|
||||
return [dict(r) for r in reversed(rows)]
|
||||
|
||||
|
||||
def clear_history(username: str, tab_id: str):
|
||||
"""Delete chat messages for one tab — backs the explicit reset action.
|
||||
|
||||
Scoped to a single (username, tab_id); since conversation context now comes
|
||||
from the DB, reset must clear it here or it would have no effect."""
|
||||
with _conn() as conn:
|
||||
conn.execute(
|
||||
"DELETE FROM messages WHERE username = ? AND tab_id = ?",
|
||||
(username, tab_id),
|
||||
)
|
||||
|
||||
|
||||
# === Users ===
|
||||
|
||||
def create_user(email: str, password_hash: str, role: str = "user") -> int:
|
||||
|
||||
@@ -11,7 +11,7 @@ from fastapi.responses import FileResponse, HTMLResponse, StreamingResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
from auth import authenticate, verify_token, make_download_ticket, verify_download_ticket
|
||||
from db import get_audit_log, get_history, get_history_any_user, init_db, list_sessions, log_action, save_message
|
||||
from db import clear_history, get_audit_log, get_history, get_history_any_user, init_db, list_sessions, log_action, save_message
|
||||
from tus_upload import register_tus
|
||||
|
||||
# Backend: "claude" (Docker sandbox), "glm" (GLM-5 + CAG), "auto" (route by task)
|
||||
@@ -592,6 +592,7 @@ async def reset_session(request: Request):
|
||||
user = _get_user(request)
|
||||
tab_id = request.headers.get("x-tab-id", "default")
|
||||
clear_session(user, tab_id)
|
||||
clear_history(user, tab_id)
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@@ -608,6 +609,7 @@ async def clear_files(request: Request):
|
||||
elif f.is_dir():
|
||||
shutil.rmtree(f)
|
||||
clear_session(user, tab_id)
|
||||
clear_history(user, tab_id)
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
"""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": "ответ"},
|
||||
]
|
||||
Reference in New Issue
Block a user