diff --git a/src/conversations/display_history/persistence/README.md b/src/conversations/display_history/persistence/README.md index e2a4ecd65..baf1d1ddc 100644 --- a/src/conversations/display_history/persistence/README.md +++ b/src/conversations/display_history/persistence/README.md @@ -8,3 +8,11 @@ Store and load conversation data used by display history. Database sessions for display history persistence. +## [facade](facade) + +v3 conversation read and mutate entry points. + +## [mapping](mapping) + +Map stored rows onto v3 API models. + diff --git a/src/conversations/display_history/persistence/facade/README.md b/src/conversations/display_history/persistence/facade/README.md index 2643d5994..12981246a 100644 --- a/src/conversations/display_history/persistence/facade/README.md +++ b/src/conversations/display_history/persistence/facade/README.md @@ -6,4 +6,8 @@ Per-mode display-history persistence entry points. ## [agentic_turn.py](agentic_turn.py) -Project a PAI run and persist agentic display history for a turn envelope. \ No newline at end of file +Project a PAI run and persist agentic display history for a turn envelope. + +## [conversation.py](conversation.py) + +Read and mutate display-history conversations for the v3 Conversations API. \ No newline at end of file diff --git a/src/conversations/display_history/persistence/facade/__init__.py b/src/conversations/display_history/persistence/facade/__init__.py index de26c9669..4f3a4f1b3 100644 --- a/src/conversations/display_history/persistence/facade/__init__.py +++ b/src/conversations/display_history/persistence/facade/__init__.py @@ -3,7 +3,17 @@ from conversations.display_history.persistence.facade.agentic_turn import ( store_agentic_turn, ) +from conversations.display_history.persistence.facade.conversation import ( + delete_conversation, + get_conversation, + list_conversations, + update_conversation_topic, +) __all__ = [ + "delete_conversation", + "get_conversation", + "list_conversations", "store_agentic_turn", + "update_conversation_topic", ] diff --git a/src/conversations/display_history/persistence/facade/conversation.py b/src/conversations/display_history/persistence/facade/conversation.py new file mode 100644 index 000000000..f647fdb08 --- /dev/null +++ b/src/conversations/display_history/persistence/facade/conversation.py @@ -0,0 +1,163 @@ +"""Read and mutate display-history conversations for the v3 Conversations API.""" + +from __future__ import annotations + +from conversations.display_history.access import ( + check_conversation_access, + get_user_conversation, +) +from conversations.display_history.agentic.models.conversation import ( + Conversation, + ConversationMetadata, +) +from conversations.display_history.errors import ConversationAccessDeniedError +from conversations.display_history.persistence.mapping.conversation import ( + map_conversation, + map_conversation_metadata, +) +from conversations.display_history.persistence.repository.agentic_turn import ( + list_agentic_turns_for_conversation, +) +from conversations.display_history.persistence.repository.conversation import ( + delete_conversation as delete_conversation_row, +) +from conversations.display_history.persistence.repository.conversation import ( + list_conversations as list_conversation_rows, +) +from conversations.display_history.persistence.repository.conversation import ( + list_conversations_for_user, + update_conversation_topic_summary, +) +from conversations.display_history.persistence.repository.turn import ( + list_turns_for_conversation, +) +from log import get_logger +from utils.suid import normalize_conversation_id + +logger = get_logger(__name__) + + +def list_conversations( + user_id: str, + others_allowed: bool, +) -> list[ConversationMetadata]: + """List conversations visible to the caller. + + Args: + user_id: Authenticated user. + others_allowed: When true, include other users' conversations. + + Returns: + Conversation metadata without chat history. + + """ + rows = ( + list_conversation_rows() + if others_allowed + else list_conversations_for_user(user_id) + ) + logger.info("Listed %s conversations for user %s", len(rows), user_id) + return [map_conversation_metadata(row) for row in rows] + + +def get_conversation( + conversation_id: str, + user_id: str, + others_allowed: bool, +) -> Conversation: + """Load one conversation with chat history. + + Args: + conversation_id: Conversation id; client prefix is optional. + user_id: Authenticated user. + others_allowed: When true, allow reading other users' conversations. + + Returns: + Full conversation for the v3 API. + + Raises: + ConversationAccessDeniedError: Caller may not read this conversation. + ConversationNotFoundError: Conversation does not exist. + DisplayHistoryDatabaseError: Database operation failed. + + """ + normalized = normalize_conversation_id(conversation_id) + row = get_user_conversation(normalized, user_id, others_allowed) + conversation = map_conversation( + row, + list_turns_for_conversation(normalized), + list_agentic_turns_for_conversation(normalized), + ) + logger.info( + "Loaded conversation %s for user %s with %s turns", + normalized, + user_id, + len(conversation.chat_history), + ) + return conversation + + +def delete_conversation( + conversation_id: str, + user_id: str, + others_allowed: bool, +) -> bool: + """Delete a conversation when the caller is allowed. + + Missing conversations return false rather than an access error so the + HTTP layer can match v2 delete semantics. + + Args: + conversation_id: Conversation id; client prefix is optional. + user_id: Authenticated user. + others_allowed: When true, allow deleting other users' conversations. + + Returns: + True when a row was removed. + + Raises: + ConversationAccessDeniedError: Caller may not delete this conversation. + DisplayHistoryDatabaseError: Database operation failed. + + """ + normalized = normalize_conversation_id(conversation_id) + if not check_conversation_access(normalized, user_id, others_allowed): + raise ConversationAccessDeniedError(normalized, user_id) + deleted = delete_conversation_row(normalized) + logger.info( + "Deleted conversation %s for user %s: %s", + normalized, + user_id, + deleted, + ) + return deleted + + +def update_conversation_topic( + conversation_id: str, + user_id: str, + others_allowed: bool, + topic_summary: str, +) -> None: + """Update the conversation topic summary. + + Args: + conversation_id: Conversation id; client prefix is optional. + user_id: Authenticated user. + others_allowed: When true, allow updating other users' conversations. + topic_summary: New topic summary text. + + Raises: + ConversationAccessDeniedError: Caller may not update this conversation. + ConversationNotFoundError: Conversation does not exist. + DisplayHistoryDatabaseError: Database operation failed. + + """ + normalized = normalize_conversation_id(conversation_id) + get_user_conversation(normalized, user_id, others_allowed) + update_conversation_topic_summary(normalized, topic_summary) + logger.info( + "Updated topic summary for conversation %s for user %s", + normalized, + user_id, + ) diff --git a/src/conversations/display_history/persistence/mapping/README.md b/src/conversations/display_history/persistence/mapping/README.md new file mode 100644 index 000000000..40a581bc8 --- /dev/null +++ b/src/conversations/display_history/persistence/mapping/README.md @@ -0,0 +1,13 @@ +# List of source files stored in `src/conversations/display_history/persistence/mapping` directory + +## [__init__.py](__init__.py) + +Map display-history database rows onto v3 API models. + +## [agent_turn.py](agent_turn.py) + +Map turn envelopes and agentic rows onto ``AgentTurn``. + +## [conversation.py](conversation.py) + +Map conversation rows onto the v3 conversation envelope. diff --git a/src/conversations/display_history/persistence/mapping/__init__.py b/src/conversations/display_history/persistence/mapping/__init__.py new file mode 100644 index 000000000..282a8bd06 --- /dev/null +++ b/src/conversations/display_history/persistence/mapping/__init__.py @@ -0,0 +1,17 @@ +"""Map display-history database rows onto v3 API models.""" + +from conversations.display_history.persistence.mapping.agent_turn import ( + map_agent_turn, + map_chat_history, +) +from conversations.display_history.persistence.mapping.conversation import ( + map_conversation, + map_conversation_metadata, +) + +__all__ = [ + "map_agent_turn", + "map_chat_history", + "map_conversation", + "map_conversation_metadata", +] diff --git a/src/conversations/display_history/persistence/mapping/agent_turn.py b/src/conversations/display_history/persistence/mapping/agent_turn.py new file mode 100644 index 000000000..95939e326 --- /dev/null +++ b/src/conversations/display_history/persistence/mapping/agent_turn.py @@ -0,0 +1,62 @@ +"""Map stored turn rows onto the public agent-turn contract.""" + +from __future__ import annotations + +from conversations.display_history.agentic.models.agent_turn import AgentTurn +from conversations.display_history.persistence.models import UserAgenticTurn, UserTurn + + +def map_agent_turn(turn: UserTurn, agentic_turn: UserAgenticTurn) -> AgentTurn: + """Join a turn envelope and agentic row into a public agent turn. + + Args: + turn: Turn envelope (provider, model, timestamps, run id). + agentic_turn: Agentic display row for the same turn number. + + Returns: + Public agent turn for the conversation timeline. + + """ + return AgentTurn.model_validate( + { + "id": turn.response_id, + "status": agentic_turn.status, + "agent": agentic_turn.agent, + "provider": turn.provider, + "model": turn.model, + "started_at": turn.started_at, + "completed_at": turn.completed_at, + "context_status": agentic_turn.context_status, + "usage": { + "input_tokens": agentic_turn.input_tokens, + "output_tokens": agentic_turn.output_tokens, + }, + "referenced_documents": agentic_turn.referenced_documents, + "input": agentic_turn.input_items, + "output": agentic_turn.output_items, + } + ) + + +def map_chat_history( + turns: list[UserTurn], + agentic_turns: list[UserAgenticTurn], +) -> list[AgentTurn]: + """Build ordered chat history by matching turn number. + + Args: + turns: Turn envelopes for the conversation. + agentic_turns: Agentic rows for the same conversation. + + Returns: + Public agent turns in turn-number order. + + """ + agentic_by_number = {row.turn_number: row for row in agentic_turns} + history: list[AgentTurn] = [] + for turn in turns: + agentic = agentic_by_number.get(turn.turn_number) + if agentic is None or not turn.response_id: + continue + history.append(map_agent_turn(turn, agentic)) + return history diff --git a/src/conversations/display_history/persistence/mapping/conversation.py b/src/conversations/display_history/persistence/mapping/conversation.py new file mode 100644 index 000000000..0953667c2 --- /dev/null +++ b/src/conversations/display_history/persistence/mapping/conversation.py @@ -0,0 +1,63 @@ +"""Map stored conversation rows onto the v3 conversation envelope.""" + +from __future__ import annotations + +from conversations.display_history.agentic.models.conversation import ( + Conversation, + ConversationMetadata, +) +from conversations.display_history.persistence.mapping.agent_turn import ( + map_chat_history, +) +from conversations.display_history.persistence.models import ( + UserAgenticTurn, + UserConversation, + UserTurn, +) + + +def map_conversation_metadata(row: UserConversation) -> ConversationMetadata: + """Map a conversation row to list/get metadata. + + Args: + row: Stored conversation row. + + Returns: + Metadata without chat history. + + """ + return ConversationMetadata.model_validate( + { + "conversation_id": row.id, + "created_at": row.created_at, + "last_turn_at": row.last_message_at, + "turn_count": row.message_count, + "last_used_model": row.last_used_model, + "last_used_provider": row.last_used_provider, + "topic_summary": row.topic_summary or None, + } + ) + + +def map_conversation( + row: UserConversation, + turns: list[UserTurn], + agentic_turns: list[UserAgenticTurn], +) -> Conversation: + """Map stored rows to a full v3 conversation. + + Args: + row: Stored conversation row. + turns: Turn envelopes for the conversation. + agentic_turns: Agentic rows for the same conversation. + + Returns: + Conversation including chat history. + + """ + return Conversation.model_validate( + { + **map_conversation_metadata(row).model_dump(), + "chat_history": map_chat_history(turns, agentic_turns), + } + ) diff --git a/tests/unit/conversations/display_history/persistence/facade/README.md b/tests/unit/conversations/display_history/persistence/facade/README.md index 3dff4d021..925d3445e 100644 --- a/tests/unit/conversations/display_history/persistence/facade/README.md +++ b/tests/unit/conversations/display_history/persistence/facade/README.md @@ -2,4 +2,8 @@ ## [test_agentic_turn.py](test_agentic_turn.py) -Tests for projecting a PAI run and persisting agentic display history. \ No newline at end of file +Tests for projecting a PAI run and persisting agentic display history. + +## [test_conversation.py](test_conversation.py) + +Tests for v3 conversation facade list, get, delete, and topic update. \ No newline at end of file diff --git a/tests/unit/conversations/display_history/persistence/facade/test_conversation.py b/tests/unit/conversations/display_history/persistence/facade/test_conversation.py new file mode 100644 index 000000000..6475a0d71 --- /dev/null +++ b/tests/unit/conversations/display_history/persistence/facade/test_conversation.py @@ -0,0 +1,193 @@ +"""Tests for the conversation persistence facade.""" + +import pytest +from sqlalchemy.engine import Engine +from sqlalchemy.orm import Session + +from conversations.display_history.agentic.models.agent_turn_summary import ( + AgentTurnSummary, +) +from conversations.display_history.agentic.models.turn_items import MessageTurnItem +from conversations.display_history.errors import ( + ConversationAccessDeniedError, + ConversationNotFoundError, +) +from conversations.display_history.persistence.facade.conversation import ( + delete_conversation, + get_conversation, + list_conversations, + update_conversation_topic, +) +from conversations.display_history.persistence.repository.agentic_turn import ( + insert_agentic_turn, +) +from conversations.display_history.persistence.repository.conversation import ( + get_conversation_by_id, + insert_conversation, +) +from tests.unit.conversations.display_history.persistence.sample_rows import ( + SAMPLE_CONVERSATION, + TEST_CONVERSATION_ID, + TEST_OTHER_USER_ID, + TEST_TURN_NUMBER, + TEST_USER_ID, + seed_sample_conversation_and_turn, +) + + +def _seed_agentic_turn() -> None: + """Attach display items to the sample turn envelope.""" + insert_agentic_turn( + TEST_CONVERSATION_ID, + TEST_TURN_NUMBER, + AgentTurnSummary( + status="completed", + input=[ + MessageTurnItem(id="u1", role="user", content=[]), + ], + output=[ + MessageTurnItem(id="a1", role="assistant", content=[]), + ], + ), + ) + + +@pytest.mark.usefixtures("patch_display_history_session") +def test_list_conversations_for_owner(memory_engine: Engine) -> None: + """Owners see only their conversations when others are not allowed.""" + with Session(memory_engine) as session: + seed_sample_conversation_and_turn(session) + insert_conversation( + "conv-2", + TEST_OTHER_USER_ID, + "gpt-4", + "openai", + "Other topic", + 0, + None, + ) + + listed = list_conversations(TEST_USER_ID, False) + assert len(listed) == 1 + assert listed[0].conversation_id == TEST_CONVERSATION_ID + assert listed[0].topic_summary == SAMPLE_CONVERSATION["topic_summary"] + assert listed[0].last_used_model == "gpt-4" + + +@pytest.mark.usefixtures("patch_display_history_session") +def test_list_conversations_includes_others_when_allowed( + memory_engine: Engine, +) -> None: + """Privileged callers receive every stored conversation.""" + with Session(memory_engine) as session: + seed_sample_conversation_and_turn(session) + insert_conversation( + "conv-2", + TEST_OTHER_USER_ID, + "gpt-4", + "openai", + "Other topic", + 0, + None, + ) + + listed = list_conversations(TEST_USER_ID, True) + assert {row.conversation_id for row in listed} == { + TEST_CONVERSATION_ID, + "conv-2", + } + + +@pytest.mark.usefixtures("patch_display_history_session") +def test_get_conversation_assembles_agent_turns(memory_engine: Engine) -> None: + """GET joins the turn envelope with persisted agentic items.""" + with Session(memory_engine) as session: + seed_sample_conversation_and_turn(session) + _seed_agentic_turn() + + conversation = get_conversation(TEST_CONVERSATION_ID, TEST_USER_ID, False) + assert conversation.conversation_id == TEST_CONVERSATION_ID + assert len(conversation.chat_history) == 1 + turn = conversation.chat_history[0] + assert turn.id == "resp-1" + assert turn.status == "completed" + assert turn.provider == "openai" + assert turn.model == "gpt-4" + assert turn.input[0].id == "u1" + assert turn.output[0].id == "a1" + + +@pytest.mark.usefixtures("patch_display_history_session") +def test_get_conversation_skips_turns_without_agentic_data( + memory_engine: Engine, +) -> None: + """Envelope-only turns are omitted from the v3 timeline.""" + with Session(memory_engine) as session: + seed_sample_conversation_and_turn(session) + + conversation = get_conversation(TEST_CONVERSATION_ID, TEST_USER_ID, False) + assert conversation.chat_history == [] + + +@pytest.mark.usefixtures("patch_display_history_session") +def test_get_conversation_forbidden(memory_engine: Engine) -> None: + """Non-owners cannot read another user's conversation.""" + with Session(memory_engine) as session: + seed_sample_conversation_and_turn(session) + with pytest.raises(ConversationAccessDeniedError): + get_conversation(TEST_CONVERSATION_ID, TEST_OTHER_USER_ID, False) + + +@pytest.mark.usefixtures("patch_display_history_session") +def test_get_conversation_not_found() -> None: + """Missing conversations raise ConversationNotFoundError.""" + with pytest.raises(ConversationNotFoundError): + get_conversation("missing-conv", TEST_USER_ID, True) + + +@pytest.mark.usefixtures("patch_display_history_session") +def test_delete_conversation_owner(memory_engine: Engine) -> None: + """Owners can delete their conversation.""" + with Session(memory_engine) as session: + seed_sample_conversation_and_turn(session) + assert delete_conversation(TEST_CONVERSATION_ID, TEST_USER_ID, False) is True + assert get_conversation_by_id(TEST_CONVERSATION_ID) is None + + +@pytest.mark.usefixtures("patch_display_history_session") +def test_delete_conversation_missing_is_not_found() -> None: + """Deleting a missing conversation returns False rather than 404 at this layer.""" + assert delete_conversation("missing-conv", TEST_USER_ID, False) is False + + +@pytest.mark.usefixtures("patch_display_history_session") +def test_delete_conversation_forbidden(memory_engine: Engine) -> None: + """Non-owners cannot delete another user's conversation.""" + with Session(memory_engine) as session: + seed_sample_conversation_and_turn(session) + with pytest.raises(ConversationAccessDeniedError): + delete_conversation(TEST_CONVERSATION_ID, TEST_OTHER_USER_ID, False) + assert get_conversation_by_id(TEST_CONVERSATION_ID) is not None + + +@pytest.mark.usefixtures("patch_display_history_session") +def test_update_conversation_topic(memory_engine: Engine) -> None: + """Owners can replace the topic summary.""" + with Session(memory_engine) as session: + seed_sample_conversation_and_turn(session) + update_conversation_topic( + TEST_CONVERSATION_ID, + TEST_USER_ID, + False, + "Updated topic", + ) + loaded = get_conversation_by_id(TEST_CONVERSATION_ID) + assert loaded is not None + assert loaded.topic_summary == "Updated topic" + + +@pytest.mark.usefixtures("patch_display_history_session") +def test_update_conversation_topic_not_found() -> None: + """Updating a missing conversation raises ConversationNotFoundError.""" + with pytest.raises(ConversationNotFoundError): + update_conversation_topic("missing-conv", TEST_USER_ID, True, "x") diff --git a/tests/unit/conversations/display_history/persistence/mapping/README.md b/tests/unit/conversations/display_history/persistence/mapping/README.md new file mode 100644 index 000000000..3b63bd9d4 --- /dev/null +++ b/tests/unit/conversations/display_history/persistence/mapping/README.md @@ -0,0 +1,9 @@ +# List of source files stored in `tests/unit/conversations/display_history/persistence/mapping` directory + +## [test_agent_turn.py](test_agent_turn.py) + +Tests for mapping turn envelopes and agentic rows onto ``AgentTurn``. + +## [test_conversation.py](test_conversation.py) + +Tests for mapping conversation rows onto the v3 conversation envelope. diff --git a/tests/unit/conversations/display_history/persistence/mapping/__init__.py b/tests/unit/conversations/display_history/persistence/mapping/__init__.py new file mode 100644 index 000000000..0d01b2226 --- /dev/null +++ b/tests/unit/conversations/display_history/persistence/mapping/__init__.py @@ -0,0 +1 @@ +"""Tests for display-history ORM-to-API mapping.""" diff --git a/tests/unit/conversations/display_history/persistence/mapping/test_agent_turn.py b/tests/unit/conversations/display_history/persistence/mapping/test_agent_turn.py new file mode 100644 index 000000000..158230f4b --- /dev/null +++ b/tests/unit/conversations/display_history/persistence/mapping/test_agent_turn.py @@ -0,0 +1,80 @@ +"""Tests for mapping stored turn rows onto AgentTurn.""" + +from conversations.display_history.agentic.models.turn_items import MessageTurnItem +from conversations.display_history.persistence.mapping.agent_turn import ( + map_agent_turn, + map_chat_history, +) +from conversations.display_history.persistence.models import UserAgenticTurn, UserTurn +from tests.unit.conversations.display_history.persistence.sample_rows import ( + SAMPLE_TURN, + TEST_CONVERSATION_ID, + TEST_RESPONSE_ID, + TEST_TURN_NUMBER, + new_turn, +) + + +def _agentic_row( + *, + turn_number: int = TEST_TURN_NUMBER, + input_tokens: int = 4, + output_tokens: int = 6, +) -> UserAgenticTurn: + user_item = MessageTurnItem(id="u1", role="user", content=[]) + assistant_item = MessageTurnItem(id="a1", role="assistant", content=[]) + return UserAgenticTurn( + conversation_id=TEST_CONVERSATION_ID, + turn_number=turn_number, + status="completed", + agent=None, + context_status="compacted", + input_tokens=input_tokens, + output_tokens=output_tokens, + referenced_documents=[{"doc_title": "OpenShift Docs", "doc_url": None}], + input_items=[user_item.model_dump(mode="json")], + output_items=[assistant_item.model_dump(mode="json")], + ) + + +def test_map_agent_turn_joins_envelope_and_row() -> None: + """Public AgentTurn merges envelope fields with agentic JSON columns.""" + turn = new_turn() + mapped = map_agent_turn(turn, _agentic_row()) + assert mapped.id == TEST_RESPONSE_ID + assert mapped.provider == turn.provider + assert mapped.model == turn.model + assert mapped.started_at == turn.started_at + assert mapped.completed_at == turn.completed_at + assert mapped.status == "completed" + assert mapped.context_status == "compacted" + assert mapped.usage.input_tokens == 4 + assert mapped.usage.output_tokens == 6 + assert mapped.input[0].id == "u1" + assert mapped.output[0].id == "a1" + assert mapped.referenced_documents[0].doc_title == "OpenShift Docs" + + +def _turn(*, turn_number: int, response_id: str | None) -> UserTurn: + """Build a turn envelope, including the legacy no-response-id case.""" + return UserTurn( + **{ + **SAMPLE_TURN, + "turn_number": turn_number, + "response_id": response_id, + } + ) + + +def test_map_chat_history_skips_incomplete_turns() -> None: + """Turns without agentic data or a response id are omitted.""" + history = map_chat_history( + [ + new_turn(), + _turn(turn_number=2, response_id=TEST_RESPONSE_ID), + _turn(turn_number=3, response_id=None), + ], + [_agentic_row(turn_number=1), _agentic_row(turn_number=3)], + ) + assert len(history) == 1 + assert history[0].id == TEST_RESPONSE_ID diff --git a/tests/unit/conversations/display_history/persistence/mapping/test_conversation.py b/tests/unit/conversations/display_history/persistence/mapping/test_conversation.py new file mode 100644 index 000000000..dbf861ed5 --- /dev/null +++ b/tests/unit/conversations/display_history/persistence/mapping/test_conversation.py @@ -0,0 +1,71 @@ +"""Tests for mapping stored conversation rows onto the v3 envelope.""" + +from conversations.display_history.agentic.models.turn_items import MessageTurnItem +from conversations.display_history.persistence.mapping.conversation import ( + map_conversation, + map_conversation_metadata, +) +from conversations.display_history.persistence.models import UserAgenticTurn +from tests.unit.conversations.display_history.persistence.sample_rows import ( + SAMPLE_CONVERSATION, + TEST_CONVERSATION_ID, + TEST_INSTANT, + TEST_RESPONSE_ID, + TEST_TURN_NUMBER, + new_conversation, + new_turn, +) + + +def test_map_conversation_metadata_renames_envelope_fields() -> None: + """Stored column names become the public conversation envelope.""" + row = new_conversation() + row.created_at = TEST_INSTANT + row.last_message_at = TEST_INSTANT + row.message_count = 3 + mapped = map_conversation_metadata(row) + assert mapped.conversation_id == TEST_CONVERSATION_ID + assert mapped.created_at == TEST_INSTANT + assert mapped.last_turn_at == TEST_INSTANT + assert mapped.turn_count == 3 + assert mapped.last_used_model == SAMPLE_CONVERSATION["last_used_model"] + assert mapped.last_used_provider == SAMPLE_CONVERSATION["last_used_provider"] + assert mapped.topic_summary == SAMPLE_CONVERSATION["topic_summary"] + + +def test_map_conversation_metadata_blank_topic_is_none() -> None: + """An empty stored topic summary is omitted on the public envelope.""" + row = new_conversation() + row.created_at = TEST_INSTANT + row.last_message_at = TEST_INSTANT + row.topic_summary = "" + assert map_conversation_metadata(row).topic_summary is None + + +def test_map_conversation_includes_chat_history() -> None: + """GET mapping attaches ordered agent turns to conversation metadata.""" + row = new_conversation() + row.created_at = TEST_INSTANT + row.last_message_at = TEST_INSTANT + agentic = UserAgenticTurn( + conversation_id=TEST_CONVERSATION_ID, + turn_number=TEST_TURN_NUMBER, + status="completed", + context_status="full", + input_tokens=0, + output_tokens=0, + referenced_documents=[], + input_items=[ + MessageTurnItem(id="u1", role="user", content=[]).model_dump(mode="json") + ], + output_items=[ + MessageTurnItem(id="a1", role="assistant", content=[]).model_dump( + mode="json" + ) + ], + ) + conversation = map_conversation(row, [new_turn()], [agentic]) + assert conversation.conversation_id == TEST_CONVERSATION_ID + assert len(conversation.chat_history) == 1 + assert conversation.chat_history[0].id == TEST_RESPONSE_ID + assert conversation.chat_history[0].input[0].id == "u1"