Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions backend/app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -1022,6 +1022,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,
Expand Down
5 changes: 5 additions & 0 deletions backend/app/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,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
Expand Down
89 changes: 89 additions & 0 deletions backend/app/store.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
41 changes: 41 additions & 0 deletions backend/app/workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -798,6 +798,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")
Expand All @@ -822,6 +862,7 @@ def finalize(self, state: WorkflowState) -> WorkflowState:
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
159 changes: 159 additions & 0 deletions backend/tests/test_session_history.py
Original file line number Diff line number Diff line change
@@ -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") == []
Loading