From ca45fb0fc79bd9ef0dd640d774fc273bf2a4d4d2 Mon Sep 17 00:00:00 2001 From: mpichini1 Date: Fri, 13 Nov 2026 20:08:34 +0100 Subject: [PATCH] fix: retain image-only records in partner session history --- deeptutor/services/partners/sessions.py | 29 +++++-- tests/api/test_partners_router.py | 31 +++++++ .../services/partners/test_partner_runtime.py | 84 ++++++++++++++++++- 3 files changed, 135 insertions(+), 9 deletions(-) diff --git a/deeptutor/services/partners/sessions.py b/deeptutor/services/partners/sessions.py index ade6aadb0..d11d4f823 100644 --- a/deeptutor/services/partners/sessions.py +++ b/deeptutor/services/partners/sessions.py @@ -47,6 +47,25 @@ def conversation_scope(channel: str, chat_type: str) -> str: ) +def _is_message_record(record: Any) -> bool: + if not isinstance(record, dict) or not record.get("role"): + return False + if record.get("content"): + return True + attachments = record.get("attachments") + return ( + isinstance(record.get("content"), str) + and isinstance(attachments, list) + and any( + isinstance(item, dict) + and item.get("type") == "image" + and isinstance(item.get("filename"), str) + and bool(item["filename"]) + for item in attachments + ) + ) + + class PartnerSessionStore: """Append-only JSONL persistence for one partner's conversations.""" @@ -259,7 +278,7 @@ class PartnerSessionStore: data = json.loads(line) except json.JSONDecodeError: continue - if isinstance(data, dict) and data.get("role") and data.get("content"): + if _is_message_record(data): records.append(data) except OSError: logger.exception("Failed to read partner session %s", session_key) @@ -273,7 +292,7 @@ class PartnerSessionStore: max_chars: int = _HISTORY_MAX_CHARS, ) -> list[dict[str, str]]: """Return trailing history in OpenAI message format, budget-capped.""" - records = self._read_records(session_key) + records = [record for record in self._read_records(session_key) if record.get("content")] window = [ {"role": str(r["role"]), "content": str(r["content"])} for r in records[-max_messages:] @@ -324,11 +343,7 @@ class PartnerSessionStore: record = json.loads(line) except json.JSONDecodeError: continue - if ( - not isinstance(record, dict) - or not record.get("role") - or not record.get("content") - ): + if not _is_message_record(record): continue if cursor is None or total < cursor: window.append(record) diff --git a/tests/api/test_partners_router.py b/tests/api/test_partners_router.py index ff3af5564..d11096c32 100644 --- a/tests/api/test_partners_router.py +++ b/tests/api/test_partners_router.py @@ -712,6 +712,37 @@ class TestHistory: client.post("/api/partners/ada/sessions/delete", json={"session_key": "web-a"}) ).status_code == 404 + def test_image_only_history_is_paged_and_redacts_private_metadata(self, client): + from deeptutor.api.routers import partners as router_mod + + _create(client) + store = router_mod.get_partner_manager().session_store("ada") + store.append("web-image", "user", "before") + attachment = {"type": "image", "filename": "photo.png", "path": "/tmp/photo.png"} + store.append("web-image", "user", "", attachments=[attachment]) + store.append("web-image", "assistant", "saw it", metadata={"model_turn": {"private": True}}) + + history = client.get("/api/partners/ada/history?session_key=web-image").json() + assert [row["role"] for row in history] == ["user", "user", "assistant"] + assert history[1]["attachments"] == [attachment] + assert history[2]["metadata"] == {} + summary = client.get("/api/partners/ada/sessions").json()[0] + assert (summary["message_count"], summary["title"], summary["last_message"]) == ( + 3, + "before", + "saw it", + ) + page = client.get("/api/partners/ada/history/page?session_key=web-image&limit=2").json() + assert page["messages"] == history[1:] + assert (page["start"], page["next_before"], page["total"]) == (1, 1, 3) + + store.append("web-image", "user", "later") + older = client.get( + "/api/partners/ada/history/page?session_key=web-image&limit=2&before=1" + ).json() + assert older["messages"] == history[:1] + assert (older["start"], older["next_before"], older["total"]) == (0, None, 4) + def test_history_pages_reach_the_beginning_with_stable_cursor(self, client): from deeptutor.api.routers import partners as router_mod diff --git a/tests/services/partners/test_partner_runtime.py b/tests/services/partners/test_partner_runtime.py index 9c10f606d..145692059 100644 --- a/tests/services/partners/test_partner_runtime.py +++ b/tests/services/partners/test_partner_runtime.py @@ -3,6 +3,7 @@ from __future__ import annotations import asyncio +import json from typing import Any import pytest @@ -942,15 +943,16 @@ class TestContextAssembly: } in context.conversation_history @pytest.mark.asyncio + @pytest.mark.parametrize("content", ["what is in this image?", ""]) async def test_image_media_becomes_context_attachment_and_session_record( - self, partners_root, fake_orchestrator + self, partners_root, fake_orchestrator, content ): image_path = partners_root / "image.png" image_path.parent.mkdir(parents=True, exist_ok=True) image_path.write_bytes(b"\x89PNG\r\n\x1a\n" + b"0" * 32) fake_orchestrator.script = finish("saw it") runner = _runner(partners_root) - msg = _msg("what is in this image?") + msg = _msg(content) msg.media = [str(image_path)] await runner.process_message(msg) @@ -960,6 +962,7 @@ class TestContextAssembly: assert context.attachments[0].type == "image" assert context.attachments[0].filename == "image.png" records = _shared_store().messages("telegram:42") + assert [record["role"] for record in records] == ["user", "assistant"] assert records[0]["attachments"][0]["type"] == "image" assert records[0]["attachments"][0]["filename"] == "image.png" @@ -1131,6 +1134,83 @@ class TestSessionStoreOps: # Events ride along so the branched copy rehydrates its trace too. assert store.messages("web-b")[1].get("events") + def test_image_only_history_replays_the_stored_model_turn(self, partners_root): + store = _shared_store() + image = [{"type": "image_url", "image_url": {"url": "https://example.test/photo.png"}}] + turn = { + "version": 1, + "messages": [ + {"role": "user", "content": image}, + {"role": "assistant", "content": "saw it"}, + ], + } + store.append( + "web-image", + "user", + "", + attachments=[ + { + "type": "image", + "filename": "photo.png", + "path": "/tmp/photo.png", + } + ], + ) + store.append("web-image", "assistant", "saw it", metadata={"model_turn": turn}) + + assert [row["role"] for row in store.messages("web-image")] == ["user", "assistant"] + assert store.messages("web-image")[1]["metadata"] == {} + summary = store.list_sessions()[0] + assert (summary["message_count"], summary["title"], summary["last_message"]) == ( + 2, + "", + "saw it", + ) + assert store.conversation_history("web-image") == [ + {"role": "assistant", "content": "saw it"} + ] + assert store.model_history("web-image") == turn["messages"] + + def test_image_only_records_do_not_consume_text_history_budget(self, partners_root): + store = _shared_store() + store.append("text-budget", "user", "before") + store.append( + "text-budget", + "user", + "", + attachments=[ + { + "type": "image", + "filename": "photo.png", + } + ], + ) + store.append("text-budget", "assistant", "saw it") + + assert store.conversation_history("text-budget", max_messages=2) == [ + {"role": "user", "content": "before"}, + {"role": "assistant", "content": "saw it"}, + ] + + @pytest.mark.parametrize("attachments", ["photo.png", ["photo.png"], [{}], [{"type": "image"}]]) + def test_malformed_attachments_do_not_admit_empty_records(self, partners_root, attachments): + store = _shared_store() + store._path("bad").write_text( + json.dumps( + { + "role": "user", + "content": "", + "attachments": attachments, + } + ) + + "\n", + encoding="utf-8", + ) + + assert store.messages("bad") == [] + assert store.messages_page("bad")["total"] == 0 + assert store.model_history("bad") == [] + def test_delete_removes_file_and_index(self, partners_root): store = _shared_store() store.append("web-a", "user", "hi")