diff --git a/README.md b/README.md index 43991ae..d262e06 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ MedGuide 是面向健康信息整理与就医指引的可审计服务。系统 Copy-Item .env.template .env ``` -生产模式至少填写 `MEDGUIDE_DOMAIN`、`OPENAI_API_KEY`、`OPENAI_BASE_URL`、`OPENAI_MODEL`、`REDIS_URL` 和 `MEDGUIDE_AUTH_DSN`。`MEDGUIDE_DOMAIN` 必须是已经解析到部署主机的公网域名;内置 Caddy 网关会自动申请并续期 TLS 证书。知识后端默认是 `milvus`,此时还必须填写 `MILVUS_URI`;若只使用经过审核并生成索引的词法知识库,请将 `MEDGUIDE_KNOWLEDGE_BACKEND` 明确设为 `bm25`。供应商地址填写到 `/v1` 基础路径,SDK 会调用标准 `/v1/chat/completions`: +生产模式至少填写 `MEDGUIDE_DOMAIN`、`OPENAI_API_KEY`、`OPENAI_BASE_URL`、`OPENAI_MODEL`、`REDIS_URL` 和 `MEDGUIDE_AUTH_DSN`。`MEDGUIDE_DOMAIN` 必须是已经解析到部署主机的公网域名;内置 Caddy 网关会自动申请并续期 TLS 证书。知识后端默认是 `milvus`,此时还必须填写 `MILVUS_URI`;若只使用经过审核并生成索引的词法知识库,请将 `MEDGUIDE_KNOWLEDGE_BACKEND` 明确设为 `bm25`。API 容器在启动前会校验生产必填依赖(`OPENAI_API_KEY`、`OPENAI_MODEL`、`REDIS_URL`、`MEDGUIDE_AUTH_DSN`,`milvus` 后端时还有 `MILVUS_URI`),缺失时直接报错退出并指明缺了哪一项;按提示补齐 `.env` 后重新 `docker compose up --build -d`。供应商地址填写到 `/v1` 基础路径,SDK 会调用标准 `/v1/chat/completions`: ```text OPENAI_BASE_URL= @@ -62,6 +62,7 @@ API 容器会在进程启动前按知识后端准备索引。`bm25` 模式根据 | --- | --- | | `MEDGUIDE_MODE` | 外部模型与共享存储设为 `production`;单实例本地推理使用独立 `local` 配置 | | `MEDGUIDE_LOCAL_LLM_BASE_URL` / `MEDGUIDE_LOCAL_LLM_MODEL` | `local` 模式专用的本机模型地址和模型 ID,不继承 `OPENAI_*` | +| `MEDGUIDE_LOCAL_LLM_PROVIDER` | 本地推理服务类型:`llama.cpp`(默认,发送 `chat_template_kwargs.enable_thinking=false`)或 `ollama`(发送 `reasoning_effort=none`);非法值启动即报错 | | `MEDGUIDE_LOCAL_LLM_TIMEOUT_SECONDS` / `MEDGUIDE_LOCAL_LLM_MAX_TOKENS` | 本地生成预算,默认 120 秒 / 512 token | | `MEDGUIDE_DOMAIN` | 已解析到部署主机的公网域名;TLS 网关启动时校验,缺失或非法则失败关闭 | | `MEDGUIDE_HTTP_PORT` / `MEDGUIDE_HTTPS_PORT` | TLS 网关对外发布端口,默认 80/443 | 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..3d01982 100644 --- a/backend/app/infra.py +++ b/backend/app/infra.py @@ -139,21 +139,47 @@ class RedisSessionAdapter: _UPSERT_FEEDBACK_SCRIPT = """ local previous = redis.call('HGET', KEYS[1], ARGV[1]) -if previous == ARGV[2] then - redis.call('EXPIRE', KEYS[1], ARGV[4]) - redis.call('EXPIRE', KEYS[2], ARGV[4]) +local stored_comment = redis.call('HGET', KEYS[1], ARGV[1] .. ':comment') +local comment = ARGV[3] +local comment_changed = comment ~= '' and stored_comment ~= comment +if previous == ARGV[2] and not comment_changed then + redis.call('EXPIRE', KEYS[1], ARGV[6]) + redis.call('EXPIRE', KEYS[2], ARGV[6]) return 0 end if previous == 'up' or previous == 'down' then - redis.call('HINCRBY', KEYS[2], 'feedback_' .. previous, -1) + if previous ~= ARGV[2] then + redis.call('HINCRBY', KEYS[2], 'feedback_' .. previous, -1) + redis.call('HINCRBY', KEYS[2], 'feedback_' .. ARGV[2], 1) + end +else + redis.call('HINCRBY', KEYS[2], 'feedback_' .. ARGV[2], 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) +if comment_changed then + redis.call('HSET', KEYS[1], ARGV[1] .. ':comment', comment) + redis.call('HSET', KEYS[1], ARGV[1] .. ':session_id', ARGV[4]) + redis.call('HSET', KEYS[1], ARGV[1] .. ':message_id', ARGV[5]) + if not stored_comment then + redis.call('HINCRBY', KEYS[2], 'feedback_commented', 1) + end end -redis.call('EXPIRE', KEYS[1], ARGV[4]) -redis.call('EXPIRE', KEYS[2], ARGV[4]) +local seq = redis.call('HINCRBY', KEYS[2], 'feedback_comment_seq', 1) +redis.call('HSET', KEYS[1], ARGV[1] .. ':seq', seq) +redis.call('EXPIRE', KEYS[1], ARGV[6]) +redis.call('EXPIRE', KEYS[2], ARGV[6]) +return 1 +""" + + _REMOVE_FEEDBACK_SCRIPT = """ +local previous = redis.call('HGET', KEYS[1], ARGV[1]) +if previous ~= 'up' and previous ~= 'down' then + return 0 +end +redis.call('HDEL', KEYS[1], ARGV[1]) +redis.call('HINCRBY', KEYS[2], 'feedback_' .. previous, -1) +redis.call('EXPIRE', KEYS[1], ARGV[2]) +redis.call('EXPIRE', KEYS[2], ARGV[2]) return 1 """ @@ -542,6 +568,9 @@ def upsert_feedback( if not callable(evaluator): return None key = hashlib.sha256(f"{session_id}\x00{message_id}".encode("utf-8")).hexdigest() + # A blank comment is no comment: send an empty string so the + # script leaves any stored text untouched (issue #21). + text = comment.strip() if isinstance(comment, str) else "" changed = evaluator( self._UPSERT_FEEDBACK_SCRIPT, 2, @@ -549,7 +578,34 @@ def upsert_feedback( self.metrics_key, key, rating, - "1" if comment else "0", + text, + session_id, + message_id, + self.ttl_seconds, + ) + return bool(int(changed)) + except Exception as exc: + self._mark_unavailable(exc) + return None + + def remove_feedback( + self, + session_id: str, + message_id: str, + ) -> bool | None: + if not self.ensure_ready() or self.client is None: + return None + try: + evaluator = getattr(self.client, "eval", None) + if not callable(evaluator): + return None + key = hashlib.sha256(f"{session_id}\x00{message_id}".encode("utf-8")).hexdigest() + changed = evaluator( + self._REMOVE_FEEDBACK_SCRIPT, + 2, + self.metrics_feedback_key, + self.metrics_key, + key, self.ttl_seconds, ) return bool(int(changed)) @@ -557,6 +613,62 @@ def upsert_feedback( self._mark_unavailable(exc) return None + def list_feedback_comments(self) -> list[dict[str, Any]] | None: + """Return stored feedback comments, oldest update first. + + The feedback hash stores one record per message under its opaque + key: the rating itself, plus `:comment`, `:session_id`, + `:message_id` and `:seq` fields. Records without a comment are + not returned. + """ + if not self.ensure_ready() or self.client is None: + return None + try: + hgetall = getattr(self.client, "hgetall", None) + if not callable(hgetall): + return None + raw = hgetall(self.metrics_feedback_key) + if not raw: + return [] + values: dict[str, str] = {} + for key, value in raw.items(): + if isinstance(key, bytes): + key = key.decode("utf-8") + if isinstance(value, bytes): + value = value.decode("utf-8") + values[str(key)] = str(value) + records: dict[str, dict[str, Any]] = {} + for field, value in values.items(): + for suffix in (":comment", ":session_id", ":message_id", ":seq"): + if field.endswith(suffix): + records.setdefault(field[: -len(suffix)], {})[suffix[1:]] = value + break + else: + records.setdefault(field, {})["rating"] = value + comments: list[dict[str, Any]] = [] + for record in records.values(): + text = record.get("comment") + if not text: + continue + try: + seq = int(record.get("seq", 0)) + except (TypeError, ValueError): + seq = 0 + comments.append( + { + "session_id": str(record.get("session_id", "")), + "message_id": str(record.get("message_id", "")), + "rating": str(record.get("rating", "")), + "comment": str(text), + "seq": seq, + } + ) + comments.sort(key=lambda item: item["seq"]) + return comments + except Exception as exc: + self._mark_unavailable(exc) + return None + def metrics_snapshot(self) -> dict[str, Any] | None: if not self.ensure_ready() or self.client is None: return None 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..d7de655 100644 --- a/backend/app/llm.py +++ b/backend/app/llm.py @@ -33,6 +33,12 @@ def __init__( mode = os.getenv("MEDGUIDE_MODE", "production").strip().lower() self.local = mode == "local" self.required = mode not in {"offline", "test"} + # The local reasoning toggle is provider-specific: llama.cpp honours + # chat_template_kwargs.enable_thinking=false, while Ollama ignores + # it and needs reasoning_effort="none" (issue #1). An unknown + # provider fails closed at startup instead of silently sending the + # wrong toggle to the local model. + self.local_llm_provider = self._read_local_provider() if self.local else None configured_model = ( os.getenv("MEDGUIDE_LOCAL_LLM_MODEL", "") if self.local else (model if model is not None else os.getenv("OPENAI_MODEL", "")) @@ -192,6 +198,13 @@ def _read_max_tokens() -> int: except ValueError: return 1600 + @staticmethod + def _read_local_provider() -> str: + provider = os.getenv("MEDGUIDE_LOCAL_LLM_PROVIDER", "llama.cpp").strip().lower() + if provider not in {"llama.cpp", "ollama"}: + raise ValueError("MEDGUIDE_LOCAL_LLM_PROVIDER must be llama.cpp or ollama") + return provider + @staticmethod def _read_local_timeout() -> float: try: @@ -208,10 +221,15 @@ def _read_local_max_tokens() -> int: return 512 def _local_request_options(self) -> dict[str, Any]: - return ( - {"extra_body": {"chat_template_kwargs": {"enable_thinking": False}}} - if getattr(self, "local", False) else {} - ) + if not getattr(self, "local", False): + return {} + # Shared by the readiness probe and generate, so one provider + # choice covers both. Ollama ignores llama.cpp's thinking toggle + # and spends the probe budget on reasoning instead, leaving an + # empty message body (issue #1). + if getattr(self, "local_llm_provider", "llama.cpp") == "ollama": + return {"extra_body": {"reasoning_effort": "none"}} + return {"extra_body": {"chat_template_kwargs": {"enable_thinking": False}}} def generate(self, query: str, risk: str, context: str) -> str | None: if not self.ensure_ready(): @@ -291,7 +309,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 +350,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..7fd9bcd 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: @@ -704,6 +720,17 @@ def _state_for_request( if request.request_id: state["request_id"] = request.request_id state["_request_fingerprint"] = _message_fingerprint(request.message) + else: + # A previous turn may have persisted request_id/_request_fingerprint + # in the stored state. A request without request_id must not inherit + # them: both _run_chat_transaction and stream_chat.run_sync read the + # identifier from this state, and the fingerprint check would compare + # the new message against the previous turn's identifier and 409 + # every plain chat after an idempotent one (issue #22). The + # request_fingerprints/request_results tombstones are untouched, so + # idempotency itself is preserved. + state.pop("request_id", None) + state.pop("_request_fingerprint", None) return state @@ -1022,6 +1049,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, @@ -1340,6 +1395,91 @@ def feedback( } +@app.delete("/api/feedback") +def revoke_feedback( + http_request: Request, + session_id: str = Query(min_length=1), + message_id: str = Query(min_length=1, max_length=128), + authorization: str | None = Header(default=None), + api_key: str | None = Header(default=None, alias="X-API-Key"), +) -> dict[str, Any]: + current = get_services() + owner_id = _require_access( + current, + http_request, + authorization, + api_key, + _session_token_from_request(current, http_request), + ) + try: + state = current.store.get(session_id, owner_id=owner_id) + except SessionAuthorizationError as exc: + raise HTTPException(status_code=404, detail="会话不存在或已过期") from exc + except SessionBackendError as exc: + raise HTTPException(status_code=503, detail=str(exc)) from exc + if state is None: + raise HTTPException(status_code=404, detail="会话不存在或已过期") + if message_id not in state.get("response_ids", []): + raise HTTPException(status_code=422, detail="反馈目标不属于当前会话") + changed = current.metrics.remove_feedback( + message_id, + session_id=session_id, + ) + return { + "accepted": True, + "changed": changed, + "session_id": session_id, + "message_id": message_id, + } + + +@app.get("/api/feedback/comments") +def feedback_comments( + http_request: Request, + authorization: str | None = Header(default=None), + api_key: str | None = Header(default=None, alias="X-API-Key"), + session_id: str | None = None, +) -> dict[str, Any]: + """List stored feedback comments, oldest update first. + + Same authentication as POST /api/feedback. Only comments on sessions + owned by the caller are visible; a comment whose session has expired + is no longer listed. Comment text is never exposed through the + anonymous /api/metrics snapshot (issue #21). + """ + current = get_services() + owner_id = _require_access( + current, + http_request, + authorization, + api_key, + _session_token_from_request(current, http_request), + ) + if session_id is not None: + try: + state = current.store.get(session_id, owner_id=owner_id) + except SessionAuthorizationError as exc: + raise HTTPException(status_code=404, detail="会话不存在或已过期") from exc + except SessionBackendError as exc: + raise HTTPException(status_code=503, detail=str(exc)) from exc + if state is None: + raise HTTPException(status_code=404, detail="会话不存在或已过期") + visible: list[dict[str, Any]] = [] + for comment in current.metrics.feedback_comments(): + if session_id is not None and comment.get("session_id") != session_id: + continue + try: + state = current.store.get(str(comment.get("session_id") or ""), owner_id=owner_id) + except SessionAuthorizationError: + continue + except SessionBackendError as exc: + raise HTTPException(status_code=503, detail=str(exc)) from exc + if state is None: + continue + visible.append(comment) + return {"comments": visible, "count": len(visible)} + + @app.get("/api/metrics") def metrics( http_request: Request, diff --git a/backend/app/metrics.py b/backend/app/metrics.py index d809a97..68a4fd3 100644 --- a/backend/app/metrics.py +++ b/backend/app/metrics.py @@ -23,6 +23,11 @@ class MetricsStore: hallucinations: int = 0 feedback: Counter[str] = field(default_factory=Counter) feedback_by_message: dict[str, Literal["up", "down"]] = field(default_factory=dict) + # Latest comment text per feedback key (f"{session_id}:{message_id}"). + # Only messages that ever carried a non-blank comment get a record; the + # "commented" counter counts those records, not submissions. + _feedback_comments: dict[str, dict[str, Any]] = field(default_factory=dict, repr=False) + _feedback_seq: int = 0 backend: Any | None = field(default=None, repr=False, compare=False) _recorded_responses: set[str] = field(default_factory=set, repr=False) _lock: threading.Lock = field(default_factory=threading.Lock, repr=False) @@ -83,10 +88,14 @@ def add_feedback( *, session_id: str | None = None, ) -> bool: + # A blank comment is no comment: it is never stored, never counted + # and never makes a resubmission count as a change (issue #21). + text = comment.strip() if isinstance(comment, str) else None + text = text or None shared = getattr(self.backend, "upsert_feedback", None) if self.backend is not None else None if callable(shared) and message_id: try: - result = shared(session_id or "", message_id, rating, comment) + result = shared(session_id or "", message_id, rating, text) if result is not None: return bool(result) except Exception: @@ -96,18 +105,93 @@ def add_feedback( feedback_key = f"{session_id}:{message_id}" if session_id and message_id else message_id if feedback_key: previous = self.feedback_by_message.get(feedback_key) - if previous == rating: - return False + rating_changed = previous != rating + record = self._feedback_comments.get(feedback_key) if feedback_key else None + # Same rating + new comment text is a real change: the stored + # text is updated. Same rating + same (or no) comment is not. + comment_changed = bool(text) and (record is None or record.get("comment") != text) + if not rating_changed and not comment_changed: + return False + if rating_changed: 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 + if feedback_key: + self.feedback_by_message[feedback_key] = rating + self.feedback[rating] += 1 + if comment_changed and feedback_key: + if record is None: + # "commented" counts messages that ever carried a comment. + self.feedback["commented"] += 1 + self._feedback_seq += 1 + self._feedback_comments[feedback_key] = { + "session_id": session_id, + "message_id": message_id, + "rating": rating, + "comment": text, + "seq": self._feedback_seq, + } + elif record is not None and rating_changed: + # Keep the stored comment in step with the current rating. + record["rating"] = rating + self._feedback_seq += 1 + record["seq"] = self._feedback_seq return True + + def remove_feedback( + self, + message_id: str | None = None, + *, + session_id: str | None = None, + ) -> bool: + # Removing a vote only removes the rating itself. "commented" counts + # messages that once carried a comment, so a revoke does not decrement + # it; comment storage/readback belongs to issue #21, not this one. + shared = getattr(self.backend, "remove_feedback", None) if self.backend is not None else None + if callable(shared) and message_id: + try: + result = shared(session_id or "", message_id) + if result is not None: + return bool(result) + except Exception: + pass + with self._lock: + feedback_key = f"{session_id}:{message_id}" if session_id and message_id else message_id + if not feedback_key: + return False + previous = self.feedback_by_message.get(feedback_key) + if not previous: + return False + self.feedback[previous] -= 1 + if self.feedback[previous] <= 0: + self.feedback.pop(previous, None) + del self.feedback_by_message[feedback_key] + return True + + + def feedback_comments(self) -> list[dict[str, Any]]: + """Return every stored feedback comment, oldest update first. + + A shared backend owns the records when it is available; local + records are the fallback for the same outages `add_feedback` + already tolerates. + """ + shared = getattr(self.backend, "list_feedback_comments", None) if self.backend is not None else None + if callable(shared): + try: + result = shared() + if isinstance(result, list): + return [dict(item) for item in result if isinstance(item, Mapping)] + except Exception: + pass + with self._lock: + return sorted( + (dict(record) for record in self._feedback_comments.values()), + key=lambda record: int(record.get("seq", 0)), + ) + def snapshot(self) -> dict: shared = getattr(self.backend, "metrics_snapshot", None) if self.backend is not None else None if callable(shared): diff --git a/backend/app/models.py b/backend/app/models.py index 7ae75c6..4d2aa88 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 @@ -32,6 +38,10 @@ class WorkflowState(TypedDict, total=False): risk_history: list[dict[str, Any]] citations: list[dict[str, Any]] structured_result: dict[str, Any] | None + # True when a content search ran but no topical document matched, so + # the answer must state the knowledge-base boundary instead of + # presenting unrelated material (issue #2). + retrieval_insufficient: bool risk_advice: str rewritten_query: str response: str @@ -115,13 +125,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..9e7a6d8 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 @@ -15,10 +15,38 @@ from .ingestion import DocumentChunk, MedicalDocumentCleaner, load_catalog from .infra import _adapter_retry_delay, _adapter_timeout +# Tokens that name only a generic aspect of a complaint — pain in +# general, a duration, a severity, a generic noun — rather than a topic +# (a symptom, disease, body part, drug, exam or department). A citation +# justified by such tokens alone is not evidence that the document is +# about the user's question: "腿关节持续疼痛" used to cite the UTI +# document through "疼痛" alone, and "掉头发很严重" through "严重" +# (issue #2). Specific pains name a body part ("头痛", "胸痛", "腹痛", +# "腰痛", "关节痛", "咽痛") and are topics, not generic tokens. +GENERIC_MATCH_TOKENS: frozenset[str] = frozenset( + { + "疼痛", # pain in general + "持续", "多久", "几天", "时间", # duration words + "严重", # severity word + "症状", "问题", # generic nouns + "怎么办", "怎么", # question words + "难受", "不舒服", # generic feeling words + "担心", # emotion word + } +) + 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 +60,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 +214,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 +272,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 +323,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 +360,25 @@ 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" + + # A citation must share at least one topical token with the query. + # Generic descriptors alone cannot justify one (see + # GENERIC_MATCH_TOKENS). A pure score floor cannot do this job: + # the false UTI match for "腿关节持续疼痛" scored higher (fused + # 0.55) than a genuine one ("感冒了怎么办", 0.50), so the gate is + # on which tokens match, not on the score. This also covers + # remote vector hits, whose scores alone say nothing about topic. + query_meaningful = meaningful_tokens(query) + candidates_by_id = { + chunk_id: candidate + for chunk_id, candidate in candidates_by_id.items() + if (query_meaningful & BM25Index._chunk_meaningful_tokens(candidate["chunk"])) + - GENERIC_MATCH_TOKENS + } candidates: list[tuple[float, float, float, DocumentChunk]] = [] for candidate in candidates_by_id.values(): @@ -287,7 +388,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 +461,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..a22e204 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:] @@ -618,6 +712,7 @@ def risk(self, state: WorkflowState) -> WorkflowState: def retrieve(self, state: WorkflowState) -> WorkflowState: intent = state.get("intent", "unknown") + state["retrieval_insufficient"] = False if intent in ("structured",) or state.get("risk_level") == "high": state["citations"] = [] return state @@ -634,6 +729,10 @@ def retrieve(self, state: WorkflowState) -> WorkflowState: query = ";".join(focused) state["rewritten_query"] = query state["citations"] = [citation.as_dict() for citation in self.retriever.search(query, intent, top_k=4)] + state["retrieval_insufficient"] = bool( + intent in ("disease", "drug", "exam", "department", "faq") + and not state["citations"] + ) return state def structured_query(self, state: WorkflowState) -> WorkflowState: @@ -669,6 +768,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"): @@ -702,6 +807,18 @@ def draft(self, state: WorkflowState) -> WorkflowState: response = f"根据当前知识库,和你描述最相关的资料是“{citations[0]['title']}”:{lead}" response += "\n\n这只是基于有限信息的健康信息整理,不代表诊断。若症状持续、加重或影响日常活动,建议预约线下医生。" state["answer_source"] = "retrieval-template" + elif state.get("retrieval_insufficient"): + # No topical document matched: say so plainly instead of + # padding the answer with unrelated material (issue #2). + # The generic care-seeking advice below is not a diagnosis + # for the user's complaint. + response = ( + "当前知识库中没有与你描述的情况直接相关的资料,我无法据此给出针对性的信息整理。" + "这不代表没有问题,只是说明现有资料覆盖不到这个主题。" + "一般建议:如果症状持续、加重或影响日常活动,请及时到线下医疗机构就诊;" + "如出现胸痛、呼吸困难、意识改变等情况,请立即就医。" + ) + state["answer_source"] = "insufficient-data" else: response = "我还缺少足够的背景信息来给出可靠的分流建议。请补充年龄、症状持续多久,以及是否伴随发热、疼痛加重或呼吸困难。" state["answer_source"] = "clarification-template" @@ -709,6 +826,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 +856,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 +884,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 +892,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 +908,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 +934,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 +993,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/docker-entrypoint.sh b/backend/docker-entrypoint.sh index 40d1b29..2acfdd2 100644 --- a/backend/docker-entrypoint.sh +++ b/backend/docker-entrypoint.sh @@ -4,6 +4,61 @@ set -eu knowledge_backend="${MEDGUIDE_KNOWLEDGE_BACKEND:-milvus}" index_path="${BM25_INDEX_PATH:-/app/data/runtime/bm25-index.json}" +# Production deployments need external services that /api/ready would +# otherwise only report as missing: without them the API stays up but +# never becomes ready, so the UI (depends_on: service_healthy) and the +# gateway never start and the whole stack sits unhealthy with no clear +# error. Fail here, before ingestion and before the server starts, +# naming every missing variable (issue #20). This is deliberately an +# entrypoint check and not a ${VAR:?} interpolation in docker-compose.yml: +# MILVUS_URI is only required for the milvus backend, the auth database +# has an explicit SQLite escape hatch, and CI runs `docker compose config` +# with no environment set, so compose-level interception cannot express +# the conditions and would break validation. Local/offline/test modes are +# unaffected: they use their own providers and never reach this branch. +mode="$(printf '%s' "${MEDGUIDE_MODE:-production}" | tr '[:upper:]' '[:lower:]')" +if [ "$mode" = "production" ]; then + python - <<'PY' +import os + +missing: list[tuple[str, str]] = [] + + +def _present(name: str) -> bool: + return bool((os.environ.get(name) or "").strip()) + + +def _truthy(name: str) -> bool: + return (os.environ.get(name) or "").strip().lower() in {"1", "true", "yes", "on"} + + +if not _present("OPENAI_API_KEY"): + missing.append(("OPENAI_API_KEY", "the OpenAI answerer has no credential")) +if not _present("OPENAI_MODEL"): + missing.append(("OPENAI_MODEL", "model selection is part of the production provider contract")) +if not _present("REDIS_URL"): + missing.append(("REDIS_URL", "sessions, idempotency and metrics need Redis in production")) +backend = (os.environ.get("MEDGUIDE_KNOWLEDGE_BACKEND") or "").strip().lower() or "milvus" +if backend == "milvus" and not _present("MILVUS_URI"): + missing.append(("MILVUS_URI", "the milvus knowledge backend needs a vector store address")) +auth_backend = (os.environ.get("MEDGUIDE_AUTH_BACKEND") or "mysql").strip().lower() +sqlite_auth_allowed = auth_backend == "sqlite" and _truthy("MEDGUIDE_ALLOW_SQLITE_AUTH") +if not _present("MEDGUIDE_AUTH_DSN") and not sqlite_auth_allowed: + missing.append(( + "MEDGUIDE_AUTH_DSN", + "the shared auth database is required when MEDGUIDE_AUTH_BACKEND=mysql; " + "set MEDGUIDE_AUTH_BACKEND=sqlite and MEDGUIDE_ALLOW_SQLITE_AUTH=true " + "to use the explicit single-node SQLite auth instead", + )) + +if missing: + lines = ["MedGuide production deployment is missing required configuration:"] + lines.extend(f" - {name}: {reason}" for name, reason in missing) + lines.append("Set the missing variables in .env (see .env.template) and re-run `docker compose up --build -d`.") + raise SystemExit("\n".join(lines)) +PY +fi + # The API receives forwarded HTTPS headers from the UI container. In the # Compose topology that container lives inside MEDGUIDE_NETWORK_SUBNET, so a # missing, empty, malformed, or drifting trust boundary must fail before the 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_deployment_contracts.py b/backend/tests/test_deployment_contracts.py index 6d36c42..00441a8 100644 --- a/backend/tests/test_deployment_contracts.py +++ b/backend/tests/test_deployment_contracts.py @@ -148,6 +148,117 @@ def test_docker_context_excludes_local_dependencies_and_runtime_artifacts() -> N assert ".env.*" in dockerignore and "!.env.template" in dockerignore +def _run_api_entrypoint(environment: dict[str, str], tmp_path: Path) -> subprocess.CompletedProcess[str]: + """Run the real API entrypoint with a controlled environment. + + The command under test is ``true`` so a successful run proves the + pre-flight checks passed; the knowledge backend is ``disabled`` in + passing cases so the run never reaches the ingestion/index branches + that need a container filesystem and network. The environment is + built from scratch so ambient developer variables cannot mask a + missing-dependency case. + """ + bin_dir = tmp_path / "bin" + bin_dir.mkdir(exist_ok=True) + python_link = bin_dir / "python" + if not python_link.exists(): + python_link.symlink_to(sys.executable) + env = { + "PATH": f"{bin_dir}{os.pathsep}{os.environ.get('PATH', '')}", + "MEDGUIDE_MODE": "production", + "MEDGUIDE_NETWORK_SUBNET": "172.30.0.0/16", + "MEDGUIDE_API_TRUSTED_PROXY_CIDR": "172.30.0.0/16", + "BM25_INDEX_PATH": str(tmp_path / "bm25-index.json"), + "MEDGUIDE_KNOWLEDGE_BACKEND": "disabled", + } + env.update(environment) + return subprocess.run( + ["sh", str(ROOT / "backend" / "docker-entrypoint.sh"), "true"], + env=env, + capture_output=True, + text=True, + encoding="utf-8", + timeout=60, + ) + + +_PRODUCTION_DEPENDENCIES = { + "OPENAI_API_KEY": "test-key", + "OPENAI_MODEL": "test-model", + "REDIS_URL": "redis://127.0.0.1:6379/0", + "MEDGUIDE_AUTH_DSN": "mysql://user:pass@127.0.0.1:3306/medguide", + "MILVUS_URI": "http://127.0.0.1:19530", +} + + +def test_production_entrypoint_fails_fast_on_missing_dependencies(tmp_path: Path) -> None: + """Issue #20: a missing production dependency must fail at startup, + naming the variable, instead of leaving the stack permanently + unhealthy behind a 503 /api/ready.""" + entrypoint = (ROOT / "backend" / "docker-entrypoint.sh").read_text(encoding="utf-8") + assert "MedGuide production deployment is missing required configuration" in entrypoint + assert 'if backend == "milvus"' in entrypoint + assert "MEDGUIDE_ALLOW_SQLITE_AUTH" in entrypoint + + for variable in ("OPENAI_API_KEY", "OPENAI_MODEL", "REDIS_URL", "MEDGUIDE_AUTH_DSN"): + environment = dict(_PRODUCTION_DEPENDENCIES) + del environment[variable] + completed = _run_api_entrypoint(environment, tmp_path) + assert completed.returncode != 0 + assert variable in completed.stderr + assert "Set the missing variables in .env" in completed.stderr + + +def test_production_entrypoint_requires_milvus_uri_only_for_milvus_backend(tmp_path: Path) -> None: + environment = dict(_PRODUCTION_DEPENDENCIES) + del environment["MILVUS_URI"] + environment["MEDGUIDE_KNOWLEDGE_BACKEND"] = "milvus" + completed = _run_api_entrypoint(environment, tmp_path) + assert completed.returncode != 0 + assert "MILVUS_URI" in completed.stderr + + # A non-milvus backend must not demand MILVUS_URI: the disabled backend + # reaches `exec "$@"` here, which proves the check passed. + environment["MEDGUIDE_KNOWLEDGE_BACKEND"] = "disabled" + completed = _run_api_entrypoint(environment, tmp_path) + assert completed.returncode == 0 + assert completed.stderr == "" + + +def test_production_entrypoint_accepts_explicit_sqlite_auth(tmp_path: Path) -> None: + environment = dict(_PRODUCTION_DEPENDENCIES) + del environment["MEDGUIDE_AUTH_DSN"] + completed = _run_api_entrypoint(environment, tmp_path) + assert completed.returncode != 0 + assert "MEDGUIDE_AUTH_DSN" in completed.stderr + + environment["MEDGUIDE_AUTH_BACKEND"] = "sqlite" + environment["MEDGUIDE_ALLOW_SQLITE_AUTH"] = "true" + completed = _run_api_entrypoint(environment, tmp_path) + assert completed.returncode == 0 + + # Opting into SQLite auth needs the explicit flag; the backend alone + # is not enough. + del environment["MEDGUIDE_ALLOW_SQLITE_AUTH"] + completed = _run_api_entrypoint(environment, tmp_path) + assert completed.returncode != 0 + assert "MEDGUIDE_AUTH_DSN" in completed.stderr + + +def test_production_entrypoint_passes_when_dependencies_are_set(tmp_path: Path) -> None: + completed = _run_api_entrypoint(dict(_PRODUCTION_DEPENDENCIES), tmp_path) + assert completed.returncode == 0 + assert completed.stderr == "" + + # The check is production-only: test mode with nothing configured + # must reach the command instead of failing on production variables. + completed = _run_api_entrypoint( + {"MEDGUIDE_MODE": "test", "MEDGUIDE_KNOWLEDGE_BACKEND": "disabled"}, + tmp_path, + ) + assert completed.returncode == 0 + + def test_browser_deployment_is_same_origin_and_cookie_authenticated() -> None: app = (ROOT / "frontend" / "src" / "App.tsx").read_text(encoding="utf-8") index = (ROOT / "frontend" / "index.html").read_text(encoding="utf-8") 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_feedback_change_vote.py b/backend/tests/test_feedback_change_vote.py new file mode 100644 index 0000000..20d0b75 --- /dev/null +++ b/backend/tests/test_feedback_change_vote.py @@ -0,0 +1,130 @@ +"""Issue #19: a recorded vote can be changed and revoked. + +Change-vote already worked on the backend (``add_feedback`` upserts per +message); the frontend blocked it. Revoking had no backend semantics at +all, so ``DELETE /api/feedback`` is new here. The frontend change is +covered by ``frontend/tests/feedback-vote.test.mjs``. +""" +from fastapi.testclient import TestClient + +from app.main import app +from app.metrics import MetricsStore +from conftest import login_client + + +def _answer(client: TestClient, request_id: str) -> tuple[str, str]: + # Issue #6: /api/sessions requires a session in every mode. + login_client(client, "feedback_change_vote_user") + session_id = client.post("/api/sessions").json()["session_id"] + answer = client.post( + "/api/chat", + json={"session_id": session_id, "message": "我咳嗽", "request_id": request_id}, + ).json() + return session_id, answer["response_id"] + + +def _vote(client: TestClient, session_id: str, message_id: str, rating: str) -> dict: + response = client.post( + "/api/feedback", + json={"session_id": session_id, "message_id": message_id, "rating": rating}, + ) + assert response.status_code == 200 + return response.json() + + +def _revoke(client: TestClient, session_id: str, message_id: str): + return client.delete( + "/api/feedback", params={"session_id": session_id, "message_id": message_id} + ) + + +def _feedback(client: TestClient) -> dict: + return client.get("/api/metrics").json()["feedback"] + + +def test_change_vote_moves_counts_instead_of_adding_a_second_vote() -> None: + with TestClient(app) as client: + session_id, message_id = _answer(client, "turn-vote-change-0001") + first = _vote(client, session_id, message_id, "up") + changed = _vote(client, session_id, message_id, "down") + metrics = client.get("/api/metrics").json() + + assert first["changed"] is True + assert changed["changed"] is True + assert _feedback(client) == {"down": 1} + assert metrics["feedback_by_message"] == {f"{session_id}:{message_id}": "down"} + + +def test_repeat_same_rating_does_not_count_twice() -> None: + with TestClient(app) as client: + session_id, message_id = _answer(client, "turn-vote-repeat-0001") + first = _vote(client, session_id, message_id, "up") + duplicate = _vote(client, session_id, message_id, "up") + + assert first["changed"] is True + assert duplicate["changed"] is False + assert _feedback(client) == {"up": 1} + + +def test_revoke_removes_the_vote_and_a_second_revoke_changes_nothing() -> None: + with TestClient(app) as client: + session_id, message_id = _answer(client, "turn-vote-revoke-0001") + _vote(client, session_id, message_id, "up") + first = _revoke(client, session_id, message_id) + second = _revoke(client, session_id, message_id) + metrics = client.get("/api/metrics").json() + + assert first.status_code == 200 + assert first.json()["changed"] is True + assert second.status_code == 200 + assert second.json()["changed"] is False + assert _feedback(client) == {} + assert metrics["feedback_by_message"] == {} + + +def test_revoke_without_a_vote_changes_nothing() -> None: + with TestClient(app) as client: + session_id, message_id = _answer(client, "turn-vote-revoke-0002") + response = _revoke(client, session_id, message_id) + + assert response.status_code == 200 + assert response.json()["changed"] is False + assert _feedback(client) == {} + + +def test_vote_again_after_revoke_counts_as_a_new_vote() -> None: + with TestClient(app) as client: + session_id, message_id = _answer(client, "turn-vote-revoke-0003") + _vote(client, session_id, message_id, "up") + _revoke(client, session_id, message_id) + again = _vote(client, session_id, message_id, "down") + + assert again["changed"] is True + assert _feedback(client) == {"down": 1} + + +def test_revoke_rejects_unknown_session_and_foreign_message() -> None: + with TestClient(app) as client: + session_id, message_id = _answer(client, "turn-vote-revoke-0004") + unknown_session = _revoke(client, "missing-session", message_id) + foreign_message = _revoke(client, session_id, "other-session:turn:1") + missing_params = client.delete("/api/feedback", params={"session_id": session_id}) + + assert unknown_session.status_code == 404 + assert foreign_message.status_code == 422 + assert missing_params.status_code == 422 + + +def test_remove_feedback_unit_in_memory() -> None: + store = MetricsStore() + assert store.remove_feedback("message-1", session_id="session-1") is False + assert store.add_feedback("up", None, "message-1", session_id="session-1") is True + assert store.add_feedback("up", "写得很清楚", "message-2", session_id="session-1") is True + assert store.snapshot()["feedback"] == {"up": 2, "commented": 1} + + assert store.remove_feedback("message-1", session_id="session-1") is True + assert store.snapshot()["feedback"] == {"up": 1, "commented": 1} + # A revoke removes the rating only; "commented" counts messages that + # once carried a comment, and comment semantics belong to issue #21. + assert store.remove_feedback("message-1", session_id="session-1") is False + assert store.remove_feedback("message-2", session_id="other-session") is False diff --git a/backend/tests/test_feedback_comments.py b/backend/tests/test_feedback_comments.py new file mode 100644 index 0000000..c3aaa54 --- /dev/null +++ b/backend/tests/test_feedback_comments.py @@ -0,0 +1,245 @@ +"""Issue #21: feedback comments must be stored and readable. + +On main, a submitted comment was only ever used as a boolean: the text +was discarded, a same-rating resubmission carrying a new comment came +back `changed:false`, and no endpoint could read the text back. The fix +stores the latest comment per message (in-memory and Redis) and exposes +it through GET /api/feedback/comments with the same authentication as +POST /api/feedback. +""" +from __future__ import annotations + +from types import SimpleNamespace + +import pytest +from fastapi.testclient import TestClient + +import app.main as main_module +from app.auth import AuthStore +from app.main import app +from app.metrics import MetricsStore +from app.store import SessionStore +from conftest import login_client + +PASSWORD = "Correct-Horse-42" + +# Issue #6: the feedback endpoints require an authenticated session, so +# tests that seed a session directly must log in as its owner first. +COMMENT_USER = "comment_user" + + +def _login(client) -> None: + assert client.post( + "/api/auth/register", json={"username": COMMENT_USER, "password": PASSWORD} + ).status_code == 201 + + +def _services(tmp_path): + """Isolated offline services: fresh auth/store/metrics per test.""" + return SimpleNamespace( + production=False, + mode="offline", + local=False, + api_tokens=(), + production_missing=(), + auth=AuthStore( + tmp_path / "auth.sqlite3", + session_ttl_seconds=300, + cookie_secure=False, + password_iterations=100_000, + ), + store=SessionStore(mode="offline"), + metrics=MetricsStore(), + ) + + +@pytest.fixture +def services(tmp_path, monkeypatch): + current = _services(tmp_path) + monkeypatch.setattr(main_module, "get_services", lambda: current) + return current + + +def _client() -> TestClient: + return TestClient(app, base_url="https://testserver") + + +def _seed_session(services, owner_id=None, response_ids=("resp-1", "resp-2")): + state = services.store.create(owner_id=owner_id) + state["response_ids"] = list(response_ids) + return services.store.save(state) + + +def _post_feedback(client, session_id, message_id, rating, comment=None): + payload = {"session_id": session_id, "message_id": message_id, "rating": rating} + if comment is not None: + payload["comment"] = comment + return client.post("/api/feedback", json=payload) + + +def test_submit_comment_then_read_back(services) -> None: + state = _seed_session(services, owner_id=f"user:{COMMENT_USER}") + session_id = state["session_id"] + with _client() as client: + _login(client) + posted = _post_feedback(client, session_id, "resp-1", "up", "回答很清楚,谢谢") + assert posted.status_code == 200 + assert posted.json()["changed"] is True + + listed = client.get("/api/feedback/comments") + assert listed.status_code == 200 + body = listed.json() + assert body["count"] == 1 + assert body["comments"] == [ + { + "session_id": session_id, + "message_id": "resp-1", + "rating": "up", + "comment": "回答很清楚,谢谢", + "seq": 1, + } + ] + # The metrics snapshot keeps counting; the text lives only in the + # comments endpoint, never in the anonymous /api/metrics snapshot. + assert services.metrics.snapshot()["feedback"].get("commented") == 1 + assert "回答很清楚" not in str(services.metrics.snapshot()) + + +def test_same_rating_new_comment_is_change_and_updates_text(services) -> None: + state = _seed_session(services, owner_id=f"user:{COMMENT_USER}") + session_id = state["session_id"] + with _client() as client: + _login(client) + assert _post_feedback(client, session_id, "resp-1", "up", "第一版评价").json()["changed"] is True + second = _post_feedback(client, session_id, "resp-1", "up", "补充一点:希望更简短") + assert second.status_code == 200 + assert second.json()["changed"] is True + + listed = client.get("/api/feedback/comments").json() + assert listed["count"] == 1 + assert listed["comments"][0]["comment"] == "补充一点:希望更简短" + # One message ever carried a comment: still counted once. + assert services.metrics.snapshot()["feedback"].get("commented") == 1 + + +def test_same_rating_same_comment_is_not_change(services) -> None: + state = _seed_session(services, owner_id=f"user:{COMMENT_USER}") + session_id = state["session_id"] + with _client() as client: + _login(client) + assert _post_feedback(client, session_id, "resp-1", "up", "很好").json()["changed"] is True + again = _post_feedback(client, session_id, "resp-1", "up", "很好") + assert again.json()["changed"] is False + assert client.get("/api/feedback/comments").json()["count"] == 1 + + +def test_rating_change_keeps_comment(services) -> None: + state = _seed_session(services, owner_id=f"user:{COMMENT_USER}") + session_id = state["session_id"] + with _client() as client: + _login(client) + _post_feedback(client, session_id, "resp-1", "up", "一开始觉得有用") + changed = _post_feedback(client, session_id, "resp-1", "down") + assert changed.json()["changed"] is True + listed = client.get("/api/feedback/comments").json() + assert listed["count"] == 1 + assert listed["comments"][0]["comment"] == "一开始觉得有用" + assert listed["comments"][0]["rating"] == "down" + # The message once carried a comment: the count stays. + assert services.metrics.snapshot()["feedback"].get("commented") == 1 + + +def test_blank_comment_is_not_stored_or_counted(services) -> None: + state = _seed_session(services, owner_id=f"user:{COMMENT_USER}") + session_id = state["session_id"] + with _client() as client: + _login(client) + for blank in ("", " ", "\n\t "): + response = _post_feedback(client, session_id, "resp-1", "up", blank) + assert response.status_code == 200 + assert client.get("/api/feedback/comments").json() == {"comments": [], "count": 0} + assert "commented" not in services.metrics.snapshot()["feedback"] + + # A blank resubmission must not clear a stored comment either. + _post_feedback(client, session_id, "resp-2", "down", "确实有问题") + assert _post_feedback(client, session_id, "resp-2", "down", " ").json()["changed"] is False + listed = client.get("/api/feedback/comments").json() + assert listed["count"] == 1 + assert listed["comments"][0]["comment"] == "确实有问题" + + +def test_comment_over_500_chars_is_rejected(services) -> None: + state = _seed_session(services, owner_id=f"user:{COMMENT_USER}") + with _client() as client: + _login(client) + response = _post_feedback(client, state["session_id"], "resp-1", "up", "x" * 501) + assert response.status_code == 422 + assert client.get("/api/feedback/comments").json() == {"comments": [], "count": 0} + + +def test_read_with_invalid_cookie_is_401(services) -> None: + _seed_session(services) + with _client() as client: + client.cookies.set("medguide_session", "invalid-token") + assert client.get("/api/feedback/comments").status_code == 401 + # Same authentication as the POST endpoint. + assert client.post( + "/api/feedback", + json={"session_id": "nope", "message_id": "resp-1", "rating": "up"}, + ).status_code == 401 + + +def test_comments_are_scoped_to_owner(services) -> None: + alice = _client() + bob = _client() + try: + assert alice.post( + "/api/auth/register", json={"username": "alice_comment", "password": PASSWORD} + ).status_code == 201 + assert bob.post( + "/api/auth/register", json={"username": "bob_comment", "password": PASSWORD} + ).status_code == 201 + + created = alice.post("/api/sessions") + assert created.status_code == 200 + session_id = created.json()["session_id"] + assert services.store.get(session_id)["owner_id"] == "user:alice_comment" + + state = services.store.get(session_id) + state["response_ids"] = ["resp-1"] + services.store.save(state) + assert _post_feedback(alice, session_id, "resp-1", "up", "只给 Alice 看").json()["changed"] is True + + assert alice.get("/api/feedback/comments").json()["count"] == 1 + assert bob.get("/api/feedback/comments").json() == {"comments": [], "count": 0} + # Scoping to one session: the owner sees it, anyone else gets 404. + assert alice.get("/api/feedback/comments", params={"session_id": session_id}).json()["count"] == 1 + assert bob.get("/api/feedback/comments", params={"session_id": session_id}).status_code == 404 + assert alice.get("/api/feedback/comments", params={"session_id": "missing"}).status_code == 404 + finally: + alice.close() + bob.close() + + +def test_end_to_end_chat_feedback_comment_read_back() -> None: + """Real app wiring: chat -> feedback with comment -> read it back.""" + with TestClient(app, base_url="https://testserver") as client: + # Issue #6: session creation requires a login in every mode. + login_client(client, "feedback_comments_e2e_user") + created = client.post("/api/sessions") + assert created.status_code == 200 + session_id = created.json()["session_id"] + response = client.post("/api/chat", json={"session_id": session_id, "message": "我32岁,咳嗽持续3天"}) + assert response.status_code == 200 + response_id = response.json()["response_id"] + + posted = client.post( + "/api/feedback", + json={"session_id": session_id, "message_id": response_id, "rating": "up", "comment": "清楚"}, + ) + assert posted.status_code == 200 + listed = client.get("/api/feedback/comments", params={"session_id": session_id}) + assert listed.status_code == 200 + assert listed.json()["count"] == 1 + assert listed.json()["comments"][0]["comment"] == "清楚" + assert listed.json()["comments"][0]["message_id"] == response_id 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_leg_pain_citation.py b/backend/tests/test_leg_pain_citation.py new file mode 100644 index 0000000..5889521 --- /dev/null +++ b/backend/tests/test_leg_pain_citation.py @@ -0,0 +1,88 @@ +"""Issue #2: leg/joint pain must not cite UTI material. + +Root cause: BM25 matched the UTI document through the generic token +"疼痛" alone (and cold/cough/diarrhoea documents through "持续"), so a +question about a topic the knowledge base does not cover was answered +with unrelated material presented as the most relevant source. +""" +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 _ids(result: dict) -> list[str]: + return [item["id"] for item in result.get("citations", [])] + + +# --- retrieval level: generic-only matches must not become citations --- + +def test_leg_pain_queries_return_no_citations() -> None: + retriever = HybridRetriever() + assert retriever.search("腿关节持续疼痛", "disease") == [] + assert retriever.search("腿关节时长疼痛", "disease") == [] + assert retriever.search("膝盖疼了几天", "disease") == [] + + +def test_severity_only_query_returns_no_citations() -> None: + # "严重" alone justified citing the loratadine/emergency documents. + assert HybridRetriever().search("掉头发很严重", "unknown") == [] + + +def test_urinary_query_still_retrieves_uti_document() -> None: + results = HybridRetriever().search("尿频尿急并伴排尿疼痛", "disease") + assert results + assert results[0].id.startswith("disease-uti-001") + + +def test_topical_queries_are_unaffected_by_the_gate() -> None: + retriever = HybridRetriever() + assert retriever.search("咳嗽", "disease")[0].id.startswith("disease-cough-001") + assert retriever.search("头痛", "disease")[0].id.startswith("disease-headache-001") + # "发烧" is only matched through the temperature token today; the gate + # must not take that citation away. + assert retriever.search("发烧38.5度三天", "unknown")[0].id.startswith("disease-fever-001") + + +# --- workflow level: no UTI citation, explicit data boundary --- + +def test_leg_pain_answer_states_insufficient_data() -> None: + result = make_workflow().run( + {"session_id": "leg-pain", "user_message": "腿关节持续疼痛", "profile": {}} + ) + assert not any(item.startswith("disease-uti-001") for item in _ids(result)) + assert result["answer_source"] == "insufficient-data" + assert "没有与你描述的情况直接相关的资料" in result["response"] + assert "尿路感染" not in result["response"] + assert "尿频" not in result["response"] + + +def test_knee_pain_answer_states_insufficient_data() -> None: + result = make_workflow().run( + {"session_id": "knee-pain", "user_message": "膝盖疼了几天", "profile": {}} + ) + assert result["citations"] == [] + assert result["answer_source"] == "insufficient-data" + assert "没有与你描述的情况直接相关的资料" in result["response"] + assert "尿路感染" not in result["response"] + + +def test_urinary_query_workflow_still_cites_uti() -> None: + result = make_workflow().run( + {"session_id": "uti", "user_message": "尿频尿急并伴排尿疼痛", "profile": {}} + ) + assert any(item.startswith("disease-uti-001") for item in _ids(result)) + assert result["answer_source"] != "insufficient-data" + assert "尿路感染" in result["response"] + + +def test_cough_workflow_still_cites_cough_document() -> None: + result = make_workflow().run( + {"session_id": "cough", "user_message": "咳嗽", "profile": {}} + ) + assert any(item.startswith("disease-cough-001") for item in _ids(result)) + assert result["answer_source"] != "insufficient-data" diff --git a/backend/tests/test_local_mode.py b/backend/tests/test_local_mode.py index fd0aa06..4129171 100644 --- a/backend/tests/test_local_mode.py +++ b/backend/tests/test_local_mode.py @@ -51,6 +51,7 @@ def local_environment(monkeypatch, tmp_path: Path) -> Path: monkeypatch.delenv("MEDGUIDE_KNOWLEDGE_BACKEND", raising=False) monkeypatch.delenv("MEDGUIDE_LOCAL_LLM_TIMEOUT_SECONDS", raising=False) monkeypatch.delenv("MEDGUIDE_LOCAL_LLM_MAX_TOKENS", raising=False) + monkeypatch.delenv("MEDGUIDE_LOCAL_LLM_PROVIDER", raising=False) monkeypatch.delenv("MEDGUIDE_API_TRUSTED_PROXY_CIDR", raising=False) monkeypatch.delenv("MEDGUIDE_TRUSTED_PROXY_CIDR", raising=False) path = tmp_path / "bm25-index.json" @@ -61,9 +62,17 @@ def local_environment(monkeypatch, tmp_path: Path) -> Path: return path +@pytest.mark.parametrize("provider,expected_reasoning,forbidden_reasoning", [ + (None, {"chat_template_kwargs": {"enable_thinking": False}}, "reasoning_effort"), + ("llama.cpp", {"chat_template_kwargs": {"enable_thinking": False}}, "reasoning_effort"), + ("Ollama ", {"reasoning_effort": "none"}, "chat_template_kwargs"), + ("OLLAMA", {"reasoning_effort": "none"}, "chat_template_kwargs"), +]) def test_local_sdk_isolates_credentials_proxies_redirects_and_request_settings( - local_environment, monkeypatch, + local_environment, monkeypatch, provider, expected_reasoning, forbidden_reasoning, ) -> None: + if provider is not None: + monkeypatch.setenv("MEDGUIDE_LOCAL_LLM_PROVIDER", provider) for name, value in { "OPENAI_API_KEY": "external-synthetic-key", "OPENAI_MODEL": "external-model", "OPENAI_CHAT_BASE_URL": "https://external.example/v1", "OPENAI_BASE_URL": "https://other.example/v1", @@ -109,13 +118,25 @@ def __init__(self, **kwargs): assert request.headers.get("openai-project") != "external-project" body = json.loads(request.content) assert body["model"] == "medguide-local-qwen3-1.7b" - assert body["chat_template_kwargs"] == {"enable_thinking": False} + # The probe and generate requests share _local_request_options, + # so both must carry the provider's reasoning toggle and none + # of the other provider's toggle. + for key, value in expected_reasoning.items(): + assert body[key] == value + assert forbidden_reasoning not in body assert json.loads(requests[0].content)["max_tokens"] == 16 assert json.loads(requests[1].content)["max_tokens"] == 512 finally: answerer.close() +@pytest.mark.parametrize("value", ["openai", "vllm", "llama", "", "ollama2"]) +def test_local_unknown_provider_fails_closed(local_environment, monkeypatch, value) -> None: + monkeypatch.setenv("MEDGUIDE_LOCAL_LLM_PROVIDER", value) + with pytest.raises(ValueError, match="MEDGUIDE_LOCAL_LLM_PROVIDER must be llama.cpp or ollama"): + OpenAIAnswerer() + + @pytest.mark.parametrize("missing", ["MEDGUIDE_LOCAL_LLM_MODEL", "MEDGUIDE_LOCAL_LLM_BASE_URL"]) def test_local_missing_configuration_never_falls_back_to_openai(local_environment, monkeypatch, missing) -> None: monkeypatch.delenv(missing) @@ -274,7 +295,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..056df07 100644 --- a/backend/tests/test_redis_atomicity.py +++ b/backend/tests/test_redis_atomicity.py @@ -46,6 +46,8 @@ def eval(self, script: str, number_of_keys: int, *items): return self._release_request(keys, args) if script == RedisSessionAdapter._UPSERT_FEEDBACK_SCRIPT: return self._upsert_feedback(keys, args) + if script == RedisSessionAdapter._REMOVE_FEEDBACK_SCRIPT: + return self._remove_feedback(keys, args) if script == RedisSessionAdapter._RECORD_METRICS_SCRIPT: return self._record_metrics(keys, args) raise AssertionError("unexpected Lua script") @@ -112,20 +114,43 @@ def _release_request(self, keys, args): def _upsert_feedback(self, keys, args): feedback_key, metrics_key = keys - field, rating, commented, _ttl = args + field, rating, comment, session_id, message_id, _ttl = args feedback = self.hashes.setdefault(feedback_key, {}) metrics = self.hashes.setdefault(metrics_key, {}) previous = feedback.get(field) - if previous == rating: + stored_comment = feedback.get(f"{field}:comment") + comment_changed = bool(comment) and stored_comment != comment + if previous == rating and not comment_changed: return 0 if previous in {"up", "down"}: - old_key = f"feedback_{previous}" - metrics[old_key] = int(metrics.get(old_key, 0)) - 1 + if previous != rating: + old_key = f"feedback_{previous}" + metrics[old_key] = int(metrics.get(old_key, 0)) - 1 + metrics[f"feedback_{rating}"] = int(metrics.get(f"feedback_{rating}", 0)) + 1 + else: + metrics[f"feedback_{rating}"] = int(metrics.get(f"feedback_{rating}", 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 + if comment_changed: + feedback[f"{field}:comment"] = comment + feedback[f"{field}:session_id"] = session_id + feedback[f"{field}:message_id"] = message_id + if not stored_comment: + metrics["feedback_commented"] = int(metrics.get("feedback_commented", 0)) + 1 + metrics["feedback_comment_seq"] = int(metrics.get("feedback_comment_seq", 0)) + 1 + feedback[f"{field}:seq"] = metrics["feedback_comment_seq"] + return 1 + + def _remove_feedback(self, keys, args): + feedback_key, metrics_key = keys + field, _ttl = args + feedback = self.hashes.setdefault(feedback_key, {}) + metrics = self.hashes.setdefault(metrics_key, {}) + previous = feedback.get(field) + if previous not in {"up", "down"}: + return 0 + del feedback[field] + old_key = f"feedback_{previous}" + metrics[old_key] = int(metrics.get(old_key, 0)) - 1 return 1 def _record_metrics(self, keys, args): @@ -300,6 +325,75 @@ 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_feedback_remove_is_atomic_under_concurrent_revokes() -> None: + redis = _AtomicRedis() + adapter = RedisSessionAdapter(client=redis) + + with ThreadPoolExecutor(max_workers=16) as pool: + first_changes = list( + pool.map(lambda _: adapter.upsert_feedback("session", "message", "up"), range(64)) + ) + with ThreadPoolExecutor(max_workers=16) as pool: + removes = list( + pool.map(lambda _: adapter.remove_feedback("session", "message"), range(64)) + ) + + assert sum(bool(changed) for changed in first_changes) == 1 + assert sum(bool(changed) for changed in removes) == 1 + metrics = redis.hashes[adapter.metrics_key] + assert metrics["feedback_up"] == 0 + assert adapter.remove_feedback("session", "message") is False + + +def test_feedback_comments_round_trip_through_redis() -> None: + """Issue #21: comment text survives the Redis upsert and reads back.""" + redis = _AtomicRedis() + adapter = RedisSessionAdapter(client=redis) + store = MetricsStore(backend=adapter) + + assert store.add_feedback("up", "回答很清楚", "message-1", session_id="session-1") is True + assert store.add_feedback("up", "回答很清楚", "message-1", session_id="session-1") is False + assert store.add_feedback("up", "补充一点:希望更简短", "message-1", session_id="session-1") is True + assert store.add_feedback("down", None, "message-1", session_id="session-1") is True + # A blank comment is no comment: it changes nothing and counts nothing. + assert store.add_feedback("up", " ", "message-2", session_id="session-1") is True + assert store.add_feedback("up", "", "message-2", session_id="session-1") is False + + comments = store.feedback_comments() + assert len(comments) == 1 + assert comments[0] == { + "session_id": "session-1", + "message_id": "message-1", + "rating": "down", + "comment": "补充一点:希望更简短", + "seq": 3, + } + assert store.snapshot()["feedback"].get("commented") == 1 + + # A second commented message reads back in update order. + assert store.add_feedback("down", "答非所问", "message-2", session_id="session-2") is True + comments = store.feedback_comments() + assert [item["message_id"] for item in comments] == ["message-1", "message-2"] + assert store.snapshot()["feedback"].get("commented") == 2 + + def test_shared_metrics_record_is_atomic_and_deduplicated_under_concurrency() -> None: redis = _AtomicRedis() adapter = RedisSessionAdapter(client=redis) diff --git a/backend/tests/test_request_id_lock.py b/backend/tests/test_request_id_lock.py new file mode 100644 index 0000000..d6693bf --- /dev/null +++ b/backend/tests/test_request_id_lock.py @@ -0,0 +1,124 @@ +"""Issue #22: a plain chat after an idempotent turn must not 409. + +Root cause: the persisted session state kept the previous turn's +``request_id``/``_request_fingerprint``, and a request without +``request_id`` inherited them in ``_state_for_request``. Both chat paths +then read the stale identifier from that state and the fingerprint check +compared the new message against the previous turn's identifier, so every +plain chat after an idempotent turn raised 409 and the session looked +permanently locked. +""" +from __future__ import annotations + +from fastapi.testclient import TestClient + +from app.main import app +from conftest import login_client + + +def _new_session(client: TestClient) -> str: + # Issue #6: protected APIs require a login in every mode, including + # test mode, so create a session only after logging in. + login_client(client, "request_id_lock_user") + session_id = client.post("/api/sessions").json()["session_id"] + assert session_id + return session_id + + +def _chat(client: TestClient, session_id: str, message: str, request_id: str | None = None): + payload = {"session_id": session_id, "message": message} + if request_id is not None: + payload["request_id"] = request_id + return client.post("/api/chat", json=payload) + + +def test_plain_chat_after_idempotent_turn_returns_200() -> None: + with TestClient(app) as client: + session_id = _new_session(client) + first = _chat(client, session_id, "我咳嗽三天了", request_id="repro-req-00001") + assert first.status_code == 200 + + # The exact reproduction from issue #22: the next plain chat used + # to 409 with "请求标识已用于其他消息,不能重复使用". + second = _chat(client, session_id, "我现在头痛") + third = _chat(client, session_id, "还有点发烧") + + assert second.status_code == 200 + assert third.status_code == 200 + assert "请求标识已用于其他消息" not in second.text + state = client.get(f"/api/sessions/{session_id}").json() + assert state["turn_count"] == 3 + + +def test_plain_stream_after_idempotent_turn_returns_final() -> None: + with TestClient(app) as client: + session_id = _new_session(client) + first = _chat(client, session_id, "我咳嗽三天了", request_id="repro-req-00002") + assert first.status_code == 200 + + streamed = client.post( + "/api/chat?stream=true", + json={"session_id": session_id, "message": "我现在头痛"}, + ) + assert streamed.status_code == 200 + assert "event: error" not in streamed.text + assert "event: final" in streamed.text + + +def test_idempotent_replay_still_works_after_plain_turns() -> None: + with TestClient(app) as client: + session_id = _new_session(client) + request = {"session_id": session_id, "message": "我咳嗽三天了", "request_id": "replay-req-00001"} + first = client.post("/api/chat", json=request) + assert first.status_code == 200 + assert _chat(client, session_id, "我现在头痛").status_code == 200 + + replay = client.post("/api/chat", json=request) + recovered = client.get(f"/api/sessions/{session_id}/requests/replay-req-00001") + state = client.get(f"/api/sessions/{session_id}").json() + + assert replay.status_code == 200 + assert replay.json()["response_id"] == first.json()["response_id"] + assert recovered.status_code == 200 + assert recovered.json()["response_id"] == first.json()["response_id"] + # The replay must not advance the turn counter. + assert state["turn_count"] == 2 + + +def test_same_request_id_different_message_still_conflicts() -> None: + with TestClient(app) as client: + session_id = _new_session(client) + first = _chat(client, session_id, "我咳嗽", request_id="turn-collision-0001") + assert first.status_code == 200 + # A plain turn in between must not disturb the fingerprint tombstone. + assert _chat(client, session_id, "我现在头痛").status_code == 200 + + conflict = _chat(client, session_id, "我腹痛", request_id="turn-collision-0001") + assert conflict.status_code == 409 + + +def test_alternating_idempotent_and_plain_turns() -> None: + with TestClient(app) as client: + session_id = _new_session(client) + first = _chat(client, session_id, "我咳嗽三天了", request_id="alternating-00001") + assert first.status_code == 200 + assert _chat(client, session_id, "我现在头痛").status_code == 200 + second = _chat(client, session_id, "还有点发烧", request_id="alternating-00002") + assert second.status_code == 200 + assert _chat(client, session_id, "昨晚没睡好").status_code == 200 + + # Replaying the first idempotent turn still returns its result. + replay = _chat(client, session_id, "我咳嗽三天了", request_id="alternating-00001") + assert 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"] == 4 + + +def test_invalid_request_id_still_rejected() -> None: + with TestClient(app) as client: + session_id = _new_session(client) + assert _chat(client, session_id, "我咳嗽", request_id="short").status_code == 422 + assert _chat(client, session_id, "我咳嗽", request_id="bad id!").status_code == 422 + # A rejected request must not poison the session. + assert _chat(client, session_id, "我咳嗽").status_code == 200 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/deploy/instabox/LOCAL_MODEL.md b/deploy/instabox/LOCAL_MODEL.md index 81b74d1..d7fc39a 100644 --- a/deploy/instabox/LOCAL_MODEL.md +++ b/deploy/instabox/LOCAL_MODEL.md @@ -48,7 +48,7 @@ docker compose @compose up -d --wait medguide-api medguide-ui docker compose @compose ps ``` -本地模式使用 `MEDGUIDE_LOCAL_LLM_BASE_URL`、`MEDGUIDE_LOCAL_LLM_MODEL`、`MEDGUIDE_LOCAL_LLM_TIMEOUT_SECONDS`、`MEDGUIDE_LOCAL_LLM_MAX_TOKENS`。不要把本机原有供应商配置或 `.env` 复制到实例。持久目录中的模型权重不要提交到 Git。 +本地模式使用 `MEDGUIDE_LOCAL_LLM_BASE_URL`、`MEDGUIDE_LOCAL_LLM_MODEL`、`MEDGUIDE_LOCAL_LLM_TIMEOUT_SECONDS`、`MEDGUIDE_LOCAL_LLM_MAX_TOKENS`。推理服务是 Ollama 时另设 `MEDGUIDE_LOCAL_LLM_PROVIDER=ollama`(发送 `reasoning_effort=none` 关闭思考,否则 readiness probe 的 token 会被思考占满而返回空正文);默认 `llama.cpp` 发送 `chat_template_kwargs.enable_thinking=false`。不要把本机原有供应商配置或 `.env` 复制到实例。持久目录中的模型权重不要提交到 Git。 ## 能力与边界 diff --git a/frontend/index.html b/frontend/index.html index b043cea..b4a0169 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -9,7 +9,8 @@ MedGuide · 健康信息工作台 -
+ +

正在加载 MedGuide…

diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 1ef03dc..f3b1a98 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,8 +1,18 @@ -import { FormEvent, KeyboardEvent as ReactKeyboardEvent, useEffect, useRef, useState } from "react"; +import { FormEvent, KeyboardEvent as ReactKeyboardEvent, useEffect, useReducer, useRef, useState } from "react"; import { PASSWORD_INPUT_MAX_LENGTH, USERNAME_INPUT_MAX_LENGTH, validateAuthCredentials } from "./auth-validation"; +import { copyAnswerText } from "./copy-text"; import { safeCitationSourceUrl } from "./source-url"; +import { formatFeedbackError } from "./feedback-error"; import { QuestionStarters } from "./QuestionStarters"; import { buildWorkflowStages, mergePipelineEvent, responsePipelineEvents, type PipelineEvent } from "./workflow-progress"; +import { applyFeedbackRevoke, applyFeedbackVote, feedbackAction, type FeedbackVote } from "./feedback-vote"; +import { + FEEDBACK_COMMENT_MAX_LENGTH, + buildFeedbackRequestBody, + feedbackCommentError, + feedbackCommentReducer, + initialFeedbackCommentState, +} from "./feedback-comment"; import { Activity, AlertTriangle, @@ -11,6 +21,7 @@ import { BookOpen, Check, Clock3, + Copy, Eye, EyeOff, HeartPulse, @@ -53,6 +64,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 +80,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 +93,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 +147,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 +250,9 @@ function formatHttpError(error: HttpResponseError) { case 404: return "当前会话已过期,请新建整理后重试。"; case 409: + if (error.detail?.includes("已过期")) { + return "当前会话已过期,请新建整理后继续。"; + } if (error.detail?.includes("请求上限") || error.detail?.includes("回放窗口")) { return "当前会话无法继续安全重放,请新建整理后继续。"; } @@ -246,19 +310,26 @@ 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); const [structuredResult, setStructuredResult] = useState(null); const [error, setError] = useState(null); + const [notice, setNotice] = useState(null); const [mobilePanel, setMobilePanel] = useState<"left" | "right" | null>(null); - const [feedbackSent, setFeedbackSent] = useState>({}); + const [feedbackSent, setFeedbackSent] = useState({}); const [feedbackPending, setFeedbackPending] = useState>({}); + const [copiedMessageId, setCopiedMessageId] = useState(null); + const [feedbackComment, dispatchFeedbackComment] = useReducer(feedbackCommentReducer, initialFeedbackCommentState); const bottomRef = useRef(null); const composerRef = useRef(null); const generationRef = useRef(0); @@ -275,6 +346,8 @@ function App() { const rightPanelRef = useRef(null); const restoreFocusRef = useRef(null); const closeTimerRef = useRef(null); + const copyTimerRef = useRef(null); + const noticeTimerRef = useRef(null); const authRequestRef = useRef(null); useEffect(() => { @@ -403,6 +476,7 @@ function App() { committedResponseIdsRef.current.clear(); sessionCreateKeyRef.current = null; setSession(null); + setSessions([]); setSessionStatus("idle"); setMessages([{ ...initialMessage, timestamp: Date.now() }]); setDraft(""); @@ -414,6 +488,8 @@ function App() { setStructuredResult(null); setFeedbackSent({}); setFeedbackPending({}); + dispatchFeedbackComment({ type: "reset" }); + setNotice(null); setMobilePanel(null); } @@ -436,7 +512,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 +633,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 +662,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 +750,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 +764,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 +811,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 +819,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 +835,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 +919,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 +933,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 +991,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() { @@ -784,6 +1004,17 @@ function App() { setEvents([]); setFeedbackSent({}); setFeedbackPending({}); + setCopiedMessageId(null); + setNotice(null); + if (copyTimerRef.current !== null) { + window.clearTimeout(copyTimerRef.current); + copyTimerRef.current = null; + } + if (noticeTimerRef.current !== null) { + window.clearTimeout(noticeTimerRef.current); + noticeTimerRef.current = null; + } + dispatchFeedbackComment({ type: "reset" }); committedResponseIdsRef.current.clear(); restoreFocusRef.current = null; closeMobilePanel(); @@ -791,25 +1022,98 @@ function App() { startSession(sessionCreateKeyRef.current); } - async function sendFeedback(messageId: string, rating: "up" | "down") { + function showNotice(text: string) { + if (noticeTimerRef.current !== null) { + window.clearTimeout(noticeTimerRef.current); + } + setNotice(text); + noticeTimerRef.current = window.setTimeout(() => { + noticeTimerRef.current = null; + setNotice(null); + }, 3000); + } + + async function copyAnswer(messageId: string) { + const message = messages.find((item) => item.id === messageId); + if (!message) return; + const result = await copyAnswerText(message.content); + if (result.ok) { + if (copyTimerRef.current !== null) { + window.clearTimeout(copyTimerRef.current); + } + setCopiedMessageId(messageId); + copyTimerRef.current = window.setTimeout(() => { + copyTimerRef.current = null; + setCopiedMessageId((current) => (current === messageId ? null : current)); + }, 2000); + showNotice("回答已复制到剪贴板。"); + return; + } + setError( + result.reason === "unavailable" + ? "当前浏览器不支持复制,请手动选中回答内容复制。" + : "复制失败,请检查浏览器剪贴板权限后重试。", + ); + } + + // A downvote opens the comment box first; the vote itself is only sent + // when the user submits from the box (an empty comment submits a plain + // downvote, exactly like the old one-click behaviour). An upvote stays + // one click and never asks for text. Clicking the downvote button again + // on an answer already marked down revokes the vote instead (#19). + function openFeedbackComment(messageId: string) { + if (feedbackSent[messageId] === "down" || feedbackPending[messageId]) return; + dispatchFeedbackComment({ type: "open", messageId }); + } + + async function sendFeedback(messageId: string, rating: "up" | "down", comment?: string) { const message = messages.find((item) => item.id === messageId); const sessionId = message?.sessionId || activeSessionIdRef.current; - if (!sessionId || feedbackSent[messageId] || feedbackPending[messageId]) return; + if (!sessionId || feedbackPending[messageId]) return; + // A recorded vote no longer blocks the buttons: clicking the other + // button changes the vote, clicking the same one revokes it (#19). + // The backend upserts votes, so a change is one POST; a revoke is a + // DELETE, which is idempotent on the server and needs no + // Idempotency-Key. Only the in-flight guard stays: while a request + // for this answer is pending, further clicks are ignored. + const action = feedbackAction(feedbackSent[messageId], rating); + if (rating === "down" && action !== "revoke") { + const commentProblem = feedbackCommentError(comment ?? ""); + if (commentProblem) { + setError(commentProblem); + return; + } + } const generation = generationRef.current; setFeedbackPending((current) => ({ ...current, [messageId]: true })); try { - const response = await apiFetch("/api/feedback", { - method: "POST", - headers: apiHeaders({ - "Content-Type": "application/json", - // Retried clicks for one answer/rating must remain one metric event. - "Idempotency-Key": `${sessionId}:${messageId}:${rating}`, - }), - body: JSON.stringify({ session_id: sessionId, message_id: messageId, rating }), - }); - await ensureResponseOk(response); + if (action === "revoke") { + const response = await apiFetch( + `/api/feedback?session_id=${encodeURIComponent(sessionId)}&message_id=${encodeURIComponent(messageId)}`, + { method: "DELETE", headers: apiHeaders({}) }, + ); + await ensureResponseOk(response); + } else { + const response = await apiFetch("/api/feedback", { + method: "POST", + headers: apiHeaders({ + "Content-Type": "application/json", + // Retried clicks for one answer/rating must remain one metric event. + "Idempotency-Key": `${sessionId}:${messageId}:${rating}`, + }), + body: JSON.stringify(buildFeedbackRequestBody({ sessionId, messageId, rating, comment })), + }); + await ensureResponseOk(response); + } if (generationRef.current === generation) { - setFeedbackSent((current) => ({ ...current, [messageId]: rating })); + setFeedbackSent((current) => (action === "revoke" + ? applyFeedbackRevoke(current, messageId) + : applyFeedbackVote(current, messageId, rating))); + if (rating === "down" && action !== "revoke") { + dispatchFeedbackComment({ type: "submitted", messageId }); + setError(null); + setNotice("反馈已提交,谢谢你的补充。"); + } } } catch (requestError) { if (generationRef.current === generation) { @@ -817,9 +1121,19 @@ function App() { returnToAuthentication("登录状态已过期,请重新登录。"); return; } - setError(requestError instanceof HttpResponseError - ? `反馈提交失败:${formatHttpError(requestError)}` - : "反馈提交失败,请稍后重试。"); + // The previous vote stays selected on failure: the local state + // is only updated after a successful response, so nothing to + // roll back here. The comment box stays open with the draft + // kept, so a failed submit does not make the user retype. + // Feedback failures must not reuse the chat input wording from + // formatHttpError ("请确认描述不为空且不超过 2000 字"): the + // question has nothing to do with a failed vote (issue #25). + setNotice(null); + setError(action === "revoke" + ? "取消反馈失败,请稍后重试。" + : requestError instanceof HttpResponseError + ? formatFeedbackError(requestError) + : "反馈提交失败,请稍后重试。"); } } finally { setFeedbackPending((current) => { @@ -849,8 +1163,6 @@ function App() { ? "服务不可用" : !session ? "建立安全会话" - : session.mode === "preview" - ? "示例会话" : session.network_enabled === false ? "知识服务受限" : "整理服务在线"; @@ -886,7 +1198,7 @@ function App() {
{serviceStatusLabel}
- {authUser.username} + {authUser.username} @@ -922,12 +1234,25 @@ function App() {
-
这次对话
+
历史对话
- + {sessions.length === 0 ? ( + + ) : ( + sessions.map((item) => ( + + )) + )}
如何描述问题 @@ -974,7 +1299,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" &&
} @@ -985,7 +1310,30 @@ function App() { )} {message.role === "assistant" && message.latency !== undefined &&
响应 {Math.round(message.latency)} ms
} - {message.role === "assistant" && message.id !== "welcome" &&
这条回答有帮助吗?
} + {message.role === "assistant" && message.id !== "welcome" &&
这条回答有帮助吗?
} + {message.role === "assistant" && message.id !== "welcome" && feedbackComment.openMessageId === message.id && ( +
+ +