oclaw/tests/test_get_messages_preserve_tool_pairing.py
oliver 4a23b715a2 重构仓库目录为统一的 runtime 分层并清理历史 openclaw 残留。
本次迁移将网关/通道/工具/技能/脚本与协议资源集中到新结构,统一路径常量与脚本转发机制,减少顶层噪音并保证运行与测试行为一致。

Made-with: Cursor
2026-04-25 01:24:23 +08:00

52 lines
2 KiB
Python

from __future__ import annotations
import json
from pathlib import Path
from oclaw.runtime.chat.agent_messages import build_llm_messages
from oclaw.platform.llm.chat_models import RuleBasedChatModel
from oclaw.platform.persistence.sqlite_store import SqliteStore
def test_get_messages_limit_preserves_tool_pairing(tmp_path: Path) -> None:
db = tmp_path / "t.sqlite"
store = SqliteStore(str(db))
sess = store.create_session("t")
store.add_message(session_id=sess.id, role="user", content="hi", turn_uuid="turn-1", event_type="user_text")
assistant = store.add_message(
session_id=sess.id,
role="assistant",
content="",
turn_uuid="turn-1",
event_type="tool_call",
tool_calls=[
{
"id": "call_abc",
"name": "mcp__x__list_directory",
"arguments": {"path": "C:\\dummy"},
}
],
)
# Tool result must keep tool_call_id + assistant_message_id for pairing.
store.add_message(
session_id=sess.id,
role="tool",
content=json.dumps({"ok": False, "error": "Access denied", "result": {"isError": True}}, ensure_ascii=False),
turn_uuid="turn-1",
event_type="tool_result",
tool_calls={"tool_call_id": "call_abc", "name": "mcp__x__list_directory", "assistant_message_id": int(assistant.id)},
)
# Boundary case: only ask for the last 1 message. Store must prepend the assistant row to keep pairing.
rows = store.get_messages(session_id=sess.id, limit=1)
assert len(rows) >= 2
assert rows[-1].role == "tool"
assert any(r.role == "assistant" and r.tool_calls for r in rows)
assert all(str(getattr(r, "turn_uuid", "") or "") == "turn-1" for r in rows)
msgs = build_llm_messages(store_messages=rows, system_prompt="s", model=RuleBasedChatModel(), lang="zh")
tool_msgs = [m for m in msgs if m.get("role") == "tool"]
assert tool_msgs, msgs
assert tool_msgs[-1].get("tool_call_id") == "call_abc"