diff --git a/backend/app/auth.py b/backend/app/auth.py index 218581a..4483af3 100644 --- a/backend/app/auth.py +++ b/backend/app/auth.py @@ -35,6 +35,10 @@ class InvalidCredentialsError(AuthError): """Raised for an unknown username or an incorrect password.""" +class UnknownUserError(AuthError): + """Raised when a session is requested for a username that is not registered.""" + + class InvalidUsernameError(AuthError): """Raised when a username cannot be represented safely.""" @@ -323,6 +327,16 @@ def verify_credentials(self, username: str, password: str) -> str: def create_session(self, username: str) -> tuple[str, int]: normalized = normalize_username(username) + with self._connect() as connection: + row = connection.execute( + "SELECT 1 FROM users WHERE username = ?", + (normalized,), + ).fetchone() + if row is None: + # Check first so a missing user is reported as such, instead of + # surfacing as a foreign-key IntegrityError retried as a + # "could not allocate a unique authentication token" failure. + raise UnknownUserError("user does not exist") now = int(self._clock()) expires_at = now + self.session_ttl_seconds for _ in range(3): @@ -338,7 +352,13 @@ def create_session(self, username: str) -> tuple[str, int]: (self._token_hash(token), normalized, now, expires_at), ) return token, expires_at - except sqlite3.IntegrityError: + except sqlite3.IntegrityError as exc: + # Only a token-hash collision is worth retrying; any other + # constraint failure (e.g. a foreign key, if the user was + # deleted between the check above and the insert) must + # surface immediately instead of being misreported. + if not _is_unique_constraint_error(exc): + raise continue raise RuntimeError("could not allocate a unique authentication token") @@ -593,6 +613,16 @@ def create_session(self, username: str) -> tuple[str, int]: from sqlalchemy.exc import IntegrityError normalized = normalize_username(username) + with self.engine.connect() as connection: + row = connection.execute( + text("SELECT 1 FROM medguide_users WHERE username = :username"), + {"username": normalized}, + ).first() + if row is None: + # Check first so a missing user is reported as such, instead of + # surfacing as a foreign-key IntegrityError retried as a + # "could not allocate a unique authentication token" failure. + raise UnknownUserError("user does not exist") now = int(self._clock()) expires_at = now + self.session_ttl_seconds for _ in range(3): @@ -617,7 +647,13 @@ def create_session(self, username: str) -> tuple[str, int]: }, ) return token, expires_at - except IntegrityError: + except IntegrityError as exc: + # Only a token-hash collision is worth retrying; any other + # constraint failure (e.g. a foreign key, if the user was + # deleted between the check above and the insert) must + # surface immediately instead of being misreported. + if not _is_unique_constraint_error(exc): + raise continue raise RuntimeError("could not allocate a unique authentication token") diff --git a/backend/app/embeddings.py b/backend/app/embeddings.py index 4494171..87e968f 100644 --- a/backend/app/embeddings.py +++ b/backend/app/embeddings.py @@ -289,7 +289,7 @@ def _embedding_timeout() -> float: return 15.0 -_EMBEDDING_ENDPOINT_SUFFIXES = ("/embeddings", "/chat/completions", "/chaat/completions") +_EMBEDDING_ENDPOINT_SUFFIXES = ("/embeddings", "/chat/completions") def _normalize_embedding_base_url(value: str | None) -> str | None: @@ -299,11 +299,19 @@ def _normalize_embedding_base_url(value: str | None) -> str | None: if not raw: return None parsed = urlsplit(raw) - if not parsed.scheme or not parsed.netloc: + if parsed.scheme.lower() not in {"http", "https"} or not parsed.netloc: raise ValueError("Embedding base URL must include an HTTP(S) host") path = parsed.path.rstrip("/") for suffix in _EMBEDDING_ENDPOINT_SUFFIXES: if path.lower().endswith(suffix): path = path[: -len(suffix)].rstrip("/") break - return urlunsplit((parsed.scheme, parsed.netloc, path, parsed.query, parsed.fragment)).rstrip("/") + else: + # See _normalize_base_url: a mistyped endpoint must fail closed + # instead of being silently truncated to a wrong base URL. + if path.lower().endswith("/completions"): + raise ValueError("Embedding base URL looks like a mistyped completion endpoint") + # Query strings and fragments are never part of a base URL; drop them + # instead of forwarding them (and any credentials they carry) with + # every request. + return urlunsplit((parsed.scheme, parsed.netloc, path, "", "")).rstrip("/") 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/ingestion.py b/backend/app/ingestion.py index 745b0ca..7c6cf94 100644 --- a/backend/app/ingestion.py +++ b/backend/app/ingestion.py @@ -230,7 +230,13 @@ def _contains_nested_credentials(cls, value: str) -> bool: break decoded = next_value normalized = unicodedata.normalize("NFKC", decoded) - for match in re.finditer(r"(?:^|[?&;\s])([^=&?#\s]+)\s*=", normalized): + # A nested URL carrying userinfo (scheme://user:password@host) + # hides credentials that no key=value scan would ever see. + if re.search(r"://[^/\s]*@", normalized): + return True + # `#` and `/` are delimiters too: a credential smuggled in as + # `.../x%23token=secret` or `.../x/token=secret` must be caught. + for match in re.finditer(r"(?:^|[?&;#/\s])([^=&?#\s]+)\s*=", normalized): if cls._sensitive_query_key(match.group(1)): return True return False diff --git a/backend/app/llm.py b/backend/app/llm.py index fd86208..590d192 100644 --- a/backend/app/llm.py +++ b/backend/app/llm.py @@ -291,7 +291,7 @@ async def aclose(self) -> None: self.close() -_COMPLETION_ENDPOINT_SUFFIXES = ("/chat/completions", "/chaat/completions") +_COMPLETION_ENDPOINT_SUFFIXES = ("/chat/completions",) def _normalize_local_base_url(value: str) -> str: @@ -332,11 +332,21 @@ def _normalize_base_url(value: str | None) -> str | None: if not raw: return None parsed = urlsplit(raw) - if not parsed.scheme or not parsed.netloc: + if parsed.scheme.lower() not in {"http", "https"} or not parsed.netloc: raise ValueError("OpenAI base URL must include an HTTP(S) host") path = parsed.path.rstrip("/") for suffix in _COMPLETION_ENDPOINT_SUFFIXES: if path.lower().endswith(suffix): path = path[: -len(suffix)].rstrip("/") break - return urlunsplit((parsed.scheme, parsed.netloc, path, parsed.query, parsed.fragment)).rstrip("/") + else: + # A path ending in some other ".../completions" is almost certainly + # a mistyped endpoint (e.g. "/chaat/completions"). Fail closed + # instead of silently truncating it to a base URL that then hits + # the wrong endpoint. + if path.lower().endswith("/completions"): + raise ValueError("OpenAI base URL looks like a mistyped completion endpoint") + # Query strings and fragments are never part of a base URL; drop them + # instead of forwarding them (and any credentials they carry) with + # every request. + return urlunsplit((parsed.scheme, parsed.netloc, path, "", "")).rstrip("/") diff --git a/backend/app/main.py b/backend/app/main.py index 217a42a..b6d5bcb 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 @@ -565,9 +569,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 +588,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 +1038,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/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/models.py b/backend/app/models.py index 7ae75c6..d3db3a9 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 @@ -115,13 +121,20 @@ class SQLQueryResult: rows: tuple[dict[str, Any], ...] blocked: bool = False reason: str | None = None + # True when the rows come from the built-in seeded sample database + # (SQLite test/local backend) rather than a connected production + # source, so callers can tell sample data apart from live data. + sample_data: bool = False def as_dict(self) -> dict[str, Any]: + # The SQL text itself is an internal detail: it must never cross + # the API boundary, where it would expose table/column layout. + # Internal callers that need the statement read ``.sql`` directly. return { "intent": self.intent, - "sql": self.sql, "columns": list(self.columns), "rows": [dict(row) for row in self.rows], "blocked": self.blocked, "reason": self.reason, + "sample_data": self.sample_data, } diff --git a/backend/app/retrieval.py b/backend/app/retrieval.py index a33dc38..a8bdbb4 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,14 +40,37 @@ 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()) + ) + + # 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" + for name in self.drug_names: + if name.lower() in normalized: + scores["drug"] = scores.get("drug", 0) + 1 + 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 {} @@ -163,6 +194,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)) @@ -188,10 +252,11 @@ def search( intent=intent, allowed_terms=self._embedding_query_terms, ) - provider_name = str(getattr(self.embedding_provider.spec, "provider", "")) - should_embed = self.remote_required or ( - self.local_vector_search and provider_name != "local" - ) + # The local Hash provider is a real embedding provider in test and + # offline modes; excluding it left the precomputed _local_vectors + # unused and every citation labelled "bm25". Embed whenever local + # vector search is enabled, regardless of provider. + should_embed = self.remote_required or self.local_vector_search if should_embed and self.embedding_provider.available: try: query_vector = self.embedding_provider.embed([embedding_query])[0] @@ -238,19 +303,19 @@ def search( mark_unavailable() candidates_by_id: dict[str, dict[str, Any]] = { - hit.chunk.id: {"chunk": hit.chunk, "bm25": hit.score, "vector": 0.0} + hit.chunk.id: {"chunk": hit.chunk, "bm25": hit.score, "vector": 0.0, "vector_source": None} for hit in lexical_hits } if ( self.local_vector_search and not self.remote_required - and provider_name != "local" and query_vector is not None ): for candidate in candidates_by_id.values(): local_vector = self._local_vectors.get(candidate["chunk"].id) if local_vector is not None: candidate["vector"] = self._cosine(query_vector, local_vector) + candidate["vector_source"] = "local" for hit_id, hit in remote_hits.items(): text = self.cleaner.clean(str(hit.get("text", ""))) if not text: @@ -275,9 +340,10 @@ def search( continue candidate = candidates_by_id.get(hit_id) if candidate is None: - candidate = {"chunk": remote_chunk, "bm25": 0.0, "vector": 0.0} + candidate = {"chunk": remote_chunk, "bm25": 0.0, "vector": 0.0, "vector_source": None} candidates_by_id[hit_id] = candidate candidate["vector"] = self._remote_score(hit) or 0.0 + candidate["vector_source"] = "remote" candidates: list[tuple[float, float, float, DocumentChunk]] = [] for candidate in candidates_by_id.values(): @@ -287,7 +353,16 @@ def search( lexical_score = bm25 / (bm25 + 5.0) if bm25 > 0 else 0.0 intent_boost = 0.08 if chunk.metadata.get("category") == intent else 0.0 if bm25 > 0 and vector > 0: - fused = 0.72 * vector + 0.20 * lexical_score + intent_boost + if candidate.get("vector_source") == "local": + # Local vectors are 64-dim token hashes, a much weaker + # relevance signal than dense remote embeddings: the + # same weights would let hash collisions outrank BM25 + # (e.g. an X-ray doc outranking the blood-test doc for + # a 血常规 query). Let BM25 carry the ranking and use + # the local vector as a secondary cue. + fused = 0.25 * vector + 0.60 * lexical_score + intent_boost + else: + fused = 0.72 * vector + 0.20 * lexical_score + intent_boost elif vector > 0: fused = 0.84 * vector + intent_boost else: @@ -351,14 +426,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..b7b8b7d 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,17 +251,23 @@ 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 if flags: - advice = "建议立即联系当地急救服务或前往最近的急诊;不要仅依赖线上问答等待观察。" + advice = "请立即拨打 120(中国大陆急救电话)或前往最近的急诊;不要仅依赖线上问答等待观察。" return RiskAssessment("high", tuple(dict.fromkeys(flags)), advice) watch_flags = [ diff --git a/backend/app/sql_guard.py b/backend/app/sql_guard.py index 6ca551a..5cb0850 100644 --- a/backend/app/sql_guard.py +++ b/backend/app/sql_guard.py @@ -527,7 +527,9 @@ def execute(self, intent: str, sql: str, params: tuple[Any, ...] = ()) -> SQLQue cursor = conn.execute(validated, params) rows = tuple(dict(row) for row in cursor.fetchall()) columns = tuple(column[0] for column in cursor.description or ()) - return SQLQueryResult(intent, validated, params, columns, rows) + return SQLQueryResult( + intent, validated, params, columns, rows, sample_data=self.backend is None + ) except Exception as exc: # Adapter/driver exceptions must not escape the API boundary. Do # not return raw driver text because it can contain DSNs, table @@ -539,6 +541,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 +617,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 +630,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 +651,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 +664,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}%",)) @@ -603,7 +688,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..2acd140 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, @@ -381,6 +470,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..0e13cae 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() @@ -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 = { @@ -376,9 +382,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 +415,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 +534,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", "") @@ -534,12 +574,32 @@ def extract_profile(self, state: WorkflowState) -> WorkflowState: for clause in patient_clauses: age_match = re.search(r"(? 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 +623,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 +675,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 +703,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:] @@ -669,6 +763,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"): @@ -709,6 +809,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 @@ -727,6 +839,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] @@ -752,7 +867,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 @@ -760,6 +875,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结果来自当前已连接的数据源;实际库存、排班和价格请以医院实时系统为准。" @@ -774,7 +891,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 @@ -798,6 +917,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") @@ -817,11 +976,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..be5a7d1 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: @@ -33,8 +34,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: @@ -82,6 +86,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 +99,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 +119,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 +136,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_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"] 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_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_rag_pipeline.py b/backend/tests/test_rag_pipeline.py index 8fbbe1f..3304ba8 100644 --- a/backend/tests/test_rag_pipeline.py +++ b/backend/tests/test_rag_pipeline.py @@ -33,11 +33,15 @@ def embed(self, texts): def test_provider_base_urls_are_normalized_and_endpoint_paths_are_stripped() -> None: assert _normalize_base_url("https://provider.example/v1/chat/completions") == "https://provider.example/v1" - # Gateways have been observed advertising a ``chaat`` completion path in - # their setup instructions. A pasted endpoint is an endpoint either way, - # so it normalizes to the same base URL instead of failing closed on a - # typo the operator cannot see. - assert _normalize_base_url("https://provider.example/v1/chaat/completions") == "https://provider.example/v1" + # Issue #8 6b: a mistyped endpoint must fail closed instead of being + # silently truncated to a base URL that then hits the wrong endpoint. + with pytest.raises(ValueError, match="mistyped completion endpoint"): + _normalize_base_url("https://provider.example/v1/chaat/completions") + # Query strings and fragments are dropped, never forwarded; only + # http(s) schemes are accepted. + assert _normalize_base_url("https://provider.example/v1?api_key=secret#frag") == "https://provider.example/v1" + with pytest.raises(ValueError, match="HTTP\\(S\\) host"): + _normalize_base_url("ftp://provider.example/v1") assert _normalize_base_url("https://provider.example/v1/") == "https://provider.example/v1" @@ -168,6 +172,10 @@ def test_source_url_rejects_public_but_unapproved_host() -> None: "private_key=secret", "redirect=https%3A%2F%2Fother.test%2Fx%3Ftoken%3Dsecret", "redirect=https%253A%252F%252Fother.test%252Fx%253Fprivate_key%253Dsecret", + # Issue #8 6e: a credential smuggled in after a `#` fragment, or a + # nested URL carrying userinfo, must be caught as well. + "redirect=https://evil/x%23token=secret", + "redirect=https://user:secretpass@evil.example/", "view=full&token=secret&token=second", ]) def test_source_url_rejects_sensitive_query_parameters(query: str) -> None: 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/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_validation_exposure.py b/backend/tests/test_validation_exposure.py new file mode 100644 index 0000000..42dffa3 --- /dev/null +++ b/backend/tests/test_validation_exposure.py @@ -0,0 +1,179 @@ +"""Regression tests for MedGuide issue #8 (backend validation & exposure, 6a-6f).""" + +from __future__ import annotations + +from types import SimpleNamespace + +import pytest +from fastapi.testclient import TestClient +from sqlalchemy import event + +from app.auth import AuthStore, MySQLAuthStore, UnknownUserError +from app.embeddings import _normalize_embedding_base_url +from app.ingestion import MedicalDocumentCleaner +from app.llm import _normalize_base_url +from app.main import app +from app.retrieval import HybridRetriever +from app.safety import SafetyEngine +from app.sql_guard import ReadOnlySQLGuard +from app.workflow import MedGuideWorkflow +from conftest import login_client + + +def _workflow() -> MedGuideWorkflow: + return MedGuideWorkflow(HybridRetriever(), ReadOnlySQLGuard(), SafetyEngine()) + + +# 6a: age extraction has no upper bound (999 -> elderly high risk). +def test_age_above_120_is_ignored_and_not_flagged_as_elderly() -> None: + workflow = _workflow() + state = workflow.normalize( + { + "user_message": "999岁男性咳嗽三天", + "profile": {"symptoms": [], "associated_symptoms": []}, + } + ) + result = workflow.extract_profile(state) + assert "age" not in result["profile"] + assessment = SafetyEngine().screen("999岁男性咳嗽三天", result["profile"]) + assert "婴幼儿或高龄人群" not in assessment.flags + + +def test_plausible_age_is_still_extracted() -> None: + workflow = _workflow() + state = workflow.normalize( + { + "user_message": "今年25岁,咳嗽三天", + "profile": {"symptoms": [], "associated_symptoms": []}, + } + ) + result = workflow.extract_profile(state) + assert result["profile"]["age"] == 25 + + +# 6b: base_url normalization keeps query/fragment, accepts any scheme, +# and silently "corrects" mistyped endpoints. +@pytest.mark.parametrize( + "normalizer", + [_normalize_base_url, _normalize_embedding_base_url], +) +def test_base_url_normalizers_drop_query_and_fragment_and_require_http(normalizer) -> None: + assert normalizer("https://provider.example/v1?api_key=secret#frag") == "https://provider.example/v1" + assert normalizer("https://provider.example/v1/chat/completions") == "https://provider.example/v1" + with pytest.raises(ValueError, match="HTTP\\(S\\) host"): + normalizer("ftp://provider.example/v1") + with pytest.raises(ValueError, match="mistyped completion endpoint"): + normalizer("https://provider.example/v1/chaat/completions") + + +# 6c: create_session does not check that the user exists; the foreign-key +# failure is misreported as a token-allocation failure. +@pytest.fixture(params=["sqlite", "mysql-adapter-on-sqlite"]) +def auth_store(request, tmp_path): + database_path = tmp_path / "auth.sqlite3" + kwargs = { + "session_ttl_seconds": 300, + "password_iterations": 100_000, + "clock": lambda: 1_000.0, + } + if request.param == "sqlite": + store = AuthStore(database_path, **kwargs) + else: + + class SQLiteSchemaMySQLAuthStore(MySQLAuthStore): + def _initialize(self): + event.listen( + self.engine, + "connect", + lambda connection, _record: connection.execute("PRAGMA foreign_keys = ON"), + ) + with self.engine.begin() as connection: + connection.exec_driver_sql( + "CREATE TABLE medguide_users (username TEXT PRIMARY KEY, " + "password_salt BLOB NOT NULL, password_hash BLOB NOT NULL, " + "password_iterations INTEGER NOT NULL, created_at INTEGER NOT NULL)" + ) + connection.exec_driver_sql( + "CREATE TABLE medguide_auth_sessions (token_hash BLOB PRIMARY KEY, " + "username TEXT NOT NULL REFERENCES medguide_users(username), " + "created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL)" + ) + + store = SQLiteSchemaMySQLAuthStore(f"sqlite:///{database_path.as_posix()}", **kwargs) + yield SimpleNamespace(store=store) + if isinstance(store, MySQLAuthStore): + store.close() + + +def test_create_session_for_unknown_user_reports_the_user_not_a_token_failure(auth_store) -> None: + with pytest.raises(UnknownUserError, match="user does not exist"): + auth_store.store.create_session("ghostuser123") + + +def test_create_session_for_registered_user_still_works(auth_store) -> None: + auth_store.store.register("realuser", "Correct-Horse-42") + token, expires_at = auth_store.store.create_session("realuser") + assert token + assert expires_at == 1_300 + + +# 6d: /api/query exposes SQL; sample rows are indistinguishable from live data. +def test_api_query_response_has_no_sql_and_labels_sample_data() -> None: + with TestClient(app, base_url="https://testserver") as client: + # Issue #6: /api/query requires a session in every mode, so this + # 6d response-shape check must log in first (same as the other + # API tests); the assertions below are unchanged. + login_client(client, "validation_exposure_user") + response = client.post("/api/query", json={"text": "查询布洛芬库存"}) + assert response.status_code == 200 + body = response.json() + assert body["matched"] is True + result = body["result"] + assert "sql" not in result + # The internal object still carries the statement for logging/debugging. + guard = ReadOnlySQLGuard() + internal = guard.from_natural_language("查询布洛芬库存") + assert internal is not None and internal.sql.startswith("SELECT") + assert result["sample_data"] is True + assert result["rows"] and result["rows"][0]["name"] == "布洛芬缓释胶囊" + + +# 6e: nested-credential check bypassed via `#` fragments and nested userinfo. +@pytest.mark.parametrize( + "query", + [ + "redirect=https://evil/x%23token=secret", + "redirect=https://user:secretpass@evil.example/", + ], +) +def test_source_url_rejects_fragment_and_userinfo_nested_credentials(query: str) -> None: + with pytest.raises(ValueError, match="sensitive query parameter"): + MedicalDocumentCleaner.sanitize_source_url(f"https://www.nhs.uk/reference?{query}") + + +def test_source_url_still_allows_plain_nested_urls_without_credentials() -> None: + value = "https://www.nhs.uk/reference?redirect=https://example.org/guide?view=full" + assert MedicalDocumentCleaner.sanitize_source_url(value) == value + + +# 6f: test-mode local vector retrieval is dead code; everything is BM25. +def test_local_vector_search_fuses_vectors_in_test_mode() -> None: + retriever = HybridRetriever() + assert len(retriever._local_vectors) == len(retriever.chunks) > 0 + labels = set() + for query in ("发烧咳嗽怎么办", "头痛的原因", "感冒吃什么药"): + for citation in retriever.search(query, "disease", top_k=4): + labels.add(citation.retrieval) + assert labels - {"bm25", "hybrid", "vector"} == set() + assert labels & {"hybrid", "vector"}, f"expected vector fusion, got only {labels}" + + +def test_local_vector_weight_does_not_outrank_bm25() -> None: + # The local vectors are 64-dim token hashes: with the remote fusion + # weights (0.72 vector / 0.20 lexical) a chest X-ray doc outranked the + # blood-test doc for a 血常规 query. Local vectors must stay a + # secondary cue behind BM25. + results = HybridRetriever().search("血常规检查前需要注意什么?", "exam", top_k=4) + assert results + assert results[0].id.startswith("exam-cbc-001") + assert results[0].retrieval == "hybrid" 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/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/public/landscapes/SOURCES.md b/frontend/public/landscapes/SOURCES.md deleted file mode 100644 index 5deeab5..0000000 --- a/frontend/public/landscapes/SOURCES.md +++ /dev/null @@ -1,17 +0,0 @@ -# Landscape photography - -The photographs below are bundled locally for the MedGuide interface. No remote image host is required at runtime. Both are landscape photography, with no visible logo or text and no identifiable portrait. The lake photograph includes a wooden boat in the foreground and tiny, distant boat occupants. - -| Local file | Photographer | Original photo | License | Local rendition | -| --- | --- | --- | --- | --- | -| `mountain-lake.webp` | [Luca Bravo](https://unsplash.com/@lucabravo) | [A wooden boat on the turquoise water of Lago di Braies with mountain peaks](https://unsplash.com/photos/O453M2Liufs) | [Unsplash License](https://unsplash.com/license) | 2000 × 1333, WebP, quality 60 | -| `forest-mist.webp` | [Sebastian Unrau](https://unsplash.com/@sebastian_unrau) | [Trees on forest with sun rays](https://unsplash.com/photos/sp-p7uuT0tw) | [Unsplash License](https://unsplash.com/license) | 2000 × 1333, WebP, quality 60 | - -Source image URLs: - -- https://images.unsplash.com/photo-1476514525535-07fb3b4ae5f1?fm=webp&q=60&w=2000&fit=max -- https://images.unsplash.com/photo-1448375240586-882707db888b?fm=webp&q=60&w=2000&fit=max - -Verification date: 2026-09-14. The publicly accessible photo pages, retrieved with the Jina Reader text service, each identify the photographer and state “Free to use under the Unsplash License.” The license page was available as a cached text snapshot. Its terms allow downloading, copying, modifying, distributing, and using the photographs for commercial and non-commercial purposes without permission; attribution is appreciated. Selling unmodified images or compiling them to replicate a competing image service is excluded. The original links above remain the license and attribution references. - -Changes: downscaled and encoded as WebP by the source image CDN. Opacity, tint, cropping in the viewport, and motion are presentation styles, not baked into these image files. diff --git a/frontend/public/landscapes/forest-mist.webp b/frontend/public/landscapes/forest-mist.webp deleted file mode 100644 index abf503c..0000000 Binary files a/frontend/public/landscapes/forest-mist.webp and /dev/null differ diff --git a/frontend/public/landscapes/mountain-lake.webp b/frontend/public/landscapes/mountain-lake.webp deleted file mode 100644 index defff8d..0000000 Binary files a/frontend/public/landscapes/mountain-lake.webp and /dev/null differ diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 1ef03dc..8c19344 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,13 +82,26 @@ 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; + /** SQL text is no longer sent by the API (issue #8 6d); kept optional + so older servers that still send it do not break the type. */ + sql?: string; columns: string[]; rows: Record[]; blocked: boolean; reason?: string | null; + /** True when the rows come from the built-in sample database. */ + sample_data?: boolean; }; type Message = { @@ -114,6 +136,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 +239,9 @@ function formatHttpError(error: HttpResponseError) { case 404: return "当前会话已过期,请新建整理后重试。"; case 409: + if (error.detail?.includes("已过期")) { + return "当前会话已过期,请新建整理后继续。"; + } if (error.detail?.includes("请求上限") || error.detail?.includes("回放窗口")) { return "当前会话无法继续安全重放,请新建整理后继续。"; } @@ -246,11 +299,15 @@ 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); 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); @@ -403,6 +460,7 @@ function App() { committedResponseIdsRef.current.clear(); sessionCreateKeyRef.current = null; setSession(null); + setSessions([]); setSessionStatus("idle"); setMessages([{ ...initialMessage, timestamp: Date.now() }]); setDraft(""); @@ -436,7 +494,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() { @@ -447,7 +615,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 +644,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 +732,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. @@ -578,6 +746,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) { @@ -624,7 +793,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 +801,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 +817,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 +901,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 +915,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) { @@ -773,6 +973,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() { @@ -849,8 +1051,6 @@ function App() { ? "服务不可用" : !session ? "建立安全会话" - : session.mode === "preview" - ? "示例会话" : session.network_enabled === false ? "知识服务受限" : "整理服务在线"; @@ -886,7 +1086,7 @@ function App() {
{serviceStatusLabel}
- {authUser.username} + {authUser.username} @@ -922,12 +1122,25 @@ function App() {
-
这次对话
+
历史对话
- + {sessions.length === 0 ? ( + + ) : ( + sessions.map((item) => ( + + )) + )}
如何描述问题 @@ -974,7 +1187,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" &&
} @@ -1025,7 +1238,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" ? "进行中" : "待处理"}
)}
:

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

}
} @@ -1043,12 +1256,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.sample_data ?

以下为内置样例数据,仅供演示,非实时业务数据。

: null}{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 +1314,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/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 ( -