From 5ecc03c13ec34633c444372951afbaec85c1895e Mon Sep 17 00:00:00 2001 From: Zhenxian Liang Date: Mon, 16 Nov 2026 11:55:26 +0800 Subject: [PATCH 1/2] Fix #7: answer drug questions and extract known names in structured queries MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Drug intent: add usage phrasing (怎么吃/如何服用/用量/能吃吗...) to drug keywords and score drug intent on known drug names derived from knowledge-base drug documents, so '布洛芬怎么吃?有什么注意 事项?' is no longer misrouted to faq with zero citations. Also allow bare negated safety phrasing ('不自行停药') in the safe output whitelist to stop false-positive safety blocks. - Structured queries: _extract_term now longest-matches against registered entity names from the whitelisted tables; unknown entities return blocked with a clarification instead of an empty result that reads as 'out of stock'. Injection guards unchanged. - Add backend/tests/test_drug_query.py (18 tests). Closes zhengdaodeguL/MedGuide#7. --- backend/app/retrieval.py | 57 ++++++++++++- backend/app/sql_guard.py | 91 +++++++++++++++++++- backend/app/workflow.py | 10 ++- backend/tests/test_drug_query.py | 142 +++++++++++++++++++++++++++++++ 4 files changed, 292 insertions(+), 8 deletions(-) create mode 100644 backend/tests/test_drug_query.py diff --git a/backend/app/retrieval.py b/backend/app/retrieval.py index a33dc38..0471b1c 100644 --- a/backend/app/retrieval.py +++ b/backend/app/retrieval.py @@ -5,7 +5,7 @@ import os import re from pathlib import Path -from collections.abc import Mapping +from collections.abc import Iterable, Mapping from time import monotonic from typing import Any @@ -18,7 +18,15 @@ class IntentRouter: KEYWORDS: dict[Intent, tuple[str, ...]] = { - "drug": ("药", "用药", "剂量", "副作用", "禁忌", "服用"), + "drug": ( + "药", "用药", "剂量", "副作用", "禁忌", "服用", + # How to take a medicine is a drug question even when the drug + # name itself is the only drug word in the sentence, e.g. + # "布洛芬怎么吃?有什么注意事项?" used to fall through to "faq" + # on "注意事项" and then retrieve nothing. + "怎么吃", "如何吃", "怎么服用", "如何服用", "吃法", "用法", "用量", + "能吃吗", "可以吃吗", + ), "exam": ("检查", "检验", "化验", "指标", "报告", "价格", "多少钱"), "department": ( "科室", "挂什么号", "挂什么科", "挂哪个科", "看什么科", "去哪个科", @@ -32,12 +40,24 @@ class IntentRouter: "structured": ("库存", "有货", "排班", "号源", "价格", "多少钱", "费用"), } + def __init__(self, drug_names: Iterable[str] | None = None) -> None: + # Drug names are supplied by the caller (the workflow passes the + # names of the drug documents in the knowledge catalog). A bare + # router still works: the usage patterns in KEYWORDS["drug"] cover + # questions such as "布洛芬怎么吃". + self.drug_names = tuple( + dict.fromkeys(name.strip() for name in (drug_names or ()) if name and name.strip()) + ) + def classify(self, text: str) -> Intent: normalized = text.lower() structured = sum(1 for word in self.KEYWORDS["structured"] if word in normalized) if structured and any(word in normalized for word in ("库存", "有货", "排班", "号源", "价格", "多少钱", "费用")): return "structured" scores = {intent: sum(1 for word in words if word in normalized) for intent, words in self.KEYWORDS.items() if intent != "structured"} + for name in self.drug_names: + if name.lower() in normalized: + scores["drug"] = scores.get("drug", 0) + 1 best = max(scores, key=scores.get) return best if scores[best] else "unknown" @@ -163,6 +183,39 @@ def _load_documents(self) -> list[KnowledgeDocument]: catalog = self.knowledge_dir / "catalog.json" return load_catalog(catalog) + @property + def drug_names(self) -> tuple[str, ...]: + """Drug-related terms from the drug documents in the catalog. + + Tags are curated per document, but some are generic clinical words + (e.g. "过敏", "皮疹") that belong to symptoms or other intents, so + they are filtered out: only terms that are not part of the shared + clinical vocabulary and not a keyword of another intent may vote + for the drug intent. + """ + other_keywords = { + word + for intent, words in IntentRouter.KEYWORDS.items() + if intent != "drug" + for word in words + } + clinical_terms = set(MedicalDocumentCleaner._EMBEDDING_QUERY_TERMS) + # "止痛" and "退热" are effects, not drug names: as intent signals + # they would outvote the disease intent on symptom questions such + # as "发烧怎么退热" or "头痛怎么止痛". + effect_words = {"止痛", "退热"} + names = { + tag.strip() + for document in self.documents + if document.category == "drug" + for tag in document.tags + if tag and tag.strip() + and tag.strip() not in other_keywords + and tag.strip() not in clinical_terms + and tag.strip() not in effect_words + } + return tuple(sorted(names)) + @staticmethod def _cosine(left: list[float], right: list[float]) -> float: return sum(a * b for a, b in zip(left, right)) diff --git a/backend/app/sql_guard.py b/backend/app/sql_guard.py index 6ca551a..a4816c3 100644 --- a/backend/app/sql_guard.py +++ b/backend/app/sql_guard.py @@ -539,6 +539,75 @@ def execute(self, intent: str, sql: str, params: tuple[Any, ...] = ()) -> SQLQue ) return SQLQueryResult(intent, validated, params, (), (), blocked=True, reason=reason) + def _known_names(self, table: str) -> tuple[str, ...] | None: + """Distinct entity names registered in a whitelisted table. + + The names come from the table itself (the same data the LIKE + predicate searches), never from free text, so a lookup term can + only ever be an allowlisted value or one of its prefixes. Returns + ``None`` when the list cannot be loaded (e.g. the data backend is + unavailable); callers then fall back to the legacy term extraction + instead of pretending the catalog is empty. + """ + if table not in self.TABLE_COLUMNS: + return None + column = self.TABLE_COLUMNS[table][0] + sql = f"SELECT DISTINCT {column} FROM {table}" + try: + if self.backend is not None: + ensure_ready = getattr(self.backend, "ensure_ready", None) + if callable(ensure_ready): + if not ensure_ready(): + return None + elif not getattr(self.backend, "ready", False): + return None + _, rows = self.backend.execute(sql, ()) + names = [str(row.get(column, "")) for row in rows] + else: + with sqlite3.connect(self.db_path) as conn: + names = [str(row[0]) for row in conn.execute(sql).fetchall()] + except Exception: + return None + return tuple(sorted({name.strip() for name in names if name and name.strip()})) + + @staticmethod + def _match_known_term(text: str, known_names: tuple[str, ...]) -> str: + """Longest registered entity name (or its longest known prefix) in text. + + A full registered name wins; otherwise the longest prefix of a + registered name (at least 2 characters, e.g. "布洛芬" for + "布洛芬缓释胶囊") is used, so the LIKE predicate stays an + indexable prefix search. Returns "" when no registered name + matches, so the caller can ask for clarification instead of + running a lookup that is guaranteed to return zero rows. + """ + best = "" + for name in known_names: + if name and name in text and len(name) > len(best): + best = name + if best: + return best + for name in known_names: + for end in range(len(name), 1, -1): + prefix = name[:end] + if prefix in text: + if len(prefix) > len(best): + best = prefix + break + return best + + @staticmethod + def _unregistered_term_reason(term: str, kind: str) -> str: + """Clarification reason when the user named something unregistered. + + ``term`` is the legacy extraction of what the user wrote; it is + only echoed back when it is short and free of LIKE metacharacters, + otherwise the generic prompt for a specific name is used. + """ + if term and len(term) <= 24 and not any(ch in term for ch in ("%_", "\\")): + return f"未能识别出已登记的{kind}名称“{term}”,请确认名称是否正确,或提供完整的{kind}名称" + return f"请提供需要查询的具体{kind}名称" + def from_natural_language(self, text: str) -> SQLQueryResult | None: normalized = text.strip() if not any(word in normalized for word in ("库存", "有货", "排班", "号源", "价格", "多少钱", "费用")): @@ -546,7 +615,11 @@ def from_natural_language(self, text: str) -> SQLQueryResult | None: if self.unavailable_reason: return SQLQueryResult("structured", "", (), (), (), blocked=True, reason=self.unavailable_reason) if any(word in normalized for word in ("库存", "有货")): - drug = self._extract_term(normalized, ("库存", "有货", "药品")) + known = self._known_names("drug_inventory") + if known is not None: + drug = self._match_known_term(normalized, known) + else: + drug = self._extract_term(normalized, ("库存", "有货", "药品")) if not drug: return SQLQueryResult( "drug_inventory", @@ -555,7 +628,10 @@ def from_natural_language(self, text: str) -> SQLQueryResult | None: (), (), blocked=True, - reason="请提供需要查询的具体药品名称", + reason=self._unregistered_term_reason( + self._extract_term(normalized, ("库存", "有货", "药品")), + "药品", + ), ) sql = "SELECT name, stock, unit, updated_at FROM drug_inventory WHERE name LIKE ? ORDER BY stock DESC LIMIT 50" return self.execute("drug_inventory", sql, (f"{drug}%",)) @@ -573,7 +649,11 @@ def from_natural_language(self, text: str) -> SQLQueryResult | None: ) sql = "SELECT doctor_name, department, date, shift, available_slots FROM doctor_schedules WHERE department LIKE ? ORDER BY date, shift LIMIT 50" return self.execute("doctor_schedules", sql, (f"{department}%",)) - exam = self._extract_term(normalized, ("价格", "多少钱", "费用", "检查", "检验")) + known = self._known_names("exam_prices") + if known is not None: + exam = self._match_known_term(normalized, known) + else: + exam = self._extract_term(normalized, ("价格", "多少钱", "费用", "检查", "检验")) if not exam: return SQLQueryResult( "exam_prices", @@ -582,7 +662,10 @@ def from_natural_language(self, text: str) -> SQLQueryResult | None: (), (), blocked=True, - reason="请提供需要查询的具体检查或检验名称", + reason=self._unregistered_term_reason( + self._extract_term(normalized, ("价格", "多少钱", "费用", "检查", "检验")), + "检查或检验", + ), ) sql = "SELECT test_name, price, department, notes FROM exam_prices WHERE test_name LIKE ? ORDER BY price LIMIT 50" return self.execute("exam_prices", sql, (f"{exam}%",)) diff --git a/backend/app/workflow.py b/backend/app/workflow.py index 5dbcc68..4e94410 100644 --- a/backend/app/workflow.py +++ b/backend/app/workflow.py @@ -147,7 +147,7 @@ class MedGuideWorkflow: r"(?:处方|用药方案|治疗方案|停药|停用|停服|加量|减量|换药)\s*" r"(?:建议|指令|结论|方案)?", r"(?:(?:(?:我|我们|医生|药师)\s*)?(?:建议|提醒|请)\s*(?:你|您|患者)?\s*)?" - r"(?:不能|不可|不要|请勿|切勿|不应|不得|不建议)\s*(?:自行|随意|擅自)\s*" + r"(?:不能|不可|不要|请勿|切勿|不应|不得|不建议|不)\s*(?:自行|随意|擅自)\s*" r"(?:停药|停用|停服|停止服用|停止使用|暂停服用|服用|口服|使用|吃药|" r"加量|减量|加倍|减半|调高|调低|换药|调整用药)" r"(?:(?!但是|然而|不过|可是|却|但|所以|因此|那就|那么|建议|请|" @@ -179,7 +179,7 @@ def __init__( self.retriever = retriever self.sql_guard = sql_guard self.safety = safety - self.router = IntentRouter() + self.router = IntentRouter(drug_names=retriever.drug_names) self.answerer = answerer or OpenAIAnswerer() self.cleaner = MedicalDocumentCleaner() self.langgraph_available = self._check_langgraph() @@ -669,6 +669,12 @@ def draft(self, state: WorkflowState) -> WorkflowState: if result.get("blocked"): if getattr(self.answerer, "local", False) and str(result.get("reason", "")).startswith("尚未连接医院业务数据"): response = f"{result['reason']}。请通过医院官方渠道确认相关信息。" + elif str(result.get("reason", "")).startswith(("请提供需要查询的具体", "未能识别出已登记的")): + # Clarification, not a safety block: the request was + # understood as a lookup but no registered entity + # matched, so say so instead of implying a data + # protection refusal or "no stock". + response = f"{result['reason']}。可以换成查询药品库存、科室排班或检查价格。" else: response = f"为了保护数据安全,这次查询没有执行:{result.get('reason')}。可以换成查询药品库存、科室排班或检查价格。" elif result.get("rows"): diff --git a/backend/tests/test_drug_query.py b/backend/tests/test_drug_query.py new file mode 100644 index 0000000..765f4f1 --- /dev/null +++ b/backend/tests/test_drug_query.py @@ -0,0 +1,142 @@ +"""Issue #7: drug questions must be answered, and structured lookups must +match registered entities (or ask for clarification) instead of running a +lookup with a garbage prefix that returns zero rows.""" + +import pytest + +from app.retrieval import HybridRetriever, IntentRouter +from app.safety import SafetyEngine +from app.sql_guard import ReadOnlySQLGuard +from app.workflow import MedGuideWorkflow + + +def make_workflow() -> MedGuideWorkflow: + return MedGuideWorkflow(HybridRetriever(), ReadOnlySQLGuard(), SafetyEngine()) + + +# --- A: drug questions ------------------------------------------------------- + +def test_ibuprofen_how_to_take_returns_cited_checklist() -> None: + result = make_workflow().run( + {"session_id": "drug-7", "user_message": "布洛芬怎么吃?有什么注意事项?", "profile": {}} + ) + assert result["intent"] == "drug" + assert result["answer_source"] != "clarification-template" + assert any(item["id"].startswith("drug-ibuprofen-001") for item in result["citations"]) + # The catalog entry carries no dosage of its own: the answer must quote + # its checklist and defer dosage to the package insert, not invent one. + assert "过敏史" in result["response"] + assert "具体剂量和疗程以当前药品说明书及医生或药师建议为准" in result["response"] + assert "缺少足够的背景信息" not in result["response"] + + +def test_loratadine_question_is_not_swallowed_by_safety_review() -> None: + result = make_workflow().run( + {"session_id": "drug-7", "user_message": "氯雷他定怎么吃,有什么注意事项", "profile": {}} + ) + assert result["intent"] == "drug" + assert any(item["id"].startswith("drug-loratadine-001") for item in result["citations"]) + assert "不自行停药" in result["response"] + assert "已停止展示" not in result["response"] + + +@pytest.mark.parametrize( + ("query", "expected"), + [ + ("布洛芬怎么吃?有什么注意事项?", "drug"), + ("布洛芬有什么副作用", "drug"), + ("皮疹看什么科?", "department"), + ("咳嗽三天应该挂什么科?", "department"), + ], +) +def test_router_classifies_drug_questions(query: str, expected: str) -> None: + router = IntentRouter(drug_names=HybridRetriever().drug_names) + assert router.classify(query) == expected + + +def test_router_knows_catalog_drug_names_without_hardcoding_them() -> None: + names = HybridRetriever().drug_names + assert "布洛芬" in names + assert "氯雷他定" in names + # Generic effect words must not vote for the drug intent: "发烧怎么退热" + # is a symptom question, not a drug question. + assert "退热" not in names + assert "止痛" not in names + assert IntentRouter(drug_names=names).classify("氯雷他定有什么注意事项") == "drug" + + +# --- B: structured lookup term extraction ----------------------------------- + +@pytest.mark.parametrize( + "query", + [ + "我想查一下布洛芬的库存", + "请帮我查布洛芬库存", + "布洛芬还有货吗", + "布洛芬有没有货", + "查询布洛芬库存", + ], +) +def test_colloquial_inventory_questions_find_ibuprofen(query: str) -> None: + result = ReadOnlySQLGuard().from_natural_language(query) + assert result is not None + assert result.blocked is False + assert result.params == ("布洛芬%",) + assert result.rows and result.rows[0]["name"] == "布洛芬缓释胶囊" + + +def test_colloquial_inventory_question_finds_loratadine() -> None: + result = ReadOnlySQLGuard().from_natural_language("氯雷他定还有货吗") + assert result is not None + assert result.blocked is False + assert result.params == ("氯雷他定%",) + assert result.rows and result.rows[0]["name"] == "氯雷他定片" + + +@pytest.mark.parametrize( + ("query", "kind"), + [ + ("阿司匹林库存", "药品"), + ("心电图多少钱", "检查或检验"), + ], +) +def test_unregistered_entity_is_blocked_with_clarification(query: str, kind: str) -> None: + result = ReadOnlySQLGuard().from_natural_language(query) + assert result is not None + assert result.blocked is True + assert result.rows == () + assert f"未能识别出已登记的{kind}名称" in (result.reason or "") + + +def test_bare_inventory_question_still_asks_for_a_specific_name() -> None: + result = ReadOnlySQLGuard().from_natural_language("查库存") + assert result is not None + assert result.blocked is True + assert "具体" in (result.reason or "") + + +def test_injection_inside_inventory_question_cannot_escape_the_allowlist() -> None: + result = ReadOnlySQLGuard().from_natural_language( + "布洛芬库存' UNION SELECT name, stock, unit, updated_at FROM drug_inventory --" + ) + assert result is not None + assert result.blocked is False + assert "UNION" not in result.sql + assert result.rows and result.rows[0]["name"] == "布洛芬缓释胶囊" + + +def test_chat_answer_distinguishes_unheard_from_out_of_stock() -> None: + workflow = make_workflow() + unknown = workflow.run( + {"session_id": "drug-7", "user_message": "阿司匹林库存", "profile": {}} + ) + assert unknown["structured_result"]["blocked"] is True + assert "未能识别出已登记的药品名称" in unknown["response"] + assert "暂时没有匹配记录" not in unknown["response"] + + known = workflow.run( + {"session_id": "drug-7", "user_message": "布洛芬还有货吗", "profile": {}} + ) + assert known["structured_result"]["blocked"] is False + assert "布洛芬缓释胶囊" in known["response"] + assert "128" in known["response"] From 767af31f8781b535089c1caaadfd99779f8f2f61 Mon Sep 17 00:00:00 2001 From: Zhenxian Liang Date: Wed, 18 Nov 2026 21:12:52 +0800 Subject: [PATCH 2/2] Rebase fix for #7 onto fix/issue-6-anon-access --- backend/app/main.py | 56 +++++- backend/app/models.py | 6 + backend/app/safety.py | 2 +- backend/app/store.py | 89 +++++++++ backend/app/workflow.py | 169 ++++++++++++++++-- backend/tests/conftest.py | 22 +++ backend/tests/test_anon_access.py | 87 +++++++++ backend/tests/test_api.py | 4 + backend/tests/test_auth.py | 10 +- backend/tests/test_citation_boundary.py | 2 + ...test_deployment_and_session_regressions.py | 5 + backend/tests/test_emergency_unlock.py | 105 +++++++++++ backend/tests/test_info_extraction.py | 152 ++++++++++++++++ backend/tests/test_session_history.py | 159 ++++++++++++++++ .../test_workflow_and_safety_regressions.py | 16 +- frontend/src/App.tsx | 160 ++++++++++++++++- frontend/src/styles.css | 1 + 17 files changed, 1007 insertions(+), 38 deletions(-) create mode 100644 backend/tests/test_anon_access.py create mode 100644 backend/tests/test_emergency_unlock.py create mode 100644 backend/tests/test_info_extraction.py create mode 100644 backend/tests/test_session_history.py diff --git a/backend/app/main.py b/backend/app/main.py index 217a42a..1f20cf7 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -565,9 +565,13 @@ def _require_access( # A proxy-validated cookie can expire or be revoked before this handler. # Cookie-bearing offline requests must not fall back to anonymous access; # production service-header priority remains unchanged. - if principal is None and ( - getattr(current, "production", False) or getattr(current, "local", False) or session_token is not None - ): + # Issue #6: authentication is required in every mode. Test/offline used + # to let requests without any credential through (while rejecting an + # invalid cookie), which exposed protected APIs and other users' + # sessions anonymously. There is intentionally no anonymous fallback + # switch: /api/health and /api/ready stay public for probes, and every + # other caller must present a valid session cookie or service token. + if principal is None: raise HTTPException(status_code=401, detail="请先登录") _require_runtime(current) return principal @@ -580,11 +584,19 @@ def _require_service_access( api_key: str | None = None, ) -> str | None: _require_secure_transport(current, request) - if not current.production: - return None - principal = _principal_from_headers(current, authorization, api_key) - _require_runtime(current) - return principal + if current.production: + principal = _principal_from_headers(current, authorization, api_key) + _require_runtime(current) + return principal + # Issue #6: the operator endpoint was wide open outside production + # (this function returned before any check). No service API tokens are + # configured in test/offline/local modes, so a logged-in user session is + # the credential here; anonymous access is never allowed. Production + # keeps the stricter service-token-only rule. + username = _username_from_cookie(current, _session_token_from_request(current, request)) + if username is None: + raise HTTPException(status_code=401, detail="请先登录") + return f"user:{username}" def _message_fingerprint(message: str) -> str: @@ -1022,6 +1034,34 @@ def create_session( return SessionCreateResponse(session_id=state["session_id"], state=public_state(state)) +@app.get("/api/sessions") +def list_sessions( + http_request: Request, + authorization: str | None = Header(default=None), + api_key: str | None = Header(default=None, alias="X-API-Key"), +) -> dict[str, Any]: + # Registered before /api/sessions/{session_id} so "sessions" is never + # treated as a session id. + current = get_services() + owner_id = _require_access( + current, + http_request, + authorization, + api_key, + _session_token_from_request(current, http_request), + ) + try: + sessions = current.store.list_sessions(owner_id) + except SessionBackendError as exc: + raise HTTPException(status_code=503, detail=str(exc)) from exc + return { + "sessions": sessions, + # False when the shared backend cannot enumerate sessions; the list + # is then empty on purpose rather than partial. See store.py. + "complete": current.store.listing_complete, + } + + @app.get("/api/sessions/{session_id}") def get_session( session_id: str, diff --git a/backend/app/models.py b/backend/app/models.py index 7ae75c6..22a452b 100644 --- a/backend/app/models.py +++ b/backend/app/models.py @@ -12,6 +12,7 @@ class PatientProfile(TypedDict, total=False): age: int sex: str duration: str + temperature: str symptoms: list[str] associated_symptoms: list[str] history: str @@ -24,6 +25,11 @@ class WorkflowState(TypedDict, total=False): owner_id: str user_message: str normalized_message: str + # Full turn transcript for this session, oldest first. Each entry is + # plain text plus identifiers only: {"role": "user" | "assistant", + # "content": str, "response_id": str (assistant only), "timestamp": str}. + # No passwords, cookies, or tokens are ever stored here. + messages: list[dict[str, Any]] profile: PatientProfile intent: Intent risk_level: RiskLevel diff --git a/backend/app/safety.py b/backend/app/safety.py index fa9a4e7..3966c19 100644 --- a/backend/app/safety.py +++ b/backend/app/safety.py @@ -244,7 +244,7 @@ def screen(self, text: str, profile: PatientProfile | None = None) -> RiskAssess break if flags: - advice = "建议立即联系当地急救服务或前往最近的急诊;不要仅依赖线上问答等待观察。" + advice = "请立即拨打 120(中国大陆急救电话)或前往最近的急诊;不要仅依赖线上问答等待观察。" return RiskAssessment("high", tuple(dict.fromkeys(flags)), advice) watch_flags = [ diff --git a/backend/app/store.py b/backend/app/store.py index 52d06b0..b562de6 100644 --- a/backend/app/store.py +++ b/backend/app/store.py @@ -170,6 +170,7 @@ def create(self, owner_id: str | None = None, idempotency_key: str | None = None "_version": 0, "mode": self.mode, "events": [], + "messages": [], "citations": [], "risk_flags": [], "risk_assessed": False, @@ -362,9 +363,97 @@ def request_result(self, session_id: str, request_id: str, owner_id: str | None result = state.get("request_results", {}).get(request_id) return merge_request_result(state, result) if isinstance(result, dict) else None + @property + def listing_complete(self) -> bool: + """Whether :meth:`list_sessions` can enumerate every session. + + The in-memory store can. A shared Redis backend cannot be enumerated + (there is no session index), so listing is incomplete by design and + :meth:`list_sessions` returns ``[]`` rather than a partial list. + """ + if self.backend is None: + return True + return callable(getattr(self.backend, "list_states", None)) + + @staticmethod + def _session_list_entry(state: WorkflowState) -> dict[str, Any]: + messages = state.get("messages", []) or [] + first_user = next( + ( + str(item.get("content", "")).strip() + for item in messages + if isinstance(item, dict) + and item.get("role") == "user" + and str(item.get("content", "")).strip() + ), + "", + ) + title = first_user[:30] or str(state.get("summary", "") or "") or "新的健康咨询" + return { + "session_id": state.get("session_id"), + "title": title, + "summary": state.get("summary", ""), + "turn_count": int(state.get("turn_count", 0)), + "updated_at": state.get("updated_at"), + "risk_level": state.get("risk_level") if state.get("risk_assessed") else None, + } + + def list_sessions(self, owner_id: str | None = None) -> list[dict[str, Any]]: + """Return one owner's unexpired sessions, newest first. + + Only the in-memory store can enumerate sessions. When a shared + backend is selected and it offers no ``list_states`` enumeration, + this returns ``[]`` (see :attr:`listing_complete`) instead of a + misleading partial list. + """ + owner = str(owner_id or "") + if self.backend is not None: + listing = getattr(self.backend, "list_states", None) + if not callable(listing): + return [] + try: + remote_states = listing(owner) + except Exception as exc: + raise SessionBackendError("共享会话后端暂时不可用,请稍后重试") from exc + states = [ + state + for state in (remote_states or []) + if isinstance(state, dict) and str(state.get("owner_id", "")) == owner + ] + states.sort(key=lambda item: str(item.get("updated_at") or ""), reverse=True) + return [self._session_list_entry(state) for state in states] + with self._lock: + self._purge_expired() + states = [ + deepcopy(state) + for state in self._sessions.values() + if str(state.get("owner_id", "")) == owner + ] + states.sort(key=lambda item: str(item.get("updated_at") or ""), reverse=True) + return [self._session_list_entry(state) for state in states] + + @staticmethod + def _public_messages(state: WorkflowState) -> list[dict[str, Any]]: + """Return only the transcript fields the API may expose.""" + messages: list[dict[str, Any]] = [] + for item in state.get("messages", []) or []: + if not isinstance(item, dict) or item.get("role") not in {"user", "assistant"}: + continue + entry: dict[str, Any] = { + "role": item["role"], + "content": str(item.get("content", "")), + } + if item.get("response_id"): + entry["response_id"] = str(item["response_id"]) + if item.get("timestamp"): + entry["timestamp"] = str(item["timestamp"]) + messages.append(entry) + return messages + def public(self, state: WorkflowState) -> dict: return { "session_id": state.get("session_id"), + "messages": self._public_messages(state), "turn_count": state.get("turn_count", 0), "profile": state.get("profile", {}), "risk_level": state.get("risk_level") if state.get("risk_assessed") else None, diff --git a/backend/app/workflow.py b/backend/app/workflow.py index 4e94410..2ba5a7c 100644 --- a/backend/app/workflow.py +++ b/backend/app/workflow.py @@ -376,9 +376,17 @@ def normalize(self, state: WorkflowState) -> WorkflowState: state["normalized_message"] = re.sub(r"\s+", " ", message) return state + # Colloquial variants sit next to their written form. Keep the user's + # own wording (``发烧`` rather than normalising to ``发热``) so the + # profile panel shows what was actually said; ingestion already uses + # the same vocabulary (see ``ingestion._EMBEDDING_QUERY_TERMS``). _PROFILE_SYMPTOMS = ( - "发热", "咳嗽", "咽痛", "腹痛", "头痛", "胸痛", "皮疹", "头晕", "恶心", "呕吐", "乏力", - "流鼻涕", "流涕", "鼻塞", "呼吸困难", "气促", + "发热", "发烧", "高烧", "低热", "咳嗽", "咽痛", "喉咙痛", "喉咙疼", + "嗓子疼", "嗓子痛", "腹痛", "肚子痛", "肚子疼", "头痛", "头疼", + "胸痛", "胸闷", "皮疹", "瘙痒", "头晕", "恶心", "呕吐", "乏力", + "疲劳", "累", "流鼻涕", "流涕", "鼻塞", "呼吸困难", "气促", "气短", + "腹泻", "便秘", "心悸", "失眠", "睡眠不好", "睡不好", "耳鸣", "耳痛", + "水肿", "腰痛", "关节痛", "牙痛", "感冒", "流感", ) _PROFILE_SPLIT = re.compile(r"[,,。;;!?!?]|但是|可是|然而|但") _PROFILE_THIRD_PARTY = re.compile( @@ -401,8 +409,27 @@ def normalize(self, state: WorkflowState) -> WorkflowState: r"(?P\d{1,4}|[零〇一二两三四五六七八九十百]+|半)\s*" r"(?P分钟|小时|天|周|个月|月|年)" ) - _DURATION_PREFIX = re.compile(r"(?:持续|已经|已有|大约|约|大概|差不多)\s*$") + _DURATION_PREFIX = re.compile(r"(?:持续|已经|已有|大约|约|大概|差不多|最近)\s*$") _DURATION_NEGATION = re.compile(r"(?:不是|并非|没有|没|否认|不到|不足|不满)\s*$") + # Body temperature, mirroring the range already used by ingestion + # (35-42.x degrees). Stored as e.g. ``38.5度``. + _TEMPERATURE = re.compile( + r"(?(?:3[5-9]|4[0-2])(?:\.\d{1,2})?)\s*(?:摄氏度|℃|°C|度)" + ) + # Relative onset (``昨天开始``) only yields a duration when no numeric + # duration is known yet, so a later turn never overwrites an earlier, + # more precise one (e.g. fever for 3 days, sore throat since yesterday). + _RELATIVE_ONSET = {"大前天": "3天", "前天": "2天", "昨天": "1天"} + _RELATIVE_ONSET_PATTERN = re.compile(r"(?:从)?(大前天|前天|昨天)(?:开始|起|就|才)?") + _CHRONIC_CONDITIONS = ( + "慢性病", "基础疾病", "基础病", "重大疾病", "高血压", "糖尿病", "心脏病", "哮喘", + ) + # Symptom spellings with filler words in between (``睡眠也不好`` for + # ``睡眠不好``). Tuple lookup is substring-based, so these need a + # pattern instead; negation is checked the same way as for plain terms. + _PROFILE_SYMPTOM_PATTERNS = { + "睡眠不好": re.compile(r"睡(?:眠)?(?:也|都)?不好"), + } _DURATION_MAXIMUM = { "分钟": 10080, "小时": 8760, @@ -501,6 +528,13 @@ def _extract_duration(cls, clause: str) -> str | None: return f"{numeric}{unit}" return None + @classmethod + def _extract_relative_onset(cls, clause: str) -> str | None: + match = cls._RELATIVE_ONSET_PATTERN.search(clause) + if not match: + return None + return cls._RELATIVE_ONSET.get(match.group(1)) + def extract_profile(self, state: WorkflowState) -> WorkflowState: profile: PatientProfile = dict(state.get("profile", {})) text = state.get("normalized_message", "") @@ -536,10 +570,23 @@ def extract_profile(self, state: WorkflowState) -> WorkflowState: if age_match: profile["age"] = int(age_match.group(1)) break + duration_found = False for clause in patient_clauses: duration = self._extract_duration(clause) if duration: profile["duration"] = duration + duration_found = True + break + if not duration_found and not profile.get("duration"): + for clause in patient_clauses: + onset = self._extract_relative_onset(clause) + if onset: + profile["duration"] = onset + break + for clause in patient_clauses: + temperature_match = self._TEMPERATURE.search(clause) + if temperature_match: + profile["temperature"] = f"{temperature_match.group('value')}度" break symptoms = list(profile.get("symptoms", [])) @@ -547,6 +594,14 @@ def extract_profile(self, state: WorkflowState) -> WorkflowState: if any(self._asserted_profile_term(clause, symptom) for clause in patient_clauses): if symptom not in symptoms: symptoms.append(symptom) + for canonical, pattern in self._PROFILE_SYMPTOM_PATTERNS.items(): + if canonical in symptoms: + continue + for clause in patient_clauses: + match = pattern.search(clause) + if match and not self._PROFILE_NEGATION_BEFORE.search(clause[:match.start()]): + symptoms.append(canonical) + break profile["symptoms"] = symptoms if symptoms and not profile.get("chief_complaint"): profile["chief_complaint"] = symptoms[0] @@ -555,6 +610,28 @@ def extract_profile(self, state: WorkflowState) -> WorkflowState: if history_match: profile["history"] = history_match.group(1).strip() break + # ``没有慢性病`` / ``无基础疾病``: the negated condition itself + # is the history, even though no ``病史`` noun follows it. + # Checked before the generic ``…病史`` rule so ``没有慢性病史`` + # becomes ``否认慢性病`` instead of the truncated ``否认慢性``. + chronic_pattern = "|".join(self._CHRONIC_CONDITIONS) + negative_chronic_match = re.search( + rf"(?:没有|无|否认)\s*({chronic_pattern})(?:史|等)?", + clause, + ) + if negative_chronic_match: + profile["history"] = f"否认{negative_chronic_match.group(1)}" + break + positive_chronic_match = re.search( + rf"(?:患有|有)\s*({chronic_pattern})(?:史|等)?", + clause, + ) + if positive_chronic_match and not re.search( + r"(?:没有|无|否认|不是|并非)", + clause[:positive_chronic_match.start()], + ): + profile["history"] = positive_chronic_match.group(1) + break negative_history_match = re.search( r"(?:没有|无|否认)\s*([^,。;;]{1,24}?)(?:等)?(?:既往病史|病史)", clause, @@ -585,19 +662,23 @@ def intent(self, state: WorkflowState) -> WorkflowState: return state def risk(self, state: WorkflowState) -> WorkflowState: + # Risk is re-evaluated from the current message on every turn. + # A previous high-risk turn used to stick permanently (issue #5): + # any follow-up, even an unrelated question, kept returning the + # emergency text with no retrieval. The earlier high-risk turn is + # still preserved in ``risk_history`` and surfaced as a brief + # reminder by ``draft``; only the live level/flags/advice follow + # the current message. assessment = self.safety.screen(state.get("normalized_message", ""), state.get("profile", {})) - previous_level = state.get("risk_level") - previous_flags = list(state.get("risk_flags", [])) - sticky_high = previous_level == "high" - if sticky_high or assessment.level == "high": + if assessment.level == "high": state["risk_level"] = "high" - state["risk_flags"] = list(dict.fromkeys(previous_flags + list(assessment.flags))) + state["risk_flags"] = list(assessment.flags) state["risk_advice"] = ( - "建议立即联系当地急救服务或前往最近的急诊;不要仅依赖线上问答等待观察。" + "请立即拨打 120(中国大陆急救电话)或前往最近的急诊;不要仅依赖线上问答等待观察。" ) - elif previous_level == "watch" or assessment.level == "watch": + elif assessment.level == "watch": state["risk_level"] = "watch" - state["risk_flags"] = list(dict.fromkeys(previous_flags + list(assessment.flags))) + state["risk_flags"] = list(assessment.flags) state["risk_advice"] = assessment.advice else: state["risk_level"] = assessment.level @@ -609,7 +690,7 @@ def risk(self, state: WorkflowState) -> WorkflowState: "at": datetime.now(timezone.utc).isoformat(), "level": state["risk_level"], "flags": list(state.get("risk_flags", [])), - "source": "sticky-history" if sticky_high else "rules", + "source": "rules", } ) state["risk_history"] = history[-20:] @@ -715,6 +796,18 @@ def draft(self, state: WorkflowState) -> WorkflowState: state["next_question"] = missing if missing and state.get("risk_level") != "high" and not state.get("structured_result"): response += f"\n\n为了缩小分流范围,下一步想确认:{missing}" + if state.get("risk_level") != "high": + # First normal turn after an emergency turn: keep a brief + # reminder so the earlier emergency is not silently forgotten, + # without locking the session in emergency mode (issue #5). + history = list(state.get("risk_history", [])) + if len(history) >= 2 and history[-2].get("level") == "high" and history[-1].get("level") != "high": + prior_flags = [str(flag) for flag in history[-2].get("flags", []) if str(flag).strip()][:2] + if prior_flags: + response += ( + f"\n\n提醒:如之前出现的{'、'.join(prior_flags)}再次出现或加重," + "请立即拨打 120 或前往最近的急诊。" + ) state["response"] = response return state @@ -733,6 +826,9 @@ def _external_query_summary(self, state: WorkflowState) -> str: duration = str(profile.get("duration", "")) if duration and re.fullmatch(r"[\d一二两三四五六七八九十半]+(?:分钟|小时|天|周|个月|月|年)", duration): parts.append(f"持续时间:{duration}") + temperature = str(profile.get("temperature", "")) + if temperature and re.fullmatch(r"(?:3[5-9]|4[0-2])(?:\.\d{1,2})?度", temperature): + parts.append(f"体温:{temperature}") associated = profile.get("associated_symptoms") if isinstance(associated, list): safe_associated = [item for item in associated if item in self._PROFILE_SYMPTOMS] @@ -758,7 +854,7 @@ def _next_question(profile: PatientProfile, risk_level: str, text: str) -> str | return "患者大致年龄是多少?" if not profile.get("duration"): return "症状从什么时候开始,持续了多久?" - if not profile.get("associated_symptoms") and any(word in text for word in ("发热", "咳嗽", "腹痛", "头痛", "皮疹")): + if not profile.get("associated_symptoms") and any(word in text for word in ("发热", "发烧", "咳嗽", "腹痛", "头痛", "头疼", "喉咙痛", "皮疹")): return "是否伴随发热、明显疼痛加重、呼吸困难或其他新出现的症状?" return None @@ -780,7 +876,9 @@ def safety_review(self, state: WorkflowState) -> WorkflowState: state["safety_blocked"] = True state["safety_block_reason"] = "unsafe-medical-instruction" return state - if "不代表诊断" not in response and state.get("risk_level") != "high": + if "不代表诊断" not in response: + # The disclaimer applies to emergency answers too (issue #5); + # it used to be skipped whenever the risk level was high. response += "\n\n提示:MedGuide 不替代医生诊断或处方。" state["response"] = response state["safety_blocked"] = False @@ -804,6 +902,46 @@ def _contains_unsafe_output(cls, response: str, compact_response: str) -> bool: return True return False + @staticmethod + def _append_turn_messages(state: WorkflowState) -> WorkflowState: + """Record this turn in the session transcript. + + Runs after ``safety_review``, so the assistant entry holds the final + reviewed response. Idempotent replays never reach this node (the + caller returns the stored result first), and ``response_id`` guards + against a duplicate append if a turn were ever executed twice. + """ + user_message = str(state.get("user_message") or state.get("normalized_message") or "").strip() + response = str(state.get("response", "") or "") + response_id = str(state.get("response_id") or "") + if not user_message and not response: + return state + messages = [ + dict(item) + for item in state.get("messages", []) or [] + if isinstance(item, dict) + ] + if response_id and any( + item.get("role") == "assistant" and item.get("response_id") == response_id + for item in messages + ): + return state + timestamp = datetime.now(timezone.utc).isoformat() + if user_message: + messages.append({"role": "user", "content": user_message, "timestamp": timestamp}) + if response: + assistant: dict[str, Any] = { + "role": "assistant", + "content": response, + "timestamp": timestamp, + } + if response_id: + assistant["response_id"] = response_id + messages.append(assistant) + # Bound transcript growth the same way response_ids are bounded. + state["messages"] = messages[-100:] + return state + def finalize(self, state: WorkflowState) -> WorkflowState: citations = state.get("citations", []) structured_result = state.get("structured_result") @@ -823,11 +961,14 @@ def finalize(self, state: WorkflowState) -> WorkflowState: summary_parts.append(str(profile["sex"])) if profile.get("symptoms"): summary_parts.append("主要症状:" + "、".join(profile["symptoms"][:4])) + if profile.get("temperature"): + summary_parts.append(f"体温{profile['temperature']}") if profile.get("duration"): summary_parts.append("持续" + str(profile["duration"])) if profile.get("history"): summary_parts.append("既往史:" + str(profile["history"])) state["summary"] = ";".join(summary_parts) if summary_parts else "已建立会话,等待补充症状和基础信息。" + self._append_turn_messages(state) # The runner writes its actual engine after the node loop completes. state.setdefault("workflow_engine", "deterministic") return state diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 9d2f77c..4cee077 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -6,3 +6,25 @@ os.environ.setdefault("MEDGUIDE_MODE", "test") sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + + +def login_client(client, username: str, password: str = "Correct-Horse-42"): + """Log a test-mode API client in through the real register/login flow. + + Issue #6: protected APIs require a valid session cookie in every mode, + including test mode, so tests that used to call them anonymously must + log in first. The shared test auth database persists between runs, so a + re-run registers nothing new: a 409 falls back to login with the same + password. + """ + registered = client.post( + "/api/auth/register", json={"username": username, "password": password} + ) + assert registered.status_code in {201, 409}, registered.text + if registered.status_code == 409: + logged_in = client.post( + "/api/auth/login", json={"username": username, "password": password} + ) + assert logged_in.status_code == 200, logged_in.text + assert client.get("/api/auth/me").status_code == 200 + return client diff --git a/backend/tests/test_anon_access.py b/backend/tests/test_anon_access.py new file mode 100644 index 0000000..35f9c8f --- /dev/null +++ b/backend/tests/test_anon_access.py @@ -0,0 +1,87 @@ +"""Issue #6: protected APIs must require authentication in every mode. + +In MEDGUIDE_MODE=test (and offline), requests without a valid session +cookie used to reach protected endpoints and even read other users' +sessions, while a request carrying an *invalid* cookie was rejected -- +the check was exactly backwards. These tests pin the fixed behavior: +no credential -> 401, invalid credential -> 401, valid session -> 200, +another user's session -> 404. +""" + +from __future__ import annotations + +import pytest +from fastapi.testclient import TestClient + +from app.main import app +from conftest import login_client + +_ANON_CASES = [ + ("post", "/api/search", {"query": "布洛芬副作用", "intent": "drug"}), + ("post", "/api/sessions", None), + ("post", "/api/chat", {"message": "我咳嗽"}), + ("post", "/api/query", {"text": "查询布洛芬库存"}), + ("post", "/api/feedback", {"session_id": "missing", "message_id": "missing:turn:1", "rating": "up"}), + ("get", "/api/metrics", None), +] + + +@pytest.mark.parametrize(("method", "path", "payload"), _ANON_CASES) +def test_anonymous_requests_are_rejected_in_test_mode(method: str, path: str, payload: dict | None) -> None: + with TestClient(app, base_url="https://testserver") as client: + response = client.request(method, path, json=payload) + assert response.status_code == 401 + assert response.json()["detail"] == "请先登录" + + +@pytest.mark.parametrize("path", ["/api/search", "/api/sessions", "/api/metrics"]) +def test_invalid_cookie_is_rejected_in_test_mode(path: str) -> None: + with TestClient(app, base_url="https://testserver") as client: + client.cookies.set("medguide_session", "invalidtoken123") + if path == "/api/search": + response = client.post(path, json={"query": "咳嗽", "intent": "disease"}) + elif path == "/api/sessions": + response = client.post(path) + else: + response = client.get(path) + assert response.status_code == 401 + assert response.json()["detail"] == "请先登录" + + +def test_logged_in_user_can_use_protected_apis_in_test_mode() -> None: + with TestClient(app, base_url="https://testserver") as client: + login_client(client, "anon_access_user") + created = client.post("/api/sessions") + assert created.status_code == 200 + session_id = created.json()["session_id"] + assert client.get(f"/api/sessions/{session_id}").status_code == 200 + answer = client.post( + "/api/chat", + json={"session_id": session_id, "message": "我咳嗽三天"}, + ) + assert answer.status_code == 200 + assert client.post( + "/api/search", json={"query": "布洛芬副作用", "intent": "drug"} + ).status_code == 200 + assert client.post("/api/query", json={"text": "查询布洛芬库存"}).status_code == 200 + metrics = client.get("/api/metrics") + assert metrics.status_code == 200 + assert metrics.json()["requests"] >= 1 + + +def test_anonymous_and_cross_user_session_reads_are_rejected() -> None: + with TestClient(app, base_url="https://testserver") as owner: + login_client(owner, "anon_owner_user") + session_id = owner.post("/api/sessions").json()["session_id"] + with TestClient(app, base_url="https://testserver") as other: + login_client(other, "anon_other_user") + assert other.get(f"/api/sessions/{session_id}").status_code == 404 + with TestClient(app, base_url="https://testserver") as anonymous: + assert anonymous.get(f"/api/sessions/{session_id}").status_code == 401 + + +def test_public_probes_stay_public_in_test_mode() -> None: + with TestClient(app, base_url="https://testserver") as client: + assert client.get("/api/health").status_code == 200 + assert client.get("/api/health").json()["status"] == "ok" + assert client.get("/api/ready").status_code == 200 diff --git a/backend/tests/test_api.py b/backend/tests/test_api.py index abd2a9f..97923cf 100644 --- a/backend/tests/test_api.py +++ b/backend/tests/test_api.py @@ -2,10 +2,12 @@ import pytest from app.main import AppServices, app +from conftest import login_client def test_session_chat_and_search_api() -> None: with TestClient(app, base_url="https://testserver") as client: + login_client(client, "api_test_user") created = client.post("/api/sessions") assert created.status_code == 200 session_id = created.json()["session_id"] @@ -37,6 +39,7 @@ def test_session_chat_and_search_api() -> None: def test_sse_chat_has_node_and_final_events() -> None: with TestClient(app) as client: + login_client(client, "api_sse_user") response = client.post("/api/chat?stream=true", json={"message": "查布洛芬库存"}) assert response.status_code == 200 assert "event: node" in response.text @@ -108,6 +111,7 @@ def test_missing_mode_defaults_to_fail_closed_production(tmp_path, monkeypatch) def test_api_responses_disable_shared_caching() -> None: with TestClient(app) as client: + login_client(client, "api_cache_user") response = client.post("/api/sessions") assert response.headers["cache-control"] == "no-store, private" assert response.headers["pragma"] == "no-cache" diff --git a/backend/tests/test_auth.py b/backend/tests/test_auth.py index 408ef47..91b1f6d 100644 --- a/backend/tests/test_auth.py +++ b/backend/tests/test_auth.py @@ -472,14 +472,18 @@ def test_offline_valid_cookie_keeps_cross_user_session_isolation(tmp_path, monke client.close() -def test_offline_without_cookie_preserves_explicit_local_anonymous_mode(tmp_path, monkeypatch) -> None: +def test_offline_without_cookie_rejects_anonymous_access(tmp_path, monkeypatch) -> None: + # Behavior change (issue #6): offline/test modes no longer have an + # anonymous mode. Previously this test pinned anonymous session creation + # in offline mode (200 with an empty owner); every protected API now + # requires a valid session in all modes, exactly like production. current = _runtime(tmp_path, cookie_secure=False, production=False) monkeypatch.setattr(main_module, "get_services", lambda: current) client = _client() try: response = client.post("/api/sessions") - assert response.status_code == 200 - assert current.store.get(response.json()["session_id"])["owner_id"] == "" + assert response.status_code == 401 + assert response.json()["detail"] == "请先登录" finally: client.close() diff --git a/backend/tests/test_citation_boundary.py b/backend/tests/test_citation_boundary.py index db5240b..210d5e4 100644 --- a/backend/tests/test_citation_boundary.py +++ b/backend/tests/test_citation_boundary.py @@ -12,6 +12,7 @@ from app.main import _response_from_state, _sanitize_citation_payload, app, public_state, stream_chat from app.models import Citation from app.store import SessionStore +from conftest import login_client def _citation(**overrides: object) -> dict[str, object]: @@ -140,6 +141,7 @@ def test_search_sanitizes_citations_before_computing_count(monkeypatch) -> None: invalid = Citation(**{**valid.__dict__, "id": "patient@example.org"}) with TestClient(app, base_url="https://testserver") as client: + login_client(client, "citation_test_user") monkeypatch.setattr(main_module.get_services().retriever, "search", lambda *_args, **_kwargs: [valid, invalid]) response = client.post("/api/search", json={"query": "咳嗽", "intent": "disease"}) diff --git a/backend/tests/test_deployment_and_session_regressions.py b/backend/tests/test_deployment_and_session_regressions.py index 45ba81d..697bc1b 100644 --- a/backend/tests/test_deployment_and_session_regressions.py +++ b/backend/tests/test_deployment_and_session_regressions.py @@ -14,6 +14,7 @@ from app.sql_guard import ReadOnlySQLGuard from app.store import SessionAuthorizationError, SessionStore from app.workflow import MedGuideWorkflow, WorkflowExecutionError +from conftest import login_client def _workflow() -> MedGuideWorkflow: @@ -82,6 +83,7 @@ def test_production_api_rejects_http_even_with_untrusted_forwarded_proto(monkeyp def test_session_creation_is_idempotent_for_one_client_key() -> None: with TestClient(app) as client: + login_client(client, "deploy_idempotency_user") headers = {"Idempotency-Key": "session-browser-load-001"} first = client.post("/api/sessions", headers=headers) second = client.post("/api/sessions", headers=headers) @@ -94,6 +96,7 @@ def test_session_creation_is_idempotent_for_one_client_key() -> None: def test_chat_request_id_replays_result_without_advancing_turn() -> None: with TestClient(app) as client: + login_client(client, "deploy_replay_user") session_id = client.post("/api/sessions").json()["session_id"] request = { "session_id": session_id, @@ -113,6 +116,7 @@ def test_chat_request_id_replays_result_without_advancing_turn() -> None: def test_request_id_cannot_be_reused_for_different_message() -> None: with TestClient(app) as client: + login_client(client, "deploy_collision_user") session_id = client.post("/api/sessions").json()["session_id"] first = client.post( "/api/chat", @@ -129,6 +133,7 @@ def test_request_id_cannot_be_reused_for_different_message() -> None: def test_duplicate_feedback_is_an_upsert_not_a_second_metric() -> None: with TestClient(app) as client: + login_client(client, "deploy_feedback_user") session_id = client.post("/api/sessions").json()["session_id"] answer = client.post( "/api/chat", diff --git a/backend/tests/test_emergency_unlock.py b/backend/tests/test_emergency_unlock.py new file mode 100644 index 0000000..c0cb4e6 --- /dev/null +++ b/backend/tests/test_emergency_unlock.py @@ -0,0 +1,105 @@ +"""Issue #5: after an emergency turn the session must not stay locked in +emergency mode. Risk is re-evaluated from each message: unrelated +follow-up questions get normal answers (with retrieval), the earlier +high-risk turn is kept in ``risk_history`` and shown as a brief reminder +on the first normal turn, and a new high-risk message re-enters the +emergency flow. +""" + +from __future__ import annotations + +from app.retrieval import HybridRetriever +from app.safety import SafetyEngine +from app.sql_guard import ReadOnlySQLGuard +from app.workflow import MedGuideWorkflow + +EMERGENCY_PREFIX = "当前描述包含需要优先排除的风险信号" + + +def _workflow() -> MedGuideWorkflow: + return MedGuideWorkflow(HybridRetriever(), ReadOnlySQLGuard(), SafetyEngine()) + + +def _emergency_turn() -> dict: + return _workflow().run( + { + "session_id": "emergency-unlock", + "user_message": "胸口突然剧烈疼痛,呼吸困难怎么办?", + "profile": {"symptoms": [], "associated_symptoms": []}, + } + ) + + +def test_emergency_response_names_120_and_carries_disclaimer() -> None: + first = _emergency_turn() + + assert first["risk_level"] == "high" + assert "120" in first["response"] + assert "不替代医生诊断或处方" in first["response"] + + +def test_drug_question_after_emergency_is_answered_normally() -> None: + first = _emergency_turn() + second = _workflow().run( + {**first, "user_message": "布洛芬怎么吃?有什么注意事项?"} + ) + + assert first["risk_level"] == "high" + assert second["risk_level"] == "low" + assert not second["response"].startswith(EMERGENCY_PREFIX) + assert second["citations"], "a normal follow-up should retrieve references again" + # The earlier emergency is not forgotten: history keeps it and the + # answer carries a brief reminder. + assert [entry["level"] for entry in second["risk_history"]].count("high") == 1 + assert "再次出现" in second["response"] + + +def test_unrelated_question_after_emergency_is_answered_normally() -> None: + first = _emergency_turn() + second = _workflow().run({**first, "user_message": "今天天气怎么样"}) + + assert second["risk_level"] == "low" + assert not second["response"].startswith(EMERGENCY_PREFIX) + + +def test_emergency_recurs_when_high_risk_signals_return() -> None: + first = _emergency_turn() + second = _workflow().run( + {**first, "user_message": "布洛芬怎么吃?有什么注意事项?"} + ) + assert second["risk_level"] == "low" + third = _workflow().run({**second, "user_message": "胸痛又发作了,呼吸困难"}) + + assert third["risk_level"] == "high" + assert third["citations"] == [] + assert third["response"].startswith(EMERGENCY_PREFIX) + assert "120" in third["response"] + assert [entry["level"] for entry in third["risk_history"]].count("high") == 2 + + +def test_reminder_only_on_first_turn_after_emergency() -> None: + first = _emergency_turn() + second = _workflow().run( + {**first, "user_message": "布洛芬怎么吃?有什么注意事项?"} + ) + assert "再次出现" in second["response"] + third = _workflow().run({**second, "user_message": "今天天气怎么样"}) + + assert third["risk_level"] == "low" + assert "再次出现" not in third["response"] + + +def test_watch_level_is_reevaluated_too() -> None: + workflow = _workflow() + first = workflow.run( + { + "session_id": "watch-reevaluate", + "user_message": "发热38度", + "profile": {"symptoms": [], "associated_symptoms": []}, + } + ) + assert first["risk_level"] == "watch" + second = workflow.run({**first, "user_message": "今天天气怎么样"}) + + assert second["risk_level"] == "low" + assert not second["response"].startswith(EMERGENCY_PREFIX) diff --git a/backend/tests/test_info_extraction.py b/backend/tests/test_info_extraction.py new file mode 100644 index 0000000..feafe55 --- /dev/null +++ b/backend/tests/test_info_extraction.py @@ -0,0 +1,152 @@ +"""Issue #4: key information (fever, duration, temperature, history) must be +extracted from colloquial user messages instead of being dropped.""" + +from app.retrieval import HybridRetriever +from app.safety import SafetyEngine +from app.sql_guard import ReadOnlySQLGuard +from app.workflow import MedGuideWorkflow + + +def make_workflow() -> MedGuideWorkflow: + return MedGuideWorkflow(HybridRetriever(), ReadOnlySQLGuard(), SafetyEngine()) + + +def run_turn(workflow: MedGuideWorkflow, state: dict, text: str) -> dict: + state = dict(state) + state["user_message"] = text + return workflow.run(state) + + +def test_issue4_two_turn_conversation_extracts_fever_duration_temperature_history(): + workflow = make_workflow() + state = run_turn( + workflow, + {"session_id": "issue4-main", "profile": {}}, + "我最近三天发烧38.5度,还咳嗽,应该怎么办?", + ) + profile = state["profile"] + assert "发烧" in profile["symptoms"] + assert "咳嗽" in profile["symptoms"] + assert profile["duration"] == "3天" + assert profile["temperature"] == "38.5度" + assert "体温38.5度" in state["summary"] + assert "持续3天" in state["summary"] + + state = run_turn(workflow, state, "今年25岁,没有慢性病,昨天开始喉咙痛") + profile = state["profile"] + assert profile["age"] == 25 + assert profile["history"] == "否认慢性病" + assert "喉咙痛" in profile["symptoms"] + # The sore throat started yesterday, but the earlier, more precise + # 3-day duration must not be overwritten by the relative onset. + assert profile["duration"] == "3天" + assert "喉咙痛" in profile["associated_symptoms"] + assert state["next_question"] != "症状从什么时候开始,持续了多久?" + assert "持续3天" in state["summary"] + assert "既往史:否认慢性病" in state["summary"] + + +def test_issue4_relative_onset_only_fills_missing_duration(): + workflow = make_workflow() + state = run_turn( + workflow, + {"session_id": "issue4-onset", "profile": {}}, + "昨天开始喉咙痛", + ) + assert state["profile"]["duration"] == "1天" + assert "喉咙痛" in state["profile"]["symptoms"] + + +def test_issue4_short_colloquial_symptom_messages(): + workflow = make_workflow() + headache = run_turn( + workflow, {"session_id": "issue4-headache", "profile": {}}, "头疼" + ) + assert "头疼" in headache["profile"]["symptoms"] + + tired = run_turn( + workflow, + {"session_id": "issue4-tired", "profile": {}}, + "最近总觉得累,睡眠也不好", + ) + assert "累" in tired["profile"]["symptoms"] + assert "睡眠不好" in tired["profile"]["symptoms"] + + +def test_issue4_colloquial_variants_and_temperature_spellings(): + workflow = make_workflow() + state = run_turn( + workflow, + {"session_id": "issue4-variants", "profile": {}}, + "我发烧了,体温38.5℃,嗓子疼", + ) + profile = state["profile"] + assert "发烧" in profile["symptoms"] + assert "嗓子疼" in profile["symptoms"] + assert profile["temperature"] == "38.5度" + + state = workflow.extract_profile( + {"normalized_message": "我有高血压", "profile": {}} + ) + assert state["profile"]["history"] == "高血压" + + +def test_issue4_negated_or_third_party_symptoms_still_excluded(): + workflow = make_workflow() + negated = run_turn( + workflow, + {"session_id": "issue4-negated", "profile": {}}, + "我没有发烧,也没有咳嗽", + ) + assert negated["profile"]["symptoms"] == [] + + third_party = run_turn( + workflow, + {"session_id": "issue4-third-party", "profile": {}}, + "我妈妈发烧咳嗽,我想问问怎么办", + ) + assert third_party["profile"]["symptoms"] == [] + + coordinated = workflow.extract_profile( + { + "normalized_message": "咳嗽,已经三天,没有胸痛或呼吸困难", + "profile": {"symptoms": [], "associated_symptoms": []}, + } + ) + assert coordinated["profile"]["symptoms"] == ["咳嗽"] + + denied_history = workflow.extract_profile( + {"normalized_message": "否认有糖尿病", "profile": {}} + ) + assert denied_history["profile"].get("history") != "糖尿病" + + +def test_issue4_duration_guards_still_hold(): + workflow = make_workflow() + for message in ("我32岁,咳嗽不是三天", "我2026年做过体检,最近咳嗽"): + state = workflow.extract_profile( + { + "normalized_message": message, + "profile": {"symptoms": [], "associated_symptoms": []}, + } + ) + assert "duration" not in state["profile"] + + +def test_issue4_temperature_in_external_summary(): + workflow = make_workflow() + outbound = workflow._external_query_summary( + { + "intent": "disease", + "profile": { + "age": 25, + "chief_complaint": "发烧", + "duration": "3天", + "temperature": "38.5度", + }, + "risk_flags": [], + "citations": [], + } + ) + assert "体温:38.5度" in outbound + assert "持续时间:3天" in outbound diff --git a/backend/tests/test_session_history.py b/backend/tests/test_session_history.py new file mode 100644 index 0000000..2ca78a7 --- /dev/null +++ b/backend/tests/test_session_history.py @@ -0,0 +1,159 @@ +"""Session history (issue #3): transcript persistence and listing. + +Covers: multi-turn messages stored and restored via GET, the session list +being newest-first and owner-scoped, cross-user reads returning 404, +expired sessions excluded from the list, and idempotent replay not +duplicating transcript entries. +""" + +from __future__ import annotations + +from types import SimpleNamespace + +import pytest +from fastapi.testclient import TestClient + +import app.main as main_module +from app.main import AppServices, app +from app.store import SessionStore + + +@pytest.fixture() +def services(tmp_path, monkeypatch): + """A fresh, isolated AppServices (fresh store + fresh auth DB).""" + monkeypatch.setenv("MEDGUIDE_AUTH_DB_PATH", str(tmp_path / "auth.sqlite3")) + current = AppServices() + monkeypatch.setattr(main_module, "get_services", lambda: current) + yield current + current.close() + + +@pytest.fixture() +def client(services): + with TestClient(app, base_url="https://testserver") as test_client: + yield test_client + + +def _register(client: TestClient, username: str) -> None: + response = client.post( + "/api/auth/register", + json={"username": username, "password": "Correct-Horse-42"}, + ) + assert response.status_code == 201 + + +def _chat(client: TestClient, session_id: str, message: str, request_id: str): + response = client.post( + "/api/chat", + json={"session_id": session_id, "message": message, "request_id": request_id}, + ) + assert response.status_code == 200 + return response.json() + + +def test_multi_turn_messages_persist_and_restore_via_get(client: TestClient) -> None: + # Issue #6 requires a session for /api/sessions in every mode. + _register(client, "history_multi_turn") + session_id = client.post("/api/sessions").json()["session_id"] + first = _chat(client, session_id, "我32岁,咳嗽持续3天", "turn-history-0001") + second = _chat(client, session_id, "还伴随发热38度", "turn-history-0002") + + state = client.get(f"/api/sessions/{session_id}").json() + assert state["turn_count"] == 2 + messages = state["messages"] + assert [item["role"] for item in messages] == ["user", "assistant", "user", "assistant"] + assert messages[0]["content"] == "我32岁,咳嗽持续3天" + assert messages[2]["content"] == "还伴随发热38度" + assert messages[1]["content"] == first["answer"] + assert messages[3]["content"] == second["answer"] + assert messages[1]["response_id"] == first["response_id"] + assert messages[3]["response_id"] == second["response_id"] + assert all(item.get("timestamp") for item in messages) + + +def test_session_list_is_newest_first_and_owner_scoped(client: TestClient) -> None: + alice = client + _register(alice, "history_alice") + first_id = alice.post("/api/sessions").json()["session_id"] + _chat(alice, first_id, "我咳嗽三天", "turn-list-a-0001") + second_id = alice.post("/api/sessions").json()["session_id"] + _chat(alice, second_id, "我想查布洛芬库存", "turn-list-a-0002") + + bob = TestClient(app, base_url="https://testserver") + try: + _register(bob, "history_bob") + other_id = bob.post("/api/sessions").json()["session_id"] + _chat(bob, other_id, "我头痛", "turn-list-b-0001") + + listed = alice.get("/api/sessions").json() + assert listed["complete"] is True + sessions = listed["sessions"] + assert [item["session_id"] for item in sessions] == [second_id, first_id] + assert sessions[0]["title"] == "我想查布洛芬库存" + assert sessions[1]["title"] == "我咳嗽三天" + assert sessions[0]["turn_count"] == 1 + assert all(item["session_id"] != other_id for item in sessions) + + bob_listed = bob.get("/api/sessions").json() + assert [item["session_id"] for item in bob_listed["sessions"]] == [other_id] + finally: + bob.close() + + +def test_cross_user_session_read_returns_404(client: TestClient) -> None: + _register(client, "history_owner") + session_id = client.post("/api/sessions").json()["session_id"] + _chat(client, session_id, "我咳嗽三天", "turn-cross-0001") + + stranger = TestClient(app, base_url="https://testserver") + try: + _register(stranger, "history_stranger") + assert stranger.get(f"/api/sessions/{session_id}").status_code == 404 + assert stranger.get("/api/sessions").json()["sessions"] == [] + finally: + stranger.close() + + +def test_idempotent_replay_does_not_duplicate_messages(client: TestClient) -> None: + # Issue #6 requires a session for /api/sessions in every mode. + _register(client, "history_replay") + session_id = client.post("/api/sessions").json()["session_id"] + request = { + "session_id": session_id, + "message": "我32岁,咳嗽持续3天", + "request_id": "turn-replay-0001", + } + first = client.post("/api/chat", json=request) + replay = client.post("/api/chat", json=request) + assert first.status_code == replay.status_code == 200 + assert replay.json()["response_id"] == first.json()["response_id"] + + state = client.get(f"/api/sessions/{session_id}").json() + assert state["turn_count"] == 1 + assert len(state["messages"]) == 2 + assert [item["role"] for item in state["messages"]] == ["user", "assistant"] + + +def test_new_session_public_state_has_empty_messages() -> None: + store = SessionStore(mode="test") + state = store.create(owner_id="user:someone") + assert store.public(state)["messages"] == [] + assert store.list_sessions("user:someone")[0]["title"] == "新的健康咨询" + + +def test_expired_sessions_are_excluded_from_list() -> None: + now = [1_000.0] + store = SessionStore(mode="test", ttl_seconds=60, clock=lambda: now[0]) + old_id = store.create(owner_id="user:alice")["session_id"] + now[0] = 1_050.0 + new_id = store.create(owner_id="user:alice")["session_id"] + now[0] = 1_070.0 + assert store.get(old_id) is None + listed = store.list_sessions("user:alice") + assert [item["session_id"] for item in listed] == [new_id] + + +def test_redis_backend_list_is_empty_and_marked_incomplete() -> None: + store = SessionStore(backend=SimpleNamespace(), mode="production") + assert store.listing_complete is False + assert store.list_sessions("user:alice") == [] diff --git a/backend/tests/test_workflow_and_safety_regressions.py b/backend/tests/test_workflow_and_safety_regressions.py index ac12062..3c8ec73 100644 --- a/backend/tests/test_workflow_and_safety_regressions.py +++ b/backend/tests/test_workflow_and_safety_regressions.py @@ -24,7 +24,13 @@ def make_workflow(*, answerer: OpenAIAnswerer | None = None) -> MedGuideWorkflow return MedGuideWorkflow(HybridRetriever(), ReadOnlySQLGuard(), SafetyEngine(), answerer) -def test_high_risk_is_sticky_across_follow_up_turns() -> None: +def test_high_risk_is_reevaluated_on_follow_up_turns() -> None: + # Behaviour change for issue #5: a high-risk turn used to lock the + # whole session in emergency mode, so every follow-up -- even an + # unrelated question -- returned the same emergency text with no + # retrieval. Risk is now re-evaluated from each message; the earlier + # high-risk turn is kept in ``risk_history`` and surfaced as a brief + # reminder instead of locking the session. workflow = make_workflow() first = workflow.run( { @@ -37,10 +43,10 @@ def test_high_risk_is_sticky_across_follow_up_turns() -> None: second = workflow.run(first) assert first["risk_level"] == "high" - assert second["risk_level"] == "high" - assert "胸痛或胸部压榨感" in second["risk_flags"] - assert second["citations"] == [] - assert "急诊" in second["response"] + assert second["risk_level"] == "low" + assert not second["response"].startswith("当前描述包含需要优先排除的风险信号") + assert "再次出现" in second["response"] + assert [entry["level"] for entry in second["risk_history"]].count("high") == 1 class _FakeCompletions: diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 1ef03dc..856dd58 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -53,6 +53,13 @@ type Citation = { source_url?: string; }; +type StoredMessage = { + role: "user" | "assistant"; + content: string; + response_id?: string; + timestamp?: string; +}; + type SessionState = { session_id: string; turn_count: number; @@ -62,6 +69,8 @@ type SessionState = { intent: string; next_question: string | null; mode: string; + /** Full turn transcript, oldest first; absent on older API versions. */ + messages?: StoredMessage[]; /** Optional capability fields supplied by newer API versions. */ environment?: string; network_enabled?: boolean; @@ -73,6 +82,15 @@ type SessionState = { summary?: string; }; +type SessionListItem = { + session_id: string; + title: string; + summary: string; + turn_count: number; + updated_at: string | null; + risk_level?: RiskLevel | null; +}; + type StructuredResult = { intent: string; sql: string; @@ -246,6 +264,7 @@ function App() { const [authBootstrapError, setAuthBootstrapError] = useState(null); const [logoutPending, setLogoutPending] = useState(false); const [session, setSession] = useState(null); + const [sessions, setSessions] = useState([]); const [messages, setMessages] = useState([initialMessage]); const [draft, setDraft] = useState(""); const [loading, setLoading] = useState(false); @@ -403,6 +422,7 @@ function App() { committedResponseIdsRef.current.clear(); sessionCreateKeyRef.current = null; setSession(null); + setSessions([]); setSessionStatus("idle"); setMessages([{ ...initialMessage, timestamp: Date.now() }]); setDraft(""); @@ -436,7 +456,117 @@ function App() { setAuthBootstrapError(null); const createKey = createRequestId("session"); sessionCreateKeyRef.current = createKey; - startSession(createKey); + void loadSessionHistory(); + } + + /** Best-effort refresh of the left-rail history list; never blocks chat. */ + async function refreshSessionList() { + try { + const response = await apiFetch("/api/sessions"); + if (!response.ok) return; + const body = (await response.json()) as { sessions?: SessionListItem[] }; + if (Array.isArray(body.sessions)) setSessions(body.sessions); + } catch { + // History is a convenience view; a failed refresh must not surface + // as a chat error. + } + } + + /** + * On login/refresh, restore the newest session that already has messages + * instead of opening an empty one. A fresh session is created only when + * the user has no history yet. The list endpoint — not localStorage — + * is the source of truth for which sessions exist. + */ + async function loadSessionHistory() { + const generation = generationRef.current; + setSessionStatus("creating"); + try { + const response = await apiFetch("/api/sessions"); + await ensureResponseOk(response); + const body = (await response.json()) as { sessions?: SessionListItem[] }; + const listed = Array.isArray(body.sessions) ? body.sessions : []; + if (generationRef.current !== generation) return; + setSessions(listed); + const latest = listed.find((item) => item.turn_count > 0); + if (latest) { + await restoreSession(latest.session_id); + return; + } + } catch (requestError) { + if (generationRef.current !== generation) return; + if (requestError instanceof HttpResponseError && requestError.status === 401) { + returnToAuthentication("登录状态已过期,请重新登录。"); + return; + } + // Fall through to a fresh session when history cannot be read. + } + startSession(sessionCreateKeyRef.current || createRequestId("session")); + } + + function applyRestoredSession(state: SessionState) { + activeSessionIdRef.current = state.session_id; + committedResponseIdsRef.current.clear(); + const restored: Message[] = [{ ...initialMessage, timestamp: Date.now() }]; + for (const [index, item] of (state.messages || []).entries()) { + const parsed = item.timestamp ? Date.parse(item.timestamp) : Number.NaN; + const message: Message = { + id: item.response_id || `restored-${index}`, + role: item.role, + content: item.content, + timestamp: Number.isNaN(parsed) ? Date.now() : parsed, + sessionId: state.session_id, + }; + if (item.role === "assistant" && item.response_id) { + committedResponseIdsRef.current.add(item.response_id); + } + restored.push(message); + } + setSession(state); + setMessages(restored); + // Per-message citations are not stored server-side, so restored + // answers link no references; the live turn's citations still apply. + setCitations([]); + setSelectedCitationMessageId(null); + setStructuredResult(null); + setEvents([]); + setFeedbackSent({}); + setFeedbackPending({}); + } + + async function restoreSession(sessionId: string) { + const generation = ++generationRef.current; + sessionRequestRef.current?.abort(); + chatRequestRef.current?.abort(); + chatRequestRef.current = null; + pendingRetryRef.current = null; + setSessionStatus("creating"); + setLoading(false); + setError(null); + const controller = new AbortController(); + sessionRequestRef.current = controller; + try { + const response = await apiFetch(`/api/sessions/${encodeURIComponent(sessionId)}`, { + signal: controller.signal, + }); + await ensureResponseOk(response); + const body = (await response.json()) as SessionState; + if (!body.session_id || !requestIsCurrent(generation, controller)) return; + applyRestoredSession(body); + setSessionStatus("ready"); + } catch (requestError) { + if (isAbortError(requestError) || !requestIsCurrent(generation, controller)) return; + if (requestError instanceof HttpResponseError && requestError.status === 401) { + returnToAuthentication("登录状态已过期,请重新登录。"); + return; + } + activeSessionIdRef.current = null; + setSession(null); + setSessionStatus("error"); + setError(requestError instanceof HttpResponseError ? formatHttpError(requestError) : "整理服务暂不可用,请稍后重试。"); + } finally { + if (sessionRequestRef.current === controller) sessionRequestRef.current = null; + } } function restoreAuthentication() { @@ -578,6 +708,7 @@ function App() { activeSessionIdRef.current = body.state.session_id; setSession(body.state); setSessionStatus("ready"); + void refreshSessionList(); } catch (requestError) { if (isAbortError(requestError) || !requestIsCurrent(generation, controller)) return; if (requestError instanceof HttpResponseError && requestError.status === 401) { @@ -773,6 +904,8 @@ function App() { latency: body.latency_ms, sessionId: body.state.session_id, }); + // The turn changed this session's title and turn count in the history. + void refreshSessionList(); } function newConversation() { @@ -922,12 +1055,25 @@ function App() { -
这次对话
+
历史对话
- + {sessions.length === 0 ? ( + + ) : ( + sessions.map((item) => ( + + )) + )}
如何描述问题 @@ -1025,7 +1171,7 @@ function App() {
{riskAssessed ? "随补充信息重新筛查" : "等待首次描述"}
- {isWelcome ?

聊之前,可以想一想

  1. 01
    最在意的感受

    哪里不舒服?与平时有什么不同?

  2. 02
    发生的时间

    什么时候开始,有没有变得更明显?

  3. 03
    你想弄清的事

    用药、检查,还是该去哪个科室?

:
已提供的信息

已经了解的情况

{session?.summary &&
整理摘要

{session.summary}

}{session?.next_question &&

还可以补充{session.next_question}

}
} + {isWelcome ?

聊之前,可以想一想

  1. 01
    最在意的感受

    哪里不舒服?与平时有什么不同?

  2. 02
    发生的时间

    什么时候开始,有没有变得更明显?

  3. 03
    你想弄清的事

    用药、检查,还是该去哪个科室?

:
已提供的信息

已经了解的情况

{session?.summary &&
整理摘要

{session.summary}

}{session?.next_question &&

还可以补充{session.next_question}

}
} {!isWelcome &&
本次整理{session?.workflow_version ? ` · ${session.workflow_version}` : ""}

处理进度

{events.length || loading ?
{buildWorkflowStages(events, risk, session?.intent, loading).map((stage, index) =>
{stage.status === "completed" ? : index + 1}
{stage.label}{stage.detail && {stage.detail}}
{stage.status === "completed" ? "完成" : stage.status === "skipped" ? "跳过" : stage.status === "running" ? "进行中" : "待处理"}
)}
:

回答已完成,未返回详细流程。

}
} diff --git a/frontend/src/styles.css b/frontend/src/styles.css index 2523191..3f9cb9e 100644 --- a/frontend/src/styles.css +++ b/frontend/src/styles.css @@ -139,6 +139,7 @@ button.starter-prompt:hover:not(:disabled) { border-color:#a1cbd0; background:#f .conversation-list { display:grid; gap:4px; } .conversation-item { display:flex; align-items:center; gap:8px; width:100%; padding:11px 8px; color:var(--ink-800); text-align:left; background:var(--teal-050); border:1px solid #d0e5e8; border-radius:7px; } .conversation-item:hover { background:#e8f3f5; } +.conversation-item.active { background:#e8f3f5; border-color:#b6dadd; } .conversation-icon { display:grid; place-items:center; flex-shrink:0; width:24px; color:var(--teal-700); } .conversation-copy { display:grid; gap:5px; min-width:0; } .conversation-copy strong { overflow:hidden; font-size:12px; font-weight:500; text-overflow:ellipsis; white-space:nowrap; }