feat: add summary configuration and sync controls
This commit is contained in:
@ -107,3 +107,30 @@ def test_sync_all_chats_for_day_saves_only_dated_messages_with_direction():
|
||||
assert [row.direction for row in outgoing] == ["out"]
|
||||
assert len(client.feed_calls) == 2
|
||||
assert client.history_calls[0][2]["visible_only"] is True
|
||||
|
||||
|
||||
def test_sync_all_chats_for_day_excludes_configured_chat_before_history_pull():
|
||||
from snooper_history import sync_all_chats_for_day
|
||||
|
||||
tz = ZoneInfo("Asia/Shanghai")
|
||||
start_ts = 1_792_000_000
|
||||
client = FakeClient(start_ts)
|
||||
client.auth = type("Auth", (), {"user_id": "self"})()
|
||||
storage = Storage(url="sqlite:///:memory:")
|
||||
|
||||
stats = sync_all_chats_for_day(
|
||||
client,
|
||||
storage,
|
||||
date(2026, 11, 3),
|
||||
tz,
|
||||
batch_size=2,
|
||||
start_ts=start_ts,
|
||||
end_ts=start_ts + 86_400,
|
||||
exclude_chat_ids=["private-b"],
|
||||
)
|
||||
|
||||
assert stats["chats"] == 1
|
||||
assert stats["matched"] == 1
|
||||
assert stats["saved"] == 1
|
||||
assert [call[0] for call in client.history_calls] == ["group-a"]
|
||||
assert storage.get_messages("private-b") == []
|
||||
|
||||
@ -207,6 +207,40 @@ def test_summary_is_per_conversation_before_daily_combination():
|
||||
assert "私聊原始内容" not in prompts[2]
|
||||
|
||||
|
||||
def test_summary_applies_chat_specific_prompts_to_each_relevant_stage():
|
||||
session = FakeSession(
|
||||
completions=[
|
||||
(DEFAULT_MODEL, "业务监控摘要"),
|
||||
(DEFAULT_MODEL, "普通群摘要"),
|
||||
(DEFAULT_MODEL, "最终日度总结"),
|
||||
]
|
||||
)
|
||||
client = MagpieClient(DEFAULT_MODEL, session=session)
|
||||
rows = [
|
||||
synthetic_row(chat_id="monitor", chat_name="监控群"),
|
||||
synthetic_row("m2", chat_id="regular", chat_name="普通群"),
|
||||
]
|
||||
_, _, _, tz = resolve_day("2026-11-03", "Asia/Shanghai")
|
||||
custom_prompt = "放量提醒是业务监控重点,不得省略。"
|
||||
|
||||
result = summarize_messages(
|
||||
client,
|
||||
rows,
|
||||
date(2026, 11, 3),
|
||||
tz,
|
||||
chat_prompts={"monitor": custom_prompt},
|
||||
)
|
||||
|
||||
assert result == "最终日度总结"
|
||||
prompts = [
|
||||
kwargs["json"]["messages"][1]["content"]
|
||||
for _, kwargs in session.post_calls
|
||||
]
|
||||
assert custom_prompt in prompts[0]
|
||||
assert custom_prompt not in prompts[1]
|
||||
assert custom_prompt in prompts[2]
|
||||
|
||||
|
||||
def test_summary_enriches_names_and_requests_obsidian_wikilinks():
|
||||
session = FakeSession(
|
||||
completions=[
|
||||
@ -247,6 +281,32 @@ def test_summary_enriches_names_and_requests_obsidian_wikilinks():
|
||||
assert "Wikilink" in final_prompt
|
||||
|
||||
|
||||
def test_summary_normalizes_people_aliases_after_both_model_stages():
|
||||
session = FakeSession(
|
||||
completions=[
|
||||
(DEFAULT_MODEL, "伦总发送了文件"),
|
||||
(DEFAULT_MODEL, "[[伦总]] 最终确认"),
|
||||
]
|
||||
)
|
||||
client = MagpieClient(DEFAULT_MODEL, session=session)
|
||||
rows = [synthetic_row(chat_id="group-a", chat_name="项目群")]
|
||||
_, _, _, tz = resolve_day("2026-11-03", "Asia/Shanghai")
|
||||
|
||||
result = summarize_messages(
|
||||
client,
|
||||
rows,
|
||||
date(2026, 11, 3),
|
||||
tz,
|
||||
contacts={"group-a": {"sender-test": "万轶伦"}},
|
||||
people_aliases={"伦总": "万轶伦"},
|
||||
)
|
||||
|
||||
final_prompt = session.post_calls[1][1]["json"]["messages"][1]["content"]
|
||||
assert "[[万轶伦]]发送了文件" in final_prompt
|
||||
assert "伦总" not in final_prompt
|
||||
assert result == "[[万轶伦]] 最终确认"
|
||||
|
||||
|
||||
def test_storage_selects_only_received_messages_inside_day_and_chat():
|
||||
storage = Storage(url="sqlite:///:memory:")
|
||||
tz = ZoneInfo("Asia/Shanghai")
|
||||
@ -324,27 +384,41 @@ def test_cli_end_to_end_with_synthetic_db_and_fake_magpie(
|
||||
{**base, "msg_id": "outgoing", "content": "合成发出内容"}, direction="out"
|
||||
)
|
||||
monkeypatch.setenv("LARKX_STORAGE_URL", database_url)
|
||||
routed_model = "maqqie/gg-chat-efund/EFundGPT-dsv4pro"
|
||||
session = FakeSession(
|
||||
completions=[(DEFAULT_MODEL, "单对话摘要"), (DEFAULT_MODEL, "# 合成总结")]
|
||||
models=[routed_model],
|
||||
completions=[(routed_model, "单对话摘要"), (routed_model, "# 合成总结")],
|
||||
)
|
||||
monkeypatch.setattr("snooper_summary.requests.Session", lambda: session)
|
||||
output = tmp_path / "summary.md"
|
||||
dry_run = tmp_path / "dry-runs" / "2026-11-03.json"
|
||||
dry_run.parent.mkdir()
|
||||
dry_run.write_text("合成 dry-run", encoding="utf-8")
|
||||
config_file = tmp_path / "config.yaml"
|
||||
config_file.write_text(
|
||||
f"output:\n dry_run: '{tmp_path}/dry-runs/{{date}}.json'\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
args = argparse.Namespace(
|
||||
date="2026-11-03",
|
||||
timezone="Asia/Shanghai",
|
||||
model=DEFAULT_MODEL,
|
||||
model=routed_model,
|
||||
base_url="http://127.0.0.1:3425/v1",
|
||||
timeout=1,
|
||||
chat=None,
|
||||
max_chars=80000,
|
||||
output=output,
|
||||
config=config_file,
|
||||
check=False,
|
||||
dry_run=False,
|
||||
no_contacts=True,
|
||||
no_fetch=True,
|
||||
)
|
||||
assert cmd_summarize(args) == 0
|
||||
assert output.read_text(encoding="utf-8") == "# 合成总结\n"
|
||||
assert output.read_text(encoding="utf-8") == (
|
||||
"---\nmodel: EFundGPT-dsv4pro\n---\n\n# 合成总结\n"
|
||||
)
|
||||
assert not dry_run.exists()
|
||||
request_text = session.post_calls[0][1]["json"]["messages"][1]["content"]
|
||||
assert "合成收到内容" in request_text
|
||||
assert "合成发出内容" not in request_text
|
||||
@ -419,7 +493,16 @@ def test_cli_summarize_prefetches_before_reading(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr("lark_snooper.LarkAuth", lambda: object())
|
||||
sync_calls = []
|
||||
|
||||
def fake_sync(client, storage, target_day, tz, batch_size=50, chat_ids=None):
|
||||
def fake_sync(
|
||||
client,
|
||||
storage,
|
||||
target_day,
|
||||
tz,
|
||||
batch_size=50,
|
||||
chat_ids=None,
|
||||
exclude_chat_ids=None,
|
||||
force=False,
|
||||
):
|
||||
assert len(session.get_calls) == 1 # EFundGPT preflight still comes first.
|
||||
_, start, _, _ = resolve_summary_day("2026-11-03", "Asia/Shanghai")
|
||||
storage.save_message(
|
||||
@ -435,11 +518,43 @@ def test_cli_summarize_prefetches_before_reading(tmp_path, monkeypatch):
|
||||
},
|
||||
direction="in",
|
||||
)
|
||||
sync_calls.append({"batch_size": batch_size, "chat_ids": chat_ids})
|
||||
return {"failed": 0, "matched": 1, "saved": 1, "chats": 1, "requests": 1}
|
||||
storage.save_message(
|
||||
{
|
||||
"msg_id": "excluded",
|
||||
"chat_id": "chat-excluded",
|
||||
"chat_type": 2,
|
||||
"from_id": "sender-synthetic",
|
||||
"msg_type": 4,
|
||||
"msg_type_name": "TEXT",
|
||||
"create_time": int(start.timestamp()) + 120,
|
||||
"content": "不应读取的排除群消息",
|
||||
},
|
||||
direction="in",
|
||||
)
|
||||
sync_calls.append(
|
||||
{
|
||||
"batch_size": batch_size,
|
||||
"chat_ids": chat_ids,
|
||||
"exclude_chat_ids": exclude_chat_ids,
|
||||
}
|
||||
)
|
||||
return {
|
||||
"failed": 0,
|
||||
"matched": 1,
|
||||
"saved": 1,
|
||||
"chats": 1,
|
||||
"requests": 1,
|
||||
"skipped": 0,
|
||||
}
|
||||
|
||||
monkeypatch.setattr("snooper_history.sync_all_chats_for_day", fake_sync)
|
||||
output = tmp_path / "summary.md"
|
||||
config_file = tmp_path / "config.yaml"
|
||||
config_file.write_text(
|
||||
f"output:\n dry_run: '{tmp_path}/dry-runs/{{date}}.json'\n"
|
||||
"chats:\n exclude:\n - 'chat-excluded'\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
args = argparse.Namespace(
|
||||
date="2026-11-03",
|
||||
timezone="Asia/Shanghai",
|
||||
@ -447,18 +562,31 @@ def test_cli_summarize_prefetches_before_reading(tmp_path, monkeypatch):
|
||||
base_url="http://127.0.0.1:3425/v1",
|
||||
timeout=1,
|
||||
chat=["chat-synthetic"],
|
||||
config=config_file,
|
||||
max_chars=80000,
|
||||
output=output,
|
||||
check=False,
|
||||
dry_run=False,
|
||||
no_contacts=True,
|
||||
no_fetch=False,
|
||||
force_fetch=False,
|
||||
)
|
||||
|
||||
assert cmd_summarize(args) == 0
|
||||
assert sync_calls == [{"batch_size": 50, "chat_ids": ["chat-synthetic"]}]
|
||||
assert sync_calls == [
|
||||
{
|
||||
"batch_size": 50,
|
||||
"chat_ids": ["chat-synthetic"],
|
||||
"exclude_chat_ids": ["chat-excluded"],
|
||||
}
|
||||
]
|
||||
assert len(session.post_calls) == 2
|
||||
assert output.read_text(encoding="utf-8") == "# 合成总结\n"
|
||||
request_text = session.post_calls[0][1]["json"]["messages"][1]["content"]
|
||||
assert "合成预取消息" in request_text
|
||||
assert "不应读取的排除群消息" not in request_text
|
||||
assert output.read_text(encoding="utf-8") == (
|
||||
f"---\nmodel: {DEFAULT_MODEL}\n---\n\n# 合成总结\n"
|
||||
)
|
||||
|
||||
|
||||
def test_cli_model_failure_happens_before_storage_is_opened(monkeypatch):
|
||||
|
||||
223
tests/test_web.py
Normal file
223
tests/test_web.py
Normal file
@ -0,0 +1,223 @@
|
||||
import http.client
|
||||
import json
|
||||
import stat
|
||||
import threading
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import yaml
|
||||
|
||||
from snooper_web import (
|
||||
ChatConfig,
|
||||
SnooperWebServer,
|
||||
WebError,
|
||||
chat_snapshot,
|
||||
fill_member_names,
|
||||
update_yaml_excludes,
|
||||
)
|
||||
|
||||
|
||||
def test_update_yaml_excludes_preserves_other_settings_and_comments():
|
||||
original = """# local settings
|
||||
output:
|
||||
summary: \"~/summaries/{date}.md\"
|
||||
chats:
|
||||
exclude:
|
||||
- \"old-chat\" # keep this note
|
||||
# prompt rules
|
||||
prompts:
|
||||
\"prompt-chat\": | # business
|
||||
保留这条总结要求。
|
||||
"""
|
||||
rendered = update_yaml_excludes(original, ["old-chat", "new-chat"])
|
||||
|
||||
assert '# \"old-chat\"' not in rendered
|
||||
assert '- \"old-chat\" # keep this note' in rendered
|
||||
assert '- \"new-chat\"' in rendered
|
||||
assert "# prompt rules\n prompts:" in rendered
|
||||
assert "保留这条总结要求。" in rendered
|
||||
assert yaml.safe_load(rendered)["output"]["summary"] == "~/summaries/{date}.md"
|
||||
assert yaml.safe_load(rendered)["chats"]["exclude"] == ["old-chat", "new-chat"]
|
||||
|
||||
restored = update_yaml_excludes(rendered, ["new-chat"])
|
||||
assert "keep this note" not in restored
|
||||
assert yaml.safe_load(restored)["chats"]["exclude"] == ["new-chat"]
|
||||
assert yaml.safe_load(restored)["chats"]["prompts"]["prompt-chat"].strip() == "保留这条总结要求。"
|
||||
|
||||
|
||||
def test_update_yaml_excludes_supports_empty_and_inline_config():
|
||||
assert yaml.safe_load(update_yaml_excludes("", []))["chats"]["exclude"] == []
|
||||
created = update_yaml_excludes("output: {}\n", ["group-a"])
|
||||
assert yaml.safe_load(created)["chats"]["exclude"] == ["group-a"]
|
||||
assert yaml.safe_load(created)["output"] == {}
|
||||
|
||||
inline = update_yaml_excludes("chats: {} # local\n", ["group-a"])
|
||||
assert "# local" in inline
|
||||
assert yaml.safe_load(inline)["chats"]["exclude"] == ["group-a"]
|
||||
|
||||
emptied = update_yaml_excludes("chats:\n exclude: [group-a]\n", [])
|
||||
assert yaml.safe_load(emptied)["chats"]["exclude"] == []
|
||||
|
||||
unsupported = "chats: {exclude: [old], prompts: {old: keep}}\n"
|
||||
with pytest.raises(WebError, match="原配置未修改"):
|
||||
update_yaml_excludes(unsupported, ["new"])
|
||||
|
||||
|
||||
def test_chat_config_set_ignored_is_persistent_and_keeps_mode(tmp_path):
|
||||
path = tmp_path / "config.yaml"
|
||||
path.write_text("output: {}\nchats:\n exclude: []\n", encoding="utf-8")
|
||||
path.chmod(0o640)
|
||||
config = ChatConfig(path)
|
||||
|
||||
assert config.set_ignored("group-a", True) == ["group-a"]
|
||||
assert config.set_ignored("group-a", True) == ["group-a"]
|
||||
assert config.excluded() == ["group-a"]
|
||||
assert stat.S_IMODE(path.stat().st_mode) == 0o640
|
||||
|
||||
assert config.set_ignored("group-a", False) == []
|
||||
assert config.excluded() == []
|
||||
with pytest.raises(WebError, match="布尔值"):
|
||||
config.set_ignored("group-a", "yes")
|
||||
|
||||
|
||||
def test_chat_snapshot_merges_local_and_stale_excluded_chats(tmp_path, monkeypatch):
|
||||
path = tmp_path / "config.yaml"
|
||||
path.write_text(
|
||||
"chats:\n exclude:\n - local-chat\n - stale-chat\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
class FakeStorage:
|
||||
def list_chats(self, limit):
|
||||
assert limit == 100000
|
||||
return [
|
||||
SimpleNamespace(chat_id="local-chat", name="本地群", chat_type=2),
|
||||
SimpleNamespace(chat_id="other-chat", name="另一个群", chat_type=3),
|
||||
]
|
||||
|
||||
monkeypatch.setattr("snooper_storage.SnifferStorage", FakeStorage)
|
||||
snapshot = chat_snapshot(ChatConfig(path), refresh=False)
|
||||
|
||||
assert snapshot["refreshed"] is False
|
||||
assert [chat["chat_id"] for chat in snapshot["chats"]] == [
|
||||
"local-chat",
|
||||
"other-chat",
|
||||
"stale-chat",
|
||||
]
|
||||
assert snapshot["chats"][0]["ignored"] is True
|
||||
assert snapshot["chats"][0]["sources"] == ["local"]
|
||||
assert snapshot["chats"][2]["sources"] == ["config"]
|
||||
assert snapshot["excluded"] == ["local-chat", "stale-chat"]
|
||||
|
||||
|
||||
def test_fill_member_names_batches_private_peers_and_names_groups():
|
||||
class FakeClient:
|
||||
auth = SimpleNamespace(user_id="self")
|
||||
|
||||
def __init__(self):
|
||||
self.chatter_requests = []
|
||||
|
||||
def api(self, name, data):
|
||||
if name == "chatters.PullChattersByIdsRequest":
|
||||
self.chatter_requests.append(data["chatterIds"])
|
||||
return {
|
||||
"chatters": {
|
||||
user_id: {"id": user_id, "name": f"同事-{user_id}"}
|
||||
for user_id in data["chatterIds"]
|
||||
}
|
||||
}
|
||||
assert name == "chats.PullChatChattersRequest"
|
||||
assert data["chatId"] == "unnamed-group"
|
||||
return {
|
||||
"chatters": {
|
||||
"self": {"id": "self", "name": "自己"},
|
||||
"member-a": {"id": "member-a", "name": "成员甲"},
|
||||
"member-b": {"id": "member-b", "name": "成员乙"},
|
||||
}
|
||||
}
|
||||
|
||||
client = FakeClient()
|
||||
chats = [
|
||||
{"id": "private-a", "type": 1, "key": "self:peer-a"},
|
||||
{"id": "private-b", "type": 1, "key": "peer-b:self"},
|
||||
{"id": "named-private", "type": 1, "name": "已有名字", "ownerId": "peer-c"},
|
||||
{"id": "unnamed-group", "type": 2},
|
||||
{"id": "named-group", "type": 2, "name": "已有群名"},
|
||||
]
|
||||
|
||||
resolved, warnings = fill_member_names(client, chats)
|
||||
|
||||
assert warnings == []
|
||||
assert client.chatter_requests == [["peer-a", "peer-b"]]
|
||||
assert [chat["name"] for chat in resolved] == [
|
||||
"同事-peer-a",
|
||||
"同事-peer-b",
|
||||
"已有名字",
|
||||
"成员甲、成员乙",
|
||||
"已有群名",
|
||||
]
|
||||
assert all("name" not in chat for chat in chats[:2])
|
||||
|
||||
|
||||
def test_fill_member_names_falls_back_to_private_chat_members():
|
||||
class FakeClient:
|
||||
auth = SimpleNamespace(user_id="self")
|
||||
|
||||
def api(self, name, data):
|
||||
if name == "chatters.PullChattersByIdsRequest":
|
||||
return {"chatters": {}}
|
||||
assert name == "chats.PullChatChattersRequest"
|
||||
return {
|
||||
"chatters": {
|
||||
"self": {"id": "self", "name": "自己"},
|
||||
"peer": {"id": "peer", "name": "私聊对方"},
|
||||
}
|
||||
}
|
||||
|
||||
resolved, warnings = fill_member_names(
|
||||
FakeClient(), [{"id": "private", "type": 1, "key": "self:peer"}]
|
||||
)
|
||||
|
||||
assert warnings == []
|
||||
assert resolved[0]["name"] == "私聊对方"
|
||||
|
||||
|
||||
def test_http_write_requires_csrf_token_and_updates_real_config(tmp_path):
|
||||
path = tmp_path / "config.yaml"
|
||||
path.write_text("chats:\n exclude: []\n", encoding="utf-8")
|
||||
server = SnooperWebServer(("127.0.0.1", 0), ChatConfig(path))
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
connection = http.client.HTTPConnection("127.0.0.1", server.server_port, timeout=5)
|
||||
payload = json.dumps({"chat_id": "group-a", "ignored": True})
|
||||
try:
|
||||
connection.request(
|
||||
"POST",
|
||||
"/api/ignore",
|
||||
body=payload,
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
response = connection.getresponse()
|
||||
response.read()
|
||||
assert response.status == 403
|
||||
assert ChatConfig(path).excluded() == []
|
||||
|
||||
connection.request(
|
||||
"POST",
|
||||
"/api/ignore",
|
||||
body=payload,
|
||||
headers={
|
||||
"Content-Type": "application/json",
|
||||
"X-CSRF-Token": server.csrf_token,
|
||||
},
|
||||
)
|
||||
response = connection.getresponse()
|
||||
result = json.loads(response.read())
|
||||
assert response.status == 200
|
||||
assert result["ignored"] is True
|
||||
assert ChatConfig(path).excluded() == ["group-a"]
|
||||
finally:
|
||||
connection.close()
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
thread.join(timeout=5)
|
||||
Reference in New Issue
Block a user