feat: personalize and stream mentor chat

This commit is contained in:
leefer
2026-07-23 19:24:57 +08:00
parent 771882ebf0
commit 95789c837c
11 changed files with 876 additions and 104 deletions
+36
View File
@@ -218,6 +218,18 @@ async function mockApplication(page, authSession = session()) {
};
} else if (url.pathname === "/api/mentors/setup") {
payload = { trade_date: "20260722", mentors: mentorDirectory(authSession.user.role) };
} else if (url.pathname === "/api/mentors/chat") {
await route.fulfill({
status: 200,
contentType: "application/x-ndjson; charset=utf-8",
body: [
JSON.stringify({ type: "delta", content: "## 判断\n先看市场结构。\n\n" }),
JSON.stringify({ type: "delta", content: "- 等待确认\n- 控制仓位" }),
JSON.stringify({ type: "meta", data_trade_date: "20260722", notice: "" }),
JSON.stringify({ type: "done" }),
].join("\n"),
});
return;
}
else if (url.pathname === "/api/heaven/setup") {
await route.fulfill({ status: 503, contentType: "application/json", body: JSON.stringify({ error: "测试环境不加载问天数据" }) });
@@ -515,6 +527,30 @@ test("mentor directory exposes evidence filters and private owner metadata", asy
await expect(page.locator("#activeMentorEvidence")).toHaveText("公开访谈与多源材料");
});
test("mentor pins, custom order and streamed replies work together", async ({ page }) => {
await mockApplication(page, session("admin", true));
await page.goto("/index.html");
await page.locator('[data-view="mentorView"]').first().click();
await page.locator('[data-mentor-pin="source-c"]').click();
await expect(page.locator("#mentorList [data-mentor-card]").first()).toHaveAttribute("data-mentor-card", "source-c");
await page.locator('[data-mentor-pin="source-b"]').click();
await expect(page.locator("#mentorList [data-mentor-card]").first()).toHaveAttribute("data-mentor-card", "source-b");
await page.locator("#mentorSortToggle").click();
await page.locator('[data-mentor-target="source-b"][data-mentor-move="down"]').click();
await expect(page.locator("#mentorList [data-mentor-card]").first()).toHaveAttribute("data-mentor-card", "source-c");
await page.locator('[data-mentor-id="source-c"]').click();
await page.locator("#mentorQuestion").fill("现在怎么看?");
await page.locator("#sendMentorQuestion").click();
const answer = page.locator("#mentorMessages .mentor-message.assistant").last();
await expect(answer).toContainText("先看市场结构。");
await expect(answer.locator(".mentor-answer-list li")).toHaveCount(2);
await expect(answer.locator("br")).toHaveCount(0);
await expect(page.locator("#mentorMessages .assistant-stream-caret")).toHaveCount(0);
});
test("mobile mentor directory opens as a searchable selector and hides private mentors", async ({ page }) => {
await page.setViewportSize({ width: 375, height: 812 });
await mockApplication(page, session("user", true));
+15
View File
@@ -78,6 +78,21 @@ class AccountDataBoundaryTests(unittest.TestCase):
self.database.delete_mentor_messages(self.first["id"], "mentor-a", "20260721"), 2
)
def test_mentor_preferences_are_scoped_by_user(self):
self.database.save_mentor_preferences(
self.first["id"], ["mentor-b", "mentor-a"], {"mentor-b"}
)
self.database.save_mentor_preferences(
self.second["id"], ["mentor-a", "mentor-b"], set()
)
first = self.database.list_mentor_preferences(self.first["id"])
second = self.database.list_mentor_preferences(self.second["id"])
self.assertEqual([item["mentor_id"] for item in first], ["mentor-b", "mentor-a"])
self.assertTrue(first[0]["pinned"])
self.assertEqual([item["mentor_id"] for item in second], ["mentor-a", "mentor-b"])
self.assertFalse(any(item["pinned"] for item in second))
def test_latest_data_snapshot_skips_demo_and_future_records(self):
self.database.save_data_snapshot(
"stock_detail", "002141:20260718", "tushare", {"marker": "real"}
+1
View File
@@ -17,6 +17,7 @@ class ApiAccessPolicyTests(unittest.TestCase):
("POST", "/api/screener/run"): "member",
("POST", "/api/screener/tracking/refresh"): "member",
("POST", "/api/mentors/chat"): "member",
("POST", "/api/mentors/preferences"): "member",
("POST", "/api/heaven/interpret"): "member",
("POST", "/api/assistant/chat"): "member",
("DELETE", "/api/screener/strategies/42"): "member",
+71
View File
@@ -0,0 +1,71 @@
from __future__ import annotations
import json
import unittest
from pathlib import Path
from unittest.mock import patch
from mentor_agent import MentorSkill, chat_with_mentor, stream_with_mentor
class FakeStreamResponse:
def __init__(self, lines: list[bytes]) -> None:
self.lines = lines
def __enter__(self):
return iter(self.lines)
def __exit__(self, exc_type, exc_value, traceback):
return False
class MentorStreamTests(unittest.TestCase):
def setUp(self) -> None:
self.skill = MentorSkill(
skill_id="test-mentor",
name="测试老师",
description="测试",
tagline="先看事实",
focus=("纪律",),
content="只做条件化判断。",
path=Path("SKILL.md"),
)
self.lines = [
b'data: {"choices":[{"delta":{"content":"first"}}]}\n',
b'data: {"choices":[{"delta":{"content":" second"}}]}\n',
b"data: [DONE]\n",
]
def test_stream_requests_upstream_streaming_and_yields_deltas(self):
captured = {}
def open_request(request, timeout):
captured["payload"] = json.loads(request.data.decode("utf-8"))
captured["accept"] = request.headers.get("Accept")
return FakeStreamResponse(self.lines)
with patch("mentor_agent.urllib.request.urlopen", side_effect=open_request):
chunks = list(
stream_with_mentor(
self.skill, {"data_trade_date": "20260723"}, "怎么看?", [],
"key", "https://example.test/v1", "model",
)
)
self.assertEqual(chunks, ["first", " second"])
self.assertTrue(captured["payload"]["stream"])
self.assertEqual(captured["accept"], "text/event-stream")
def test_non_streaming_compatibility_wrapper_collects_chunks(self):
with patch(
"mentor_agent.urllib.request.urlopen",
return_value=FakeStreamResponse(self.lines),
):
result = chat_with_mentor(
self.skill, {}, "怎么看?", [], "key", "https://example.test/v1", "model"
)
self.assertEqual(result["answer"], "first second")
if __name__ == "__main__":
unittest.main()