From 32ed5d1a9d79ec3a1f27230bd95975cf8ca533b1 Mon Sep 17 00:00:00 2001 From: Zhenxian Liang Date: Mon, 16 Nov 2026 12:45:15 +0800 Subject: [PATCH 1/7] Fix #9: low-priority polish collection (21 items) Frontend: expired-session 409 message, recovery-path error handling, drop dead streaming state (cancel SSE reader on final), empty structured-result state, drop dead preview branch and unused ScenicAtmosphere assets, noscript placeholder + alert toast, fetch timeouts incl. logout, /api proxy for vite preview, workflow-progress states, date divider from first user message, username truncation. Backend: LangGraph node timing, row-truncation totals, feedback comment retention + commented counting, safety false positives for pure questions and resolved symptoms, local network_enabled, test embedding_model name, intent tie-break priority, department whitelist 5 -> 14, CORS '*' fails fast at startup. Add backend/tests/test_low_priority.py (42 tests) and 2 frontend workflow-progress tests. Closes zhengdaodeguL/MedGuide#9. --- backend/app/infra.py | 21 ++- backend/app/main.py | 8 +- backend/app/metrics.py | 24 ++- backend/app/retrieval.py | 20 ++- backend/app/safety.py | 53 ++++-- backend/app/sql_guard.py | 9 +- backend/app/store.py | 2 +- backend/app/workflow.py | 10 +- ...test_deployment_and_session_regressions.py | 5 +- backend/tests/test_local_mode.py | 4 +- backend/tests/test_low_priority.py | 168 ++++++++++++++++++ backend/tests/test_redis_atomicity.py | 30 +++- frontend/index.html | 3 +- frontend/src/App.tsx | 115 +++++++++--- frontend/src/styles.css | 5 +- frontend/src/workflow-progress.ts | 9 +- frontend/tests/workflow-progress.test.mjs | 28 +++ frontend/vite.config.ts | 22 ++- 18 files changed, 461 insertions(+), 75 deletions(-) create mode 100644 backend/tests/test_low_priority.py diff --git a/backend/app/infra.py b/backend/app/infra.py index 050e908..a791435 100644 --- a/backend/app/infra.py +++ b/backend/app/infra.py @@ -139,19 +139,25 @@ class RedisSessionAdapter: _UPSERT_FEEDBACK_SCRIPT = """ local previous = redis.call('HGET', KEYS[1], ARGV[1]) +local stored_comment = redis.call('HGET', KEYS[1], ARGV[1] .. ':commented') +local comment_recorded = 0 +if ARGV[3] == '1' and stored_comment ~= ARGV[5] then + redis.call('HSET', KEYS[1], ARGV[1] .. ':commented', ARGV[5]) + if not stored_comment then + redis.call('HINCRBY', KEYS[2], 'feedback_commented', 1) + end + comment_recorded = 1 +end if previous == ARGV[2] then redis.call('EXPIRE', KEYS[1], ARGV[4]) redis.call('EXPIRE', KEYS[2], ARGV[4]) - return 0 + return comment_recorded end if previous == 'up' or previous == 'down' then redis.call('HINCRBY', KEYS[2], 'feedback_' .. previous, -1) end redis.call('HSET', KEYS[1], ARGV[1], ARGV[2]) redis.call('HINCRBY', KEYS[2], 'feedback_' .. ARGV[2], 1) -if ARGV[3] == '1' and not previous then - redis.call('HINCRBY', KEYS[2], 'feedback_commented', 1) -end redis.call('EXPIRE', KEYS[1], ARGV[4]) redis.call('EXPIRE', KEYS[2], ARGV[4]) return 1 @@ -542,6 +548,12 @@ def upsert_feedback( if not callable(evaluator): return None key = hashlib.sha256(f"{session_id}\x00{message_id}".encode("utf-8")).hexdigest() + # Only a hash of the comment reaches the metrics store, so a + # resubmitted rating with a new comment still counts as a change + # without storing user text in the metrics hash. + comment_hash = ( + hashlib.sha256(comment.encode("utf-8")).hexdigest()[:16] if comment else "" + ) changed = evaluator( self._UPSERT_FEEDBACK_SCRIPT, 2, @@ -551,6 +563,7 @@ def upsert_feedback( rating, "1" if comment else "0", self.ttl_seconds, + comment_hash, ) return bool(int(changed)) except Exception as exc: diff --git a/backend/app/main.py b/backend/app/main.py index 217a42a..c141894 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -489,9 +489,13 @@ def _cors_origins() -> list[str]: origins = [item.strip().rstrip("/") for item in raw.split(",") if item.strip()] # Credentials and wildcard origins are mutually exclusive. Treat a # wildcard as an explicit configuration error rather than silently - # downgrading browser security. + # downgrading browser security: failing startup is the only honest + # signal, otherwise an operator would believe CORS is open. if "*" in origins: - return [] + raise ValueError( + "MEDGUIDE_CORS_ORIGINS must not contain '*': wildcard origins cannot " + "be combined with credentials; list explicit origins instead." + ) return origins diff --git a/backend/app/metrics.py b/backend/app/metrics.py index d809a97..660db46 100644 --- a/backend/app/metrics.py +++ b/backend/app/metrics.py @@ -25,6 +25,8 @@ class MetricsStore: feedback_by_message: dict[str, Literal["up", "down"]] = field(default_factory=dict) backend: Any | None = field(default=None, repr=False, compare=False) _recorded_responses: set[str] = field(default_factory=set, repr=False) + _commented_keys: set[str] = field(default_factory=set, repr=False) + _feedback_comments: dict[str, str] = field(default_factory=dict, repr=False) _lock: threading.Lock = field(default_factory=threading.Lock, repr=False) def record(self, state: WorkflowState) -> None: @@ -94,18 +96,34 @@ def add_feedback( with self._lock: previous: str | None = None feedback_key = f"{session_id}:{message_id}" if session_id and message_id else message_id + comment_recorded = False + if comment: + if feedback_key: + # "commented" counts messages that carry a comment, not + # feedback submissions: a later comment on the same + # message is stored, but the message is counted once. + # The latest comment text is kept so a resubmitted + # rating with a new comment is a real change, not a + # silent drop. + if feedback_key not in self._commented_keys: + self._commented_keys.add(feedback_key) + self.feedback["commented"] += 1 + if self._feedback_comments.get(feedback_key) != comment: + self._feedback_comments[feedback_key] = comment + comment_recorded = True + else: + self.feedback["commented"] += 1 + comment_recorded = True if feedback_key: previous = self.feedback_by_message.get(feedback_key) if previous == rating: - return False + return comment_recorded if previous: self.feedback[previous] -= 1 if self.feedback[previous] <= 0: self.feedback.pop(previous, None) self.feedback_by_message[feedback_key] = rating self.feedback[rating] += 1 - if comment and previous is None: - self.feedback["commented"] += 1 return True def snapshot(self) -> dict: diff --git a/backend/app/retrieval.py b/backend/app/retrieval.py index a33dc38..9815279 100644 --- a/backend/app/retrieval.py +++ b/backend/app/retrieval.py @@ -32,14 +32,25 @@ class IntentRouter: "structured": ("库存", "有货", "排班", "号源", "价格", "多少钱", "费用"), } + # Score ties are broken by an explicit priority instead of dict order: + # an explicit "which department" question wins over a bare symptom + # mention ("咳嗽三天应该挂什么科?" is a department question), while a + # symptom plus a drug mention ("发热吃药") stays a disease question. + _INTENT_PRIORITY: tuple[Intent, ...] = ("department", "disease", "drug", "exam", "faq") + 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"} - best = max(scores, key=scores.get) - return best if scores[best] else "unknown" + best: Intent = "unknown" + best_score = 0 + for intent in self._INTENT_PRIORITY: + if scores[intent] > best_score: + best = intent + best_score = scores[intent] + return best if best_score else "unknown" def rewrite(self, text: str, profile: PatientProfile | None = None) -> str: profile = profile or {} @@ -351,14 +362,15 @@ def health(self) -> dict[str, str | int]: if self.milvus is not None and getattr(self.milvus, "ready", False) else ("milvus-unavailable" if self.remote_required else "disabled") ) - provider_name = str(getattr(self.embedding_provider.spec, "provider", "")) indexed_chunks = self.bm25_index.chunks if self.bm25_index is not None else [] return { "documents": len({chunk.document_id for chunk in indexed_chunks}), "chunks": len(indexed_chunks), "vector_store": vector_store, "keyword_store": "bm25" if self.bm25_index is not None else "bm25-unavailable", - "embedding_model": self.embedding_provider.spec.model if provider_name != "local" else "not-configured", + # The local hash provider is a real, working provider; report its + # model instead of claiming the embedding is not configured. + "embedding_model": self.embedding_provider.spec.model, "embedding_version": self.embedding_provider.spec.version, } diff --git a/backend/app/safety.py b/backend/app/safety.py index fa9a4e7..942d467 100644 --- a/backend/app/safety.py +++ b/backend/app/safety.py @@ -66,7 +66,12 @@ class SafetyEngine: "?", "?", ) - _HELP_SEEKING = ( + # Action-seeking cues: asking what to do about a symptom implies the + # symptom is current, so they override a trailing question mark. Pure + # severity questions ("严重吗", "危险吗", "要紧吗") are deliberately NOT + # in this list: asking whether chest pain is serious does not assert + # that the patient has chest pain right now. + _ACTION_SEEKING = ( "怎么办", "如何处理", "需要就医", @@ -74,10 +79,8 @@ class SafetyEngine: "要去医院", "该去医院", "该挂什么", - "严重吗", - "危险吗", - "要紧吗", ) + _HELP_SEEKING = _ACTION_SEEKING _THIRD_PARTY = re.compile( r"朋友|家人|父亲|母亲|爸爸|妈妈|儿子|女儿|丈夫|妻子|老公|老婆|同事|邻居|" r"男朋友|女朋友|他人|他们|她们|(?:他|她)(?=(?:也|都|又|还|刚|今天|昨天|" @@ -105,6 +108,25 @@ class SafetyEngine: r"(?:明显|完全)?" r"(?:缓解|消失|好转|恢复)" ) + # Colloquial resolution: "昨天胸痛,今天好了" / "胸痛不疼了" / "好多了". + # No 已经/已 prefix is required, so this also covers "今天好了". + _RESOLVED_COLLOQUIAL_AFTER = re.compile( + r"^(?:[,,。;;]\s*(?:但是|但)?\s*(?:我|本人|患者|症状)?\s*(?:目前|现在|如今|今天|昨天)?)?" + r"(?:已经|已|现已)?(?:好了|不疼了|不痛了|好多了|没事了)" + ) + _RECURRENCE_AFTER = re.compile( + r"(?:复发|加重|未完全(?:缓解|消失|好转|恢复)|" + r"(?:又|再次|重新)[^,,。;;!?!?]{0,12}(?:出现|发作|疼|痛|闷|喘|呼吸|无力|出血|黑便))" + ) + + @classmethod + def _is_resolved_after(cls, after: str) -> bool: + """Whether the text after a symptom says it has resolved (and not relapsed).""" + for pattern in (cls._RESOLVED_AFTER, cls._RESOLVED_COLLOQUIAL_AFTER): + match = pattern.match(after) + if match and not cls._RECURRENCE_AFTER.search(after[match.end():]): + return True + return False _CLAUSE_BREAK = re.compile(r"[,,。;;!?!?]|但是|但|可是|然而|却") _DIRECT_NEGATION = re.compile( r"(?:没有|无|否认|不曾|从未|不是|并非|未见|没|不再|未|不伴有|不伴随)" @@ -155,12 +177,7 @@ def _asserted(cls, text: str, pattern: str) -> bool: continue if cls._RESOLVED_BEFORE.search(clause_before): continue - resolved = cls._RESOLVED_AFTER.match(after) - if resolved and not re.search( - r"(?:复发|加重|未完全(?:缓解|消失|好转|恢复)|" - r"(?:又|再次|重新)[^,,。;;!?!?]{0,12}(?:出现|发作|疼|痛|闷|喘|呼吸|无力|出血|黑便))", - after[resolved.end():], - ): + if cls._is_resolved_after(after): continue if re.match(r"(?:不再|已经没有|已没有|未见|不存在)", clause_after): continue @@ -186,13 +203,13 @@ def _asserted(cls, text: str, pattern: str) -> bool: knowledge_prefix = cls._KNOWLEDGE_PREFIX.search(clause_before) knowledge_suffix = cls._KNOWLEDGE_SUFFIX.fullmatch(clause_after) if (knowledge_prefix or (knowledge_suffix and not cls._PATIENT_MARKER.search(clause_before))) and not any( - marker in full_clause for marker in cls._HELP_SEEKING + marker in full_clause for marker in cls._ACTION_SEEKING ): continue is_question = any(marker in clause_after for marker in ("吗", "?", "?")) or any( clause_after.startswith(marker) for marker in cls._QUESTION if marker not in ("吗", "?", "?") ) - if is_question and not any(marker in full_clause for marker in cls._HELP_SEEKING): + if is_question and not any(marker in full_clause for marker in cls._ACTION_SEEKING): continue return True return False @@ -234,12 +251,18 @@ def screen(self, text: str, profile: PatientProfile | None = None) -> RiskAssess self._TEMPERATURE_NEGATION.search(clause_before) or re.match(r"(?:以下|以内|之下|不到)", clause_after) ) + # A trailing severity question ("39度严重吗") is a question about + # the number, not an assertion of a current 39° fever. Only an + # action-seeking cue ("怎么办") keeps it high-risk. is_question = bool( self._TEMPERATURE_QUESTION.search(clause_before) - or clause_after.startswith(("吗", "是否", "是不是", "有无", "有没有")) + or "吗" in clause_after + or "?" in clause_after + or "?" in clause_after + or clause_after.startswith(("是否", "是不是", "有无", "有没有")) or after.startswith(("?", "?")) - ) and not any(marker in f"{clause_before}{match.group(0)}{clause_after}" for marker in self._HELP_SEEKING) - if value >= 39 and not is_negated and not is_question: + ) and not any(marker in f"{clause_before}{match.group(0)}{clause_after}" for marker in self._ACTION_SEEKING) + if value >= 39 and not is_negated and not is_question and not self._is_resolved_after(after): flags.append("高热伴精神状态异常") break diff --git a/backend/app/sql_guard.py b/backend/app/sql_guard.py index 6ca551a..a5cb08d 100644 --- a/backend/app/sql_guard.py +++ b/backend/app/sql_guard.py @@ -603,7 +603,14 @@ def _extract_term(text: str, markers: tuple[str, ...]) -> str: @staticmethod def _extract_department(text: str) -> str: - for department in ("呼吸内科", "消化内科", "全科医学科", "心内科", "皮肤科"): + # Common hospital departments. The sample schedules only carry a + # few of them; an unknown department still returns no rows rather + # than a misleading "please specify" block. + for department in ( + "呼吸内科", "消化内科", "全科医学科", "心内科", "皮肤科", + "眼科", "耳鼻喉科", "口腔科", "骨科", "神经内科", "神经外科", + "儿科", "妇产科", "泌尿外科", + ): if department in text: return department return "" diff --git a/backend/app/store.py b/backend/app/store.py index 52d06b0..bc62c46 100644 --- a/backend/app/store.py +++ b/backend/app/store.py @@ -381,6 +381,6 @@ def public(self, state: WorkflowState) -> dict: "answer_source": state.get("answer_source"), "safety_blocked": bool(state.get("safety_blocked", False)), "environment": self.mode if self.mode in {"offline", "test", "local"} else "production", - "network_enabled": self.mode not in {"offline", "test"}, + "network_enabled": self.mode not in {"offline", "test", "local"}, "updated_at": state.get("updated_at"), } diff --git a/backend/app/workflow.py b/backend/app/workflow.py index 5dbcc68..220e68d 100644 --- a/backend/app/workflow.py +++ b/backend/app/workflow.py @@ -260,6 +260,7 @@ def run( compiled_result = dict(state) completed: dict[str, dict[str, Any]] = {} path: list[str] = [] + node_started = time.perf_counter() if hasattr(self.graph, "stream"): for update in self.graph.stream(state, stream_mode="updates"): for node, node_update in update.items(): @@ -273,11 +274,16 @@ def run( "node": node, "label": NODE_LABELS[node], "status": "completed", - "elapsed_ms": 0.0, + # Time between node updates approximates the + # node's own execution time on this path. + "elapsed_ms": round((time.perf_counter() - node_started) * 1000, 2), } + node_started = time.perf_counter() else: # A small compatibility path keeps test doubles and older # compiled graphs usable while production uses stream(). + # A single invoke() exposes no per-node boundary, so its + # events keep elapsed_ms 0.0 instead of a fabricated split. compiled_result.update(dict(self.graph.invoke(state))) path = list(WORKFLOW_ORDER) completed = { @@ -760,6 +766,8 @@ def _next_question(profile: PatientProfile, risk_level: str, text: str) -> str | def _format_rows(result: dict[str, Any]) -> str: rows = result.get("rows", []) lines = ["已通过只读白名单查询到以下数据:"] + if len(rows) > 5: + lines.append(f"共 {len(rows)} 行,仅展示前 5 行:") for row in rows[:5]: lines.append(" · " + " / ".join(f"{key}: {value}" for key, value in row.items())) return "\n".join(lines) + "\n\n结果来自当前已连接的数据源;实际库存、排班和价格请以医院实时系统为准。" diff --git a/backend/tests/test_deployment_and_session_regressions.py b/backend/tests/test_deployment_and_session_regressions.py index 45ba81d..ed87ffb 100644 --- a/backend/tests/test_deployment_and_session_regressions.py +++ b/backend/tests/test_deployment_and_session_regressions.py @@ -33,8 +33,11 @@ def test_cors_defaults_to_same_origin_and_requires_explicit_allowlist(monkeypatc "https://admin.medguide.example", ] + # A wildcard must fail startup loudly instead of silently disabling + # CORS: an operator would otherwise believe cross-origin access is open. monkeypatch.setenv("MEDGUIDE_CORS_ORIGINS", "*") - assert main_module._cors_origins() == [] + with pytest.raises(ValueError, match="must not contain"): + main_module._cors_origins() def test_production_requires_secure_cookie_and_https_pair(monkeypatch) -> None: diff --git a/backend/tests/test_local_mode.py b/backend/tests/test_local_mode.py index fd0aa06..ba8c878 100644 --- a/backend/tests/test_local_mode.py +++ b/backend/tests/test_local_mode.py @@ -274,7 +274,9 @@ def test_local_generated_answer_keeps_citations_safety_and_runtime_identity(loca assert state["answer_source"] == "local-grounded" and state["citations"] assert not state["safety_blocked"] public = current.store.public(state) - assert public["environment"] == "local" and public["network_enabled"] + # Local mode is self-contained (local model, local knowledge, no remote + # services): it must not claim network access is enabled. + assert public["environment"] == "local" and public["network_enabled"] is False assert public["answer_source"] == "local-grounded" current.answerer.text = "你已经确诊肺炎,请立即停药。" reviewed = current.workflow.run({"session_id": "unsafe", "user_message": "咳嗽三天", "profile": {}}) diff --git a/backend/tests/test_low_priority.py b/backend/tests/test_low_priority.py new file mode 100644 index 0000000..ceb2626 --- /dev/null +++ b/backend/tests/test_low_priority.py @@ -0,0 +1,168 @@ +"""Regression tests for MedGuide issue #9 (low-priority polish collection).""" + +from __future__ import annotations + +import time + +import pytest + +from app.metrics import MetricsStore +from app.retrieval import HybridRetriever, IntentRouter +from app.safety import SafetyEngine +from app.sql_guard import ReadOnlySQLGuard +from app.store import SessionStore +from app.workflow import MedGuideWorkflow + + +def make_workflow() -> MedGuideWorkflow: + return MedGuideWorkflow(HybridRetriever(), ReadOnlySQLGuard(), SafetyEngine()) + + +# 13. LangGraph path records real per-node timings. +class _SleepingGraph: + def stream(self, state, stream_mode="updates"): + yield {"normalize": {"normalized_message": state.get("user_message", "")}} + time.sleep(0.02) + yield {"extract_profile": {"profile": {}}} + + +def test_langgraph_stream_events_carry_real_elapsed_ms() -> None: + workflow = make_workflow() + workflow.graph = _SleepingGraph() + result = workflow.run({"session_id": "timing", "user_message": "咳嗽", "profile": {}}) + events = {event["node"]: event for event in result["events"]} + assert events["normalize"]["status"] == "completed" + assert events["extract_profile"]["status"] == "completed" + assert isinstance(events["extract_profile"]["elapsed_ms"], float) + assert events["extract_profile"]["elapsed_ms"] >= 10 + assert events["normalize"]["elapsed_ms"] >= 0 + + +# 14. Structured rows are truncated with a visible total. +def test_format_rows_notes_total_when_truncated() -> None: + text = MedGuideWorkflow._format_rows({"rows": [{"name": "布洛芬", "stock": 1}] * 7}) + assert "共 7 行" in text + assert "前 5 行" in text + assert text.count("布洛芬") == 5 + + +def test_format_rows_without_truncation_has_no_total_note() -> None: + text = MedGuideWorkflow._format_rows({"rows": [{"name": "布洛芬", "stock": 1}] * 5}) + assert "共" not in text + + +# 15. A comment is saved on a same-rating resubmission, and "commented" +# counts messages that carry a comment (once each). +def test_feedback_comment_saved_on_same_rating_resubmission() -> None: + metrics = MetricsStore() + assert metrics.add_feedback("up", "清楚", "m1", session_id="s") is True + # Same rating, new comment text: the comment is saved, so this changed. + assert metrics.add_feedback("up", "补充了一句", "m1", session_id="s") is True + # Same rating, identical comment: nothing changed. + assert metrics.add_feedback("up", "补充了一句", "m1", session_id="s") is False + assert metrics.snapshot()["feedback"].get("commented") == 1 + + +def test_feedback_comment_counted_when_rating_changes() -> None: + metrics = MetricsStore() + assert metrics.add_feedback("up", None, "m1", session_id="s") is True + # First comment on this message, attached to a rating change: it counts. + assert metrics.add_feedback("down", "不好", "m1", session_id="s") is True + snapshot = metrics.snapshot() + assert snapshot["feedback"].get("commented") == 1 + assert snapshot["feedback"].get("up", 0) == 0 + assert snapshot["feedback"].get("down") == 1 + # A second message with a comment counts separately. + assert metrics.add_feedback("up", "清楚", "m2", session_id="s") is True + assert metrics.snapshot()["feedback"].get("commented") == 2 + + +# 16. Pure questions and colloquial "resolved" wording are not high risk, +# while real emergencies still are. +@pytest.mark.parametrize( + "text", + ( + "39度严重吗", + "胸痛严重吗", + "胸痛危险吗", + "胸痛要紧吗", + "39度吗", + "昨天胸痛,今天好了", + "胸痛不疼了", + "昨天胸痛,今天好多了", + "昨天发烧39度,今天好了", + "胸痛严重吗,需要就医吗", + ), +) +def test_pure_questions_and_resolved_symptoms_are_not_high(text: str) -> None: + assert SafetyEngine().screen(text).level != "high", text + + +@pytest.mark.parametrize( + "text", + ( + "胸痛很严重", + "胸痛很严重怎么办", + "胸痛怎么办?", + "昨天胸痛,今天好了,但现在又疼", + "39度,怎么办", + "39度很严重", + "我现在胸痛怎么办", + "胸痛已经缓解,但现在再次胸痛", + "我胸痛,很严重吗?", + ), +) +def test_real_emergencies_stay_high(text: str) -> None: + assert SafetyEngine().screen(text).level == "high", text + + +# 17. Local mode does not claim network access. +def test_store_public_reports_no_network_in_local_mode() -> None: + assert SessionStore(mode="local").public({"session_id": "x"})["network_enabled"] is False + assert SessionStore(mode="offline").public({"session_id": "x"})["network_enabled"] is False + assert SessionStore(mode="test").public({"session_id": "x"})["network_enabled"] is False + assert SessionStore(mode="production").public({"session_id": "x"})["network_enabled"] is True + + +# 18. Test mode reports the real (hash) embedding model. +def test_ready_health_reports_real_embedding_model_in_test_mode() -> None: + assert HybridRetriever().health()["embedding_model"] == "sha256-token-hash" + + +# 19. Intent ties are broken by an explicit priority, not dict order. +@pytest.mark.parametrize( + "text,expected", + ( + ("发热吃药", "disease"), + ("咳嗽三天应该挂什么科?", "department"), + ("皮疹看什么科?", "department"), + ("布洛芬有什么副作用", "drug"), + ("头痛吃药", "disease"), + ), +) +def test_intent_tie_breaks_by_priority(text: str, expected: str) -> None: + assert IntentRouter().classify(text) == expected + + +# 20. Common departments are accepted for schedule queries. +@pytest.mark.parametrize( + "text", + ( + "眼科排班", + "耳鼻喉科排班", + "皮肤科排班", + "口腔科排班", + "骨科排班", + "神经内科排班", + "神经外科排班", + "儿科排班", + "妇产科排班", + "泌尿外科排班", + "眼科号源", + ), +) +def test_common_departments_are_accepted(text: str) -> None: + result = ReadOnlySQLGuard().from_natural_language(text) + assert result is not None + assert result.blocked is False + assert result.intent == "doctor_schedules" diff --git a/backend/tests/test_redis_atomicity.py b/backend/tests/test_redis_atomicity.py index c8774f3..a7fe043 100644 --- a/backend/tests/test_redis_atomicity.py +++ b/backend/tests/test_redis_atomicity.py @@ -112,20 +112,25 @@ def _release_request(self, keys, args): def _upsert_feedback(self, keys, args): feedback_key, metrics_key = keys - field, rating, commented, _ttl = args + field, rating, commented, _ttl, comment_hash = args feedback = self.hashes.setdefault(feedback_key, {}) metrics = self.hashes.setdefault(metrics_key, {}) previous = feedback.get(field) + stored_comment = feedback.get(f"{field}:commented") + comment_recorded = 0 + if commented == "1" and stored_comment != comment_hash: + feedback[f"{field}:commented"] = comment_hash + if not stored_comment: + metrics["feedback_commented"] = int(metrics.get("feedback_commented", 0)) + 1 + comment_recorded = 1 if previous == rating: - return 0 + return comment_recorded if previous in {"up", "down"}: old_key = f"feedback_{previous}" metrics[old_key] = int(metrics.get(old_key, 0)) - 1 feedback[field] = rating rating_key = f"feedback_{rating}" metrics[rating_key] = int(metrics.get(rating_key, 0)) + 1 - if commented == "1" and previous is None: - metrics["feedback_commented"] = int(metrics.get("feedback_commented", 0)) + 1 return 1 def _record_metrics(self, keys, args): @@ -300,6 +305,23 @@ def test_feedback_upsert_is_atomic_under_concurrent_duplicates_and_changes() -> assert metrics["feedback_down"] == 1 +def test_feedback_comment_counts_once_per_message_in_shared_store() -> None: + redis = _AtomicRedis() + adapter = RedisSessionAdapter(client=redis) + + # First comment on the message counts, even on a rating change. + assert adapter.upsert_feedback("session", "message", "up") is True + assert adapter.upsert_feedback("session", "message", "down", "不好") is True + # Same rating with a new comment: the comment is recorded (changed), + # but the message is still counted once in feedback_commented. + assert adapter.upsert_feedback("session", "message", "down", "还是不好") is True + assert adapter.upsert_feedback("session", "message", "down") is False + metrics = redis.hashes[adapter.metrics_key] + assert metrics["feedback_commented"] == 1 + assert metrics["feedback_down"] == 1 + assert metrics.get("feedback_up", 0) == 0 + + def test_shared_metrics_record_is_atomic_and_deduplicated_under_concurrency() -> None: redis = _AtomicRedis() adapter = RedisSessionAdapter(client=redis) diff --git a/frontend/index.html b/frontend/index.html index b043cea..b4a0169 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -9,7 +9,8 @@ MedGuide · 健康信息工作台 -
+ +

正在加载 MedGuide…

diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 1ef03dc..987ca6d 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -114,6 +114,34 @@ function apiFetch(path: string, init: RequestInit = {}) { return fetch(path, { ...init, credentials: "include" }); } +// Bounded fetch: without this a hung request (for example logout) waits +// forever. The caller's own signal is still honoured, and a timeout is +// reported as a plain error rather than an AbortError so callers do not +// mistake it for a user-initiated abort. Chat generation streams, so it +// gets a wider bound than the quick calls. +const FETCH_TIMEOUT_MS = 30000; +const CHAT_FETCH_TIMEOUT_MS = 120000; + +async function apiFetchTimed(path: string, init: RequestInit = {}, timeoutMs: number = FETCH_TIMEOUT_MS): Promise { + const controller = new AbortController(); + let timedOut = false; + const timer = window.setTimeout(() => { + timedOut = true; + controller.abort(); + }, timeoutMs); + const onExternalAbort = () => controller.abort(); + init.signal?.addEventListener("abort", onExternalAbort, { once: true }); + try { + return await apiFetch(path, { ...init, signal: controller.signal }); + } catch (error) { + if (timedOut && isAbortError(error)) throw new Error("Request timed out"); + throw error; + } finally { + window.clearTimeout(timer); + init.signal?.removeEventListener("abort", onExternalAbort); + } +} + function createRequestId(prefix: string) { if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") { return `${prefix}-${crypto.randomUUID()}`; @@ -189,6 +217,9 @@ function formatHttpError(error: HttpResponseError) { case 404: return "当前会话已过期,请新建整理后重试。"; case 409: + if (error.detail?.includes("已过期")) { + return "当前会话已过期,请新建整理后继续。"; + } if (error.detail?.includes("请求上限") || error.detail?.includes("回放窗口")) { return "当前会话无法继续安全重放,请新建整理后继续。"; } @@ -250,7 +281,10 @@ function App() { const [draft, setDraft] = useState(""); const [loading, setLoading] = useState(false); const [sessionStatus, setSessionStatus] = useState("idle"); - const [streaming, setStreaming] = useState(true); + // Streaming is always on: the JSON body is only a fallback when the + // server answers without an event stream. There is no toggle for it, + // so this is a plain constant rather than unused state. + const streaming = true; const [events, setEvents] = useState([]); const [citations, setCitations] = useState([]); const [selectedCitationMessageId, setSelectedCitationMessageId] = useState(null); @@ -447,7 +481,7 @@ function App() { setAuthBootstrapError(null); void (async () => { try { - const response = await apiFetch("/api/auth/me", { signal: controller.signal }); + const response = await apiFetchTimed("/api/auth/me", { signal: controller.signal }); if (response.status === 401) { if (authRequestRef.current !== controller || controller.signal.aborted) return; setAuthUser(null); @@ -476,7 +510,7 @@ function App() { setLogoutPending(true); setError(null); try { - const response = await apiFetch("/api/auth/logout", { method: "POST" }); + const response = await apiFetchTimed("/api/auth/logout", { method: "POST" }); if (response.status !== 401) await ensureResponseOk(response); returnToAuthentication(""); setAuthBootstrapError(null); @@ -564,7 +598,7 @@ function App() { sessionRequestRef.current = controller; void (async () => { try { - const response = await apiFetch("/api/sessions", { + const response = await apiFetchTimed("/api/sessions", { method: "POST", headers: apiHeaders({ // The key lets a StrictMode effect replay resolve to one server session. @@ -624,7 +658,7 @@ function App() { setLoading(true); setEvents([]); try { - const response = await apiFetch(`/api/chat?stream=${streaming}`, { + const response = await apiFetchTimed(`/api/chat?stream=${streaming}`, { method: "POST", headers: apiHeaders({ "Content-Type": "application/json", @@ -632,7 +666,7 @@ function App() { }), body: JSON.stringify({ session_id: sessionId, message: text, request_id: requestId }), signal: controller.signal, - }); + }, CHAT_FETCH_TIMEOUT_MS); await ensureResponseOk(response); if (streaming && response.body && response.headers.get("content-type")?.includes("text/event-stream")) { const body = await consumeStream(response.body, generation, sessionId, controller); @@ -648,12 +682,31 @@ function App() { returnToAuthentication("登录状态已过期,请重新登录。"); return; } + // A reply for another session is a session problem, not a network + // problem: say so and keep the user's message instead of deleting it. + if (requestError instanceof Error && requestError.message.includes("invalid session identity")) { + setError("会话已变更,本次回答无法确认,请新建整理后重试。你的输入已保留。"); + return; + } if (!(requestError instanceof HttpResponseError)) { - const recovered = await recoverCommittedResult(sessionId, requestId, controller); - if (recovered && requestIsCurrent(generation, controller, sessionId)) { - applyFinal(recovered, generation, sessionId, controller); - pendingRetryRef.current = null; - setError(null); + let recovered: RecoveryResult = { status: "unavailable" }; + try { + recovered = await recoverCommittedResult(sessionId, requestId, controller); + } catch { + recovered = { status: "unavailable" }; + } + if (recovered.status === "found" && requestIsCurrent(generation, controller, sessionId)) { + try { + applyFinal(recovered.body, generation, sessionId, controller); + pendingRetryRef.current = null; + setError(null); + } catch { + setError("会话已变更,本次回答无法恢复,请新建整理后重试。你的输入已保留。"); + } + return; + } + if (recovered.status === "not-found") { + setError("本次回答未找到,会话可能已过期,请新建整理后重试。你的输入已保留。"); return; } } @@ -713,7 +766,11 @@ function App() { // A complete final frame is the application-level commit marker. Do // not wait for the transport to close: the socket may drop after the // payload was received, and discarding it would create an orphaned turn. - if (finalPayload) return finalPayload; + // Release the reader first so the stream does not stay open. + if (finalPayload) { + await reader.cancel(); + return finalPayload; + } if (done) break; } if (!finalPayload && requestIsCurrent(generation, controller, sessionId)) { @@ -723,26 +780,34 @@ function App() { return finalPayload; } + // A recovery lookup distinguishes "the committed answer is gone" from + // "the network is down": only the first is a session problem, and the + // two must not be reported with the same message. + type RecoveryResult = + | { status: "found"; body: ChatResponseBody } + | { status: "not-found" } + | { status: "unavailable" }; + async function recoverCommittedResult( sessionId: string, requestId: string, controller: AbortController, - ): Promise { + ): Promise { for (let attempt = 0; attempt < 3; attempt += 1) { - if (controller.signal.aborted) return null; + if (controller.signal.aborted) return { status: "unavailable" }; try { - const response = await apiFetch( + const response = await apiFetchTimed( `/api/sessions/${encodeURIComponent(sessionId)}/requests/${encodeURIComponent(requestId)}`, { headers: apiHeaders(), signal: controller.signal }, ); - if (response.ok) return (await response.json()) as ChatResponseBody; - if (response.status !== 404) return null; + if (response.ok) return { status: "found", body: (await response.json()) as ChatResponseBody }; + if (response.status !== 404) return { status: "unavailable" }; } catch (recoveryError) { - if (isAbortError(recoveryError)) return null; + if (isAbortError(recoveryError)) return { status: "unavailable" }; } if (attempt < 2) await new Promise((resolve) => window.setTimeout(resolve, 120)); } - return null; + return { status: "not-found" }; } function applyFinal(body: ChatResponseBody, generation: number, sessionId: string, controller: AbortController) { @@ -849,8 +914,6 @@ function App() { ? "服务不可用" : !session ? "建立安全会话" - : session.mode === "preview" - ? "示例会话" : session.network_enabled === false ? "知识服务受限" : "整理服务在线"; @@ -886,7 +949,7 @@ function App() {
{serviceStatusLabel}
- {authUser.username} + {authUser.username} @@ -974,7 +1037,7 @@ function App() {

可以从哪里不舒服、持续多久开始。用药或检查方面的疑问,也可以直接提问。

先从一个具体问题开始,信息会随着对话逐步补齐。
- :
{formatDateDivider(messages[0]?.timestamp ?? Date.now())}
} + :
{formatDateDivider(messages.find((message) => message.role === "user")?.timestamp ?? messages[0]?.timestamp ?? Date.now())}
} {(!isWelcome ? messages : []).map((message) => (
{message.role === "assistant" &&
} @@ -1043,12 +1106,12 @@ function App() { {referenceCitations.some((citation) => citation.source.includes("OGL-3.0")) &&

部分资料为项目中文改编,未经原机构审核。
Contains public sector information licensed under the Open Government Licence v3.0.

} - {structuredResult &&
只读数据查询

结构化结果

{structuredResult.blocked ?

{structuredResult.reason}

:
{structuredResult.rows.map((row, index) =>
{Object.entries(row).map(([key, value]) => {key}{value})}
)}
}
} + {structuredResult &&
只读数据查询

结构化结果

{structuredResult.blocked ?

{structuredResult.reason}

: structuredResult.rows.length === 0 ?

无匹配结果

{structuredResult.columns?.length ?

查询字段:{structuredResult.columns.join("、")}

: null}{structuredResult.sql ?

查询语句:{structuredResult.sql}

: null}
:
{structuredResult.rows.map((row, index) =>
{Object.entries(row).map(([key, value]) => {key}{value})}
)}
}
}
{riskAssessed ? "回答经过规则安全审查" : "随对话整理健康线索"}
来源版本和查询范围可追溯
- {error &&
{error}
} + {error &&
{error}
}
); } @@ -1101,7 +1164,7 @@ function AuthScreen({ status, bootstrapError, onAuthenticated, onRetryConnection setPending(true); setFormError(null); try { - const response = await apiFetch(`/api/auth/${mode}`, { + const response = await apiFetchTimed(`/api/auth/${mode}`, { method: "POST", headers: apiHeaders({ "Content-Type": "application/json" }), body: JSON.stringify({ username: validation.username, password }), diff --git a/frontend/src/styles.css b/frontend/src/styles.css index 2523191..31347fd 100644 --- a/frontend/src/styles.css +++ b/frontend/src/styles.css @@ -121,7 +121,7 @@ button.starter-prompt:hover:not(:disabled) { border-color:#a1cbd0; background:#f .service-status.unavailable .status-dot { background:var(--coral-600); } .account-cluster { display:flex; align-items:center; gap:9px; padding-left:17px; border-left:1px solid var(--line); } .account-identity { display:inline-flex; align-items:center; gap:6px; color:var(--ink-700); font-size:12px; } -.account-name { max-width:120px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; } +.account-name { max-width:220px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; } .logout-button { display:inline-flex; align-items:center; gap:5px; min-height:34px; padding:0 7px; color:var(--ink-500); font-size:12px; background:transparent; border:1px solid transparent; border-radius:6px; } .logout-button:hover { color:var(--teal-800); background:var(--teal-050); } .workspace { display:grid; grid-template-columns:216px minmax(0,1fr) 320px; gap:0; height:calc(100dvh - 64px); min-height:0; } @@ -301,6 +301,9 @@ button.starter-prompt:hover:not(:disabled) { border-color:#a1cbd0; background:#f .query-row > span { display:flex; justify-content:space-between; gap:10px; color:var(--ink-800); font-size:12px; overflow-wrap:anywhere; } .query-row small { color:var(--ink-500); font-size:11px; } .query-blocked { color:var(--coral-600); font-size:12px; line-height:1.8; } +.query-empty { color:var(--ink-700); font-size:12px; line-height:1.8; } +.query-empty p { margin:0 0 4px; } +.query-sql { color:var(--ink-500); font-size:11px; overflow-wrap:anywhere; } .panel-footnote { display:flex; align-items:flex-start; gap:8px; margin-top:19px; color:var(--ink-500); font-size:11px; line-height:1.8; } .panel-footnote svg { flex-shrink:0; margin-top:3px; } .content-license { margin:0; padding:15px 0; color:var(--ink-500); font-size:11px; line-height:1.8; overflow-wrap:anywhere; } diff --git a/frontend/src/workflow-progress.ts b/frontend/src/workflow-progress.ts index e89dabf..db8fe24 100644 --- a/frontend/src/workflow-progress.ts +++ b/frontend/src/workflow-progress.ts @@ -45,13 +45,18 @@ export function buildWorkflowStages( return STAGES.map((stage) => { const terminal = stage.nodes.every((node) => byNode.has(node)); const skipped = terminal && stage.nodes.every((node) => byNode.get(node)?.status === "skipped"); + // Once the run has ended, a stage that never completed did not stay + // "pending": it was not executed. Only a live run has a pending stage. const status = terminal ? (skipped ? "skipped" : "completed") - : loading && !activeAssigned ? "running" : "pending"; + : loading && !activeAssigned ? "running" + : loading ? "pending" : "skipped"; if (!terminal) activeAssigned = true; const label = stage.id === "answer" && risk === "high" ? "整理紧急就医指引" : stage.id === "answer" && intent === "structured" ? "核对只读查询结果" : stage.label; const skippedRetrieval = byNode.get("retrieve")?.status === "skipped"; - const detail = stage.id === "answer" && skippedRetrieval + // The "skipped retrieval" note describes a finished answer stage; it + // must not appear while the answer stage is still running or pending. + const detail = terminal && stage.id === "answer" && skippedRetrieval ? risk === "high" ? "高风险分流,跳过普通资料检索" : "结构化分支,跳过普通资料检索" : undefined; return { id: stage.id, label, status, detail }; diff --git a/frontend/tests/workflow-progress.test.mjs b/frontend/tests/workflow-progress.test.mjs index b88a45b..2d9400e 100644 --- a/frontend/tests/workflow-progress.test.mjs +++ b/frontend/tests/workflow-progress.test.mjs @@ -39,3 +39,31 @@ test("final JSON and recovered replies restore node states from metadata", () => assert.ok(buildWorkflowStages(restored, "low", "disease", false).every((stage) => stage.status === "completed")); assert.deepEqual(responsePipelineEvents([event("risk")], metadata), [event("risk")]); }); + +test("a run that ends unfinished marks unexecuted stages skipped, not pending", () => { + const events = [event("normalize"), event("extract_profile"), event("intent")]; + const stages = buildWorkflowStages(events, "low", "disease", false); + assert.equal(stages[0].status, "completed"); + assert.equal(stages[1].status, "skipped"); + assert.equal(stages[2].status, "skipped"); + assert.equal(stages[3].status, "skipped"); + // While the same run is still live, the next stage is running. + const live = buildWorkflowStages(events, "low", "disease", true); + assert.equal(live[1].status, "running"); + assert.equal(live[2].status, "pending"); +}); + +test("the skipped-retrieval note only appears once the answer stage is finished", () => { + const events = [event("normalize"), event("extract_profile"), event("intent"), event("risk"), event("retrieve", "skipped")]; + const running = buildWorkflowStages(events, "high", "disease", true); + assert.equal(running[2].status, "running"); + assert.equal(running[2].detail, undefined); + const finished = buildWorkflowStages( + [...events, event("structured_query", "skipped"), event("draft"), event("safety_review"), event("finalize")], + "high", + "disease", + false, + ); + assert.equal(finished[2].status, "completed"); + assert.match(finished[2].detail, /跳过普通资料检索/); +}); diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts index d5174b6..b9620c9 100644 --- a/frontend/vite.config.ts +++ b/frontend/vite.config.ts @@ -9,18 +9,24 @@ export default defineConfig(({ mode }) => { || env.MEDGUIDE_API_PROXY || env.VITE_API_PROXY; + const proxy = apiProxyTarget ? { + "/api": { + target: apiProxyTarget, + changeOrigin: true, + }, + } : undefined; + return { plugins: [react()], server: { port: 5173, - ...(apiProxyTarget ? { - proxy: { - "/api": { - target: apiProxyTarget, - changeOrigin: true, - }, - }, - } : {}), + ...(proxy ? { proxy } : {}), + }, + // `vite preview` serves the production build without the dev server, + // so it needs the same /api proxy or /api/auth/me answers with HTML. + preview: { + port: 4173, + ...(proxy ? { proxy } : {}), }, }; }); From ed52500936ad00e7b626a3eb9e71ffcb0e2cfbac Mon Sep 17 00:00:00 2001 From: Zhenxian Liang Date: Mon, 16 Nov 2026 12:45:23 +0800 Subject: [PATCH 2/7] Fix #9: remove unused ScenicAtmosphere assets (frontend/src/ScenicAtmosphere.tsx) --- frontend/src/ScenicAtmosphere.tsx | 132 ------------------------------ 1 file changed, 132 deletions(-) delete mode 100644 frontend/src/ScenicAtmosphere.tsx diff --git a/frontend/src/ScenicAtmosphere.tsx b/frontend/src/ScenicAtmosphere.tsx deleted file mode 100644 index 28b654e..0000000 --- a/frontend/src/ScenicAtmosphere.tsx +++ /dev/null @@ -1,132 +0,0 @@ -import { useCallback, useEffect, useState } from "react"; -import { Mountain, Pause, Play, Trees } from "lucide-react"; -import "./scenery.css"; - -type Scene = "lake" | "forest"; -type SceneryPreferences = { scene: Scene; paused: boolean }; - -export type SceneryState = { - scene: Scene; - setScene: (scene: Scene) => void; - paused: boolean; - togglePaused: () => void; - reducedMotion: boolean; -}; - -const STORAGE_KEY = "medguide-scenery"; -const MOTION_QUERY = "(prefers-reduced-motion: reduce)"; -const DEFAULT_PREFERENCES: SceneryPreferences = { scene: "lake", paused: false }; - -function readPreferences(): SceneryPreferences { - if (typeof window === "undefined") return DEFAULT_PREFERENCES; - try { - const stored: unknown = JSON.parse(window.localStorage.getItem(STORAGE_KEY) ?? "null"); - if (!stored || typeof stored !== "object" || Array.isArray(stored)) return DEFAULT_PREFERENCES; - const value = stored as Record; - return { - scene: value.scene === "forest" ? "forest" : "lake", - paused: typeof value.paused === "boolean" ? value.paused : false, - }; - } catch { - return DEFAULT_PREFERENCES; - } -} - -function prefersReducedMotion() { - return typeof window !== "undefined" && typeof window.matchMedia === "function" - ? window.matchMedia(MOTION_QUERY).matches - : false; -} - -export function useScenery(): SceneryState { - const [preferences, setPreferences] = useState(readPreferences); - const [reducedMotion, setReducedMotion] = useState(prefersReducedMotion); - - useEffect(() => { - if (typeof window.matchMedia !== "function") return; - const query = window.matchMedia(MOTION_QUERY); - const onChange = () => setReducedMotion(query.matches); - onChange(); - query.addEventListener("change", onChange); - return () => query.removeEventListener("change", onChange); - }, []); - - useEffect(() => { - try { - window.localStorage.setItem(STORAGE_KEY, JSON.stringify(preferences)); - } catch { - // The controls still work when browser storage is unavailable. - } - }, [preferences]); - - const setScene = useCallback((scene: Scene) => { - setPreferences((current) => current.scene === scene ? current : { ...current, scene }); - }, []); - - const togglePaused = useCallback(() => { - if (reducedMotion) return; - setPreferences((current) => ({ ...current, paused: !current.paused })); - }, [reducedMotion]); - - return { - scene: preferences.scene, - setScene, - paused: preferences.paused || reducedMotion, - togglePaused, - reducedMotion, - }; -} - -export function ScenicBackdrop({ scene, paused }: Pick) { - return ( -