From 23d98b5cc3b3a5b6d08525492c8918daacf93ad3 Mon Sep 17 00:00:00 2001 From: Zhenxian Liang Date: Mon, 16 Nov 2026 11:31:52 +0800 Subject: [PATCH 1/2] Fix #3: persist session history and add session listing - Store per-turn messages in WorkflowState and include them in the public session state, so refresh/logout no longer loses the transcript. - Add GET /api/sessions (owner-scoped, newest first) and include messages in GET /api/sessions/{id}. - Frontend: show a real history list, restore the most recent session on login/refresh, and restore a session on click. - Add backend/tests/test_session_history.py (7 tests). Closes zhengdaodeguL/MedGuide#3 (session history lost on refresh/logout). --- backend/app/main.py | 28 +++++ backend/app/models.py | 5 + backend/app/store.py | 89 +++++++++++++++ backend/app/workflow.py | 41 +++++++ backend/tests/test_session_history.py | 155 +++++++++++++++++++++++++ frontend/src/App.tsx | 158 +++++++++++++++++++++++++- frontend/src/styles.css | 1 + 7 files changed, 471 insertions(+), 6 deletions(-) create mode 100644 backend/tests/test_session_history.py diff --git a/backend/app/main.py b/backend/app/main.py index 217a42a..90c3003 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -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, diff --git a/backend/app/models.py b/backend/app/models.py index 7ae75c6..4f61585 100644 --- a/backend/app/models.py +++ b/backend/app/models.py @@ -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 diff --git a/backend/app/store.py b/backend/app/store.py index 52d06b0..b562de6 100644 --- a/backend/app/store.py +++ b/backend/app/store.py @@ -170,6 +170,7 @@ def create(self, owner_id: str | None = None, idempotency_key: str | None = None "_version": 0, "mode": self.mode, "events": [], + "messages": [], "citations": [], "risk_flags": [], "risk_assessed": False, @@ -362,9 +363,97 @@ def request_result(self, session_id: str, request_id: str, owner_id: str | None result = state.get("request_results", {}).get(request_id) return merge_request_result(state, result) if isinstance(result, dict) else None + @property + def listing_complete(self) -> bool: + """Whether :meth:`list_sessions` can enumerate every session. + + The in-memory store can. A shared Redis backend cannot be enumerated + (there is no session index), so listing is incomplete by design and + :meth:`list_sessions` returns ``[]`` rather than a partial list. + """ + if self.backend is None: + return True + return callable(getattr(self.backend, "list_states", None)) + + @staticmethod + def _session_list_entry(state: WorkflowState) -> dict[str, Any]: + messages = state.get("messages", []) or [] + first_user = next( + ( + str(item.get("content", "")).strip() + for item in messages + if isinstance(item, dict) + and item.get("role") == "user" + and str(item.get("content", "")).strip() + ), + "", + ) + title = first_user[:30] or str(state.get("summary", "") or "") or "新的健康咨询" + return { + "session_id": state.get("session_id"), + "title": title, + "summary": state.get("summary", ""), + "turn_count": int(state.get("turn_count", 0)), + "updated_at": state.get("updated_at"), + "risk_level": state.get("risk_level") if state.get("risk_assessed") else None, + } + + def list_sessions(self, owner_id: str | None = None) -> list[dict[str, Any]]: + """Return one owner's unexpired sessions, newest first. + + Only the in-memory store can enumerate sessions. When a shared + backend is selected and it offers no ``list_states`` enumeration, + this returns ``[]`` (see :attr:`listing_complete`) instead of a + misleading partial list. + """ + owner = str(owner_id or "") + if self.backend is not None: + listing = getattr(self.backend, "list_states", None) + if not callable(listing): + return [] + try: + remote_states = listing(owner) + except Exception as exc: + raise SessionBackendError("共享会话后端暂时不可用,请稍后重试") from exc + states = [ + state + for state in (remote_states or []) + if isinstance(state, dict) and str(state.get("owner_id", "")) == owner + ] + states.sort(key=lambda item: str(item.get("updated_at") or ""), reverse=True) + return [self._session_list_entry(state) for state in states] + with self._lock: + self._purge_expired() + states = [ + deepcopy(state) + for state in self._sessions.values() + if str(state.get("owner_id", "")) == owner + ] + states.sort(key=lambda item: str(item.get("updated_at") or ""), reverse=True) + return [self._session_list_entry(state) for state in states] + + @staticmethod + def _public_messages(state: WorkflowState) -> list[dict[str, Any]]: + """Return only the transcript fields the API may expose.""" + messages: list[dict[str, Any]] = [] + for item in state.get("messages", []) or []: + if not isinstance(item, dict) or item.get("role") not in {"user", "assistant"}: + continue + entry: dict[str, Any] = { + "role": item["role"], + "content": str(item.get("content", "")), + } + if item.get("response_id"): + entry["response_id"] = str(item["response_id"]) + if item.get("timestamp"): + entry["timestamp"] = str(item["timestamp"]) + messages.append(entry) + return messages + def public(self, state: WorkflowState) -> dict: return { "session_id": state.get("session_id"), + "messages": self._public_messages(state), "turn_count": state.get("turn_count", 0), "profile": state.get("profile", {}), "risk_level": state.get("risk_level") if state.get("risk_assessed") else None, diff --git a/backend/app/workflow.py b/backend/app/workflow.py index 5dbcc68..00e5f9c 100644 --- a/backend/app/workflow.py +++ b/backend/app/workflow.py @@ -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") @@ -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 diff --git a/backend/tests/test_session_history.py b/backend/tests/test_session_history.py new file mode 100644 index 0000000..c37ccb7 --- /dev/null +++ b/backend/tests/test_session_history.py @@ -0,0 +1,155 @@ +"""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: + 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: + 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/frontend/src/App.tsx b/frontend/src/App.tsx index 1ef03dc..d74a0fb 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -53,6 +53,13 @@ type Citation = { source_url?: string; }; +type StoredMessage = { + role: "user" | "assistant"; + content: string; + response_id?: string; + timestamp?: string; +}; + type SessionState = { session_id: string; turn_count: number; @@ -62,6 +69,8 @@ type SessionState = { intent: string; next_question: string | null; mode: string; + /** Full turn transcript, oldest first; absent on older API versions. */ + messages?: StoredMessage[]; /** Optional capability fields supplied by newer API versions. */ environment?: string; network_enabled?: boolean; @@ -73,6 +82,15 @@ type SessionState = { summary?: string; }; +type SessionListItem = { + session_id: string; + title: string; + summary: string; + turn_count: number; + updated_at: string | null; + risk_level?: RiskLevel | null; +}; + type StructuredResult = { intent: string; sql: string; @@ -246,6 +264,7 @@ function App() { const [authBootstrapError, setAuthBootstrapError] = useState(null); const [logoutPending, setLogoutPending] = useState(false); const [session, setSession] = useState(null); + const [sessions, setSessions] = useState([]); const [messages, setMessages] = useState([initialMessage]); const [draft, setDraft] = useState(""); const [loading, setLoading] = useState(false); @@ -403,6 +422,7 @@ function App() { committedResponseIdsRef.current.clear(); sessionCreateKeyRef.current = null; setSession(null); + setSessions([]); setSessionStatus("idle"); setMessages([{ ...initialMessage, timestamp: Date.now() }]); setDraft(""); @@ -436,7 +456,117 @@ function App() { setAuthBootstrapError(null); const createKey = createRequestId("session"); sessionCreateKeyRef.current = createKey; - startSession(createKey); + void loadSessionHistory(); + } + + /** Best-effort refresh of the left-rail history list; never blocks chat. */ + async function refreshSessionList() { + try { + const response = await apiFetch("/api/sessions"); + if (!response.ok) return; + const body = (await response.json()) as { sessions?: SessionListItem[] }; + if (Array.isArray(body.sessions)) setSessions(body.sessions); + } catch { + // History is a convenience view; a failed refresh must not surface + // as a chat error. + } + } + + /** + * On login/refresh, restore the newest session that already has messages + * instead of opening an empty one. A fresh session is created only when + * the user has no history yet. The list endpoint — not localStorage — + * is the source of truth for which sessions exist. + */ + async function loadSessionHistory() { + const generation = generationRef.current; + setSessionStatus("creating"); + try { + const response = await apiFetch("/api/sessions"); + await ensureResponseOk(response); + const body = (await response.json()) as { sessions?: SessionListItem[] }; + const listed = Array.isArray(body.sessions) ? body.sessions : []; + if (generationRef.current !== generation) return; + setSessions(listed); + const latest = listed.find((item) => item.turn_count > 0); + if (latest) { + await restoreSession(latest.session_id); + return; + } + } catch (requestError) { + if (generationRef.current !== generation) return; + if (requestError instanceof HttpResponseError && requestError.status === 401) { + returnToAuthentication("登录状态已过期,请重新登录。"); + return; + } + // Fall through to a fresh session when history cannot be read. + } + startSession(sessionCreateKeyRef.current || createRequestId("session")); + } + + function applyRestoredSession(state: SessionState) { + activeSessionIdRef.current = state.session_id; + committedResponseIdsRef.current.clear(); + const restored: Message[] = [{ ...initialMessage, timestamp: Date.now() }]; + for (const [index, item] of (state.messages || []).entries()) { + const parsed = item.timestamp ? Date.parse(item.timestamp) : Number.NaN; + const message: Message = { + id: item.response_id || `restored-${index}`, + role: item.role, + content: item.content, + timestamp: Number.isNaN(parsed) ? Date.now() : parsed, + sessionId: state.session_id, + }; + if (item.role === "assistant" && item.response_id) { + committedResponseIdsRef.current.add(item.response_id); + } + restored.push(message); + } + setSession(state); + setMessages(restored); + // Per-message citations are not stored server-side, so restored + // answers link no references; the live turn's citations still apply. + setCitations([]); + setSelectedCitationMessageId(null); + setStructuredResult(null); + setEvents([]); + setFeedbackSent({}); + setFeedbackPending({}); + } + + async function restoreSession(sessionId: string) { + const generation = ++generationRef.current; + sessionRequestRef.current?.abort(); + chatRequestRef.current?.abort(); + chatRequestRef.current = null; + pendingRetryRef.current = null; + setSessionStatus("creating"); + setLoading(false); + setError(null); + const controller = new AbortController(); + sessionRequestRef.current = controller; + try { + const response = await apiFetch(`/api/sessions/${encodeURIComponent(sessionId)}`, { + signal: controller.signal, + }); + await ensureResponseOk(response); + const body = (await response.json()) as SessionState; + if (!body.session_id || !requestIsCurrent(generation, controller)) return; + applyRestoredSession(body); + setSessionStatus("ready"); + } catch (requestError) { + if (isAbortError(requestError) || !requestIsCurrent(generation, controller)) return; + if (requestError instanceof HttpResponseError && requestError.status === 401) { + returnToAuthentication("登录状态已过期,请重新登录。"); + return; + } + activeSessionIdRef.current = null; + setSession(null); + setSessionStatus("error"); + setError(requestError instanceof HttpResponseError ? formatHttpError(requestError) : "整理服务暂不可用,请稍后重试。"); + } finally { + if (sessionRequestRef.current === controller) sessionRequestRef.current = null; + } } function restoreAuthentication() { @@ -578,6 +708,7 @@ function App() { activeSessionIdRef.current = body.state.session_id; setSession(body.state); setSessionStatus("ready"); + void refreshSessionList(); } catch (requestError) { if (isAbortError(requestError) || !requestIsCurrent(generation, controller)) return; if (requestError instanceof HttpResponseError && requestError.status === 401) { @@ -773,6 +904,8 @@ function App() { latency: body.latency_ms, sessionId: body.state.session_id, }); + // The turn changed this session's title and turn count in the history. + void refreshSessionList(); } function newConversation() { @@ -922,12 +1055,25 @@ function App() { -
这次对话
+
历史对话
- + {sessions.length === 0 ? ( + + ) : ( + sessions.map((item) => ( + + )) + )}
如何描述问题 diff --git a/frontend/src/styles.css b/frontend/src/styles.css index 2523191..3f9cb9e 100644 --- a/frontend/src/styles.css +++ b/frontend/src/styles.css @@ -139,6 +139,7 @@ button.starter-prompt:hover:not(:disabled) { border-color:#a1cbd0; background:#f .conversation-list { display:grid; gap:4px; } .conversation-item { display:flex; align-items:center; gap:8px; width:100%; padding:11px 8px; color:var(--ink-800); text-align:left; background:var(--teal-050); border:1px solid #d0e5e8; border-radius:7px; } .conversation-item:hover { background:#e8f3f5; } +.conversation-item.active { background:#e8f3f5; border-color:#b6dadd; } .conversation-icon { display:grid; place-items:center; flex-shrink:0; width:24px; color:var(--teal-700); } .conversation-copy { display:grid; gap:5px; min-width:0; } .conversation-copy strong { overflow:hidden; font-size:12px; font-weight:500; text-overflow:ellipsis; white-space:nowrap; } From 4e52993ad1116db9b0b16b725a1884e01cd00d65 Mon Sep 17 00:00:00 2001 From: Zhenxian Liang Date: Wed, 18 Nov 2026 21:08:15 +0800 Subject: [PATCH 2/2] Rebase fix for #3 onto main --- backend/tests/test_session_history.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/backend/tests/test_session_history.py b/backend/tests/test_session_history.py index c37ccb7..2ca78a7 100644 --- a/backend/tests/test_session_history.py +++ b/backend/tests/test_session_history.py @@ -52,6 +52,8 @@ def _chat(client: TestClient, session_id: str, message: str, request_id: str): 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") @@ -113,6 +115,8 @@ def test_cross_user_session_read_returns_404(client: TestClient) -> None: 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,