Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix(turns): keep prior conversation images readable on later turns (#1438) (#1443)

ZQR11017b863c8b1d98
diff --git a/deeptutor/services/config/__init__.py b/deeptutor/services/config/__init__.py
index 1483bbd8c..30e21fe68 100644
--- a/deeptutor/services/config/__init__.py
+++ b/deeptutor/services/config/__init__.py
@@ -32,6 +32,7 @@ from .runtime_settings import (
ensure_runtime_settings_files,
export_runtime_settings_to_env,
get_chat_attachment_limits,
+ get_prior_image_reinject_limit,
get_runtime_settings_service,
get_ws_max_size,
load_auth_settings,
@@ -97,6 +98,7 @@ __all__ = [
"export_runtime_settings_to_env",
"get_chat_attachment_limits",
"get_runtime_settings_service",
+ "get_prior_image_reinject_limit",
"get_ws_max_size",
"load_auth_settings",
"load_graphrag_settings",
diff --git a/deeptutor/services/config/runtime_settings.py b/deeptutor/services/config/runtime_settings.py
index 0ef52bd64..09900a4bc 100644
--- a/deeptutor/services/config/runtime_settings.py
+++ b/deeptutor/services/config/runtime_settings.py
@@ -60,6 +60,11 @@ DEFAULT_SYSTEM_SETTINGS: dict[str, Any] = {
"chat_attachment_max_total_mb": 25,
"chat_attachment_max_chars_per_doc": 200_000,
"chat_attachment_max_chars_total": 150_000,
+ # Images the manifest cannot carry across turns are re-attached by the
+ # turn executor instead (#1438). This bounds how many of a conversation's
+ # earlier images ride along on every later turn — a re-sent payload, so
+ # it is a policy like the caps above, not an LLM budget.
+ "chat_prior_image_reinject_max": 4,
}
# Clamp bounds for the chat attachment knobs. The MB ceilings are deliberately
@@ -68,6 +73,9 @@ DEFAULT_SYSTEM_SETTINGS: dict[str, Any] = {
CHAT_ATTACHMENT_MAX_FILE_MB_RANGE = (1, 1024)
CHAT_ATTACHMENT_MAX_TOTAL_MB_RANGE = (1, 2048)
CHAT_ATTACHMENT_CHARS_RANGE = (10_000, 5_000_000)
+# Zero is a real choice here — it turns prior-image re-injection off for a
+# deployment whose model or bandwidth cannot afford it.
+CHAT_PRIOR_IMAGE_REINJECT_RANGE = (0, 20)
DEFAULT_AUTH_SETTINGS: dict[str, Any] = {
"version": 1,
@@ -797,6 +805,8 @@ class RuntimeSettingsService:
payload["chat_attachment_max_chars_per_doc"] = value
if value := self._process_env_value("CHAT_ATTACHMENT_MAX_CHARS_TOTAL"):
payload["chat_attachment_max_chars_total"] = value
+ if value := self._process_env_value("CHAT_PRIOR_IMAGE_REINJECT_MAX"):
+ payload["chat_prior_image_reinject_max"] = value
return self._normalize_system(payload)
def _apply_auth_process_overrides(self, settings: dict[str, Any]) -> dict[str, Any]:
@@ -1175,6 +1185,11 @@ class RuntimeSettingsService:
},
"chat_attachment_max_file_mb": max_file_mb,
"chat_attachment_max_total_mb": max_total_mb,
+ "chat_prior_image_reinject_max": _coerce_clamped_int(
+ settings.get("chat_prior_image_reinject_max"),
+ DEFAULT_SYSTEM_SETTINGS["chat_prior_image_reinject_max"],
+ *CHAT_PRIOR_IMAGE_REINJECT_RANGE,
+ ),
"chat_attachment_max_chars_per_doc": _coerce_clamped_int(
settings.get("chat_attachment_max_chars_per_doc"),
DEFAULT_SYSTEM_SETTINGS["chat_attachment_max_chars_per_doc"],
@@ -1309,6 +1324,23 @@ def compute_ws_max_size(max_total_bytes: int) -> int:
return max(_WS_MAX_SIZE_FLOOR, inflated + 8 * 1024 * 1024)
+def get_prior_image_reinject_limit() -> int:
+ """How many earlier images a later turn re-attaches.
+
+ Read at call time like the attachment policy above, so a deployment can
+ change it without a restart, and 0 turns the behaviour off entirely.
+
+ Resolved with the seeded default rather than by subscript: a system.json
+ written before this key existed is the normal state of every upgraded
+ install, and a missing knob must not take image re-injection down with it.
+ """
+ return _coerce_clamped_int(
+ load_system_settings().get("chat_prior_image_reinject_max"),
+ DEFAULT_SYSTEM_SETTINGS["chat_prior_image_reinject_max"],
+ *CHAT_PRIOR_IMAGE_REINJECT_RANGE,
+ )
+
+
def get_ws_max_size() -> int:
"""Frame ceiling for the current settings — wire into every uvicorn launch."""
return compute_ws_max_size(get_chat_attachment_limits().max_total_bytes)
diff --git a/deeptutor/services/session/source_inventory.py b/deeptutor/services/session/source_inventory.py
index 8d0492e1b..c97e98f31 100644
--- a/deeptutor/services/session/source_inventory.py
+++ b/deeptutor/services/session/source_inventory.py
@@ -61,6 +61,12 @@ class SourceEntry:
# within the active branch's lineage. Fresh sources use the **current**
# turn's ordinal so the manifest can label them consistently.
first_seen_turn: int
+ # Set (and full_text empty) when the source exists but its text could not
+ # be served — for an attachment whose extraction produced nothing. The
+ # manifest renders the reason so the model can tell the learner *why* a
+ # file is not quotable instead of silently dropping it or asking for a
+ # blind re-upload (#1438 expected behavior 6).
+ availability_note: str = ""
@property
def char_count(self) -> int:
@@ -83,7 +89,7 @@ class SourceInventory:
def add(self, entry: SourceEntry) -> None:
if not entry.sid:
return
- if not entry.full_text.strip():
+ if not entry.full_text.strip() and not entry.availability_note:
return
existing_pos = self._index.get(entry.sid)
if existing_pos is None:
@@ -184,7 +190,9 @@ def render_manifest(inv: SourceInventory) -> tuple[str, dict[str, str]]:
if inv.is_empty():
return "", {}
- source_index: dict[str, str] = {sid: e.full_text for sid, e in _iter_sid_entries(inv)}
+ source_index: dict[str, str] = {
+ sid: e.full_text for sid, e in _iter_sid_entries(inv) if e.full_text.strip()
+ }
rendered_rows: list[str] = []
for entry in inv.entries:
rendered_rows.append(_render_row(entry))
@@ -230,6 +238,14 @@ def _format_size(char_count: int) -> str:
def _render_row(entry: SourceEntry) -> str:
+ if entry.availability_note:
+ identity = (
+ f"- id={entry.sid} type={entry.kind} name={entry.name!r} "
+ f"source: previously attached (turn {entry.first_seen_turn})"
+ )
+ if entry.fresh:
+ identity = f"- id={entry.sid} type={entry.kind} name={entry.name!r}"
+ return f"{identity}\n note: {entry.availability_note}"
if entry.fresh:
preview = _clip_preview(entry.full_text)
return f"- id={entry.sid} type={entry.kind} name={entry.name!r}\n preview: {preview!r}"
@@ -306,7 +322,28 @@ def _add_fresh(
continue
text = str(record.get("extracted_text", "") or "")
att_id = str(record.get("id", "") or "").strip()
- if not text.strip() or not att_id:
+ if not att_id:
+ continue
+ if not text.strip():
+ # The file is real but its text could not be extracted (scanned
+ # pages, an unsupported format, a failed parse). Surface the
+ # reason instead of silently dropping the attachment: the model
+ # can then tell the learner what happened and whether re-uploading
+ # is worth another try, rather than a blind "please upload again".
+ inv.add(
+ SourceEntry(
+ sid=f"at-{att_id}",
+ kind="attachment",
+ name=str(record.get("filename") or "Untitled file"),
+ full_text="",
+ fresh=True,
+ first_seen_turn=current_turn_ordinal,
+ availability_note=(
+ "text extraction produced no content for this file "
+ "(scanned or unsupported format); it cannot be quoted"
+ ),
+ )
+ )
continue
inv.add(
SourceEntry(
@@ -456,6 +493,23 @@ async def _collect_from_user_message(
continue
text = str(att.get("extracted_text") or "")
if not text.strip():
+ # Same as the fresh path: an earlier turn's file whose extraction
+ # produced nothing still gets a manifest row, with the reason
+ # attached, so the failure is visible on every later turn.
+ inv.add(
+ SourceEntry(
+ sid=sid,
+ kind="attachment",
+ name=str(att.get("filename") or "Untitled file"),
+ full_text="",
+ fresh=False,
+ first_seen_turn=turn_ordinal,
+ availability_note=(
+ "text extraction produced no content for this file "
+ "(scanned or unsupported format); it cannot be quoted"
+ ),
+ )
+ )
continue
inv.add(
SourceEntry(
@@ -642,6 +696,72 @@ async def _load_lineage(
return chain
+# ----- Prior-image collection (#1438) -------------------------------------
+
+
+# Images are the one attachment kind with no cross-turn path: the manifest
+# deliberately excludes them (they reach a vision model as multimodal blocks
+# on the upload turn only), so from the second turn onward the model could not
+# see an image it was just discussing. The turn executor re-attaches what this
+# collector returns; the cap keeps a long image-heavy conversation from
+# re-sending unbounded payloads every turn, and lives in system settings
+# beside the other chat-attachment policy — a deployment whose model or
+# bandwidth cannot afford the re-send sets it to 0.
+
+
+async def collect_prior_image_attachments(
+ store: SessionStoreProtocol,
+ *,
+ session_id: str,
+ leaf_message_id: int | None,
+ exclude_urls: set[str] | None = None,
+ limit: int | None = None,
+) -> list[dict[str, Any]]:
+ """Return this conversation's earlier image attachments, most recent first.
+
+ Walks the active branch's persisted user messages — the same lineage the
+ manifest's historical walk uses — and collects every image entry that
+ carries an attachment-store URL, deduplicated by URL. The turn executor
+ re-attaches the result (URL-only; the multimodal layer resolves the bytes
+ from the attachment store at request time). Text attachments are not
+ collected here: they are re-served by the inventory's own historical walk.
+ """
+ if limit is None:
+ from deeptutor.services.config import get_prior_image_reinject_limit
+
+ limit = get_prior_image_reinject_limit()
+ if limit <= 0:
+ return []
+ excluded_urls = exclude_urls or set()
+ collected: list[dict[str, Any]] = []
+ seen_urls: set[str] = set()
+ lineage = await _load_lineage(store, session_id, leaf_message_id)
+ for msg in reversed(lineage):
+ if msg.get("role") != "user":
+ continue
+ for att in msg.get("attachments") or []:
+ mime = str(att.get("mime_type", "")).lower()
+ url = str(att.get("url", "") or "").strip()
+ if not url or url in seen_urls or url in excluded_urls:
+ continue
+ if not mime.startswith(_IMAGE_MIME_PREFIX):
+ continue
+ seen_urls.add(url)
+ collected.append(
+ {
+ "id": str(att.get("id", "") or ""),
+ "type": "image",
+ "url": url,
+ "base64": "",
+ "filename": str(att.get("filename", "") or ""),
+ "mime_type": str(att.get("mime_type", "") or ""),
+ }
+ )
+ if len(collected) >= limit:
+ return collected
+ return collected
+
+
# ----- Per-type resolvers shared by fresh + historical paths --------------
diff --git a/deeptutor/services/session/turns/executor.py b/deeptutor/services/session/turns/executor.py
index 3cef6a508..96616eee2 100644
--- a/deeptutor/services/session/turns/executor.py
+++ b/deeptutor/services/session/turns/executor.py
@@ -353,6 +353,38 @@ class TurnExecutor:
for r in attachment_records
]
+ # Images attached in earlier turns of this conversation stay
+ # readable (#1438): re-attach them (URL-only; the multimodal layer
+ # resolves the bytes from the attachment store at request time) so
+ # a vision model keeps seeing an image the learner attached before.
+ # Text attachments are not repeated here — the source inventory's
+ # historical walk already serves them. Selection tutoring is
+ # deliberately isolated from conversation context.
+ if not selection_tutor_context:
+ from deeptutor.services.session.source_inventory import (
+ collect_prior_image_attachments,
+ )
+
+ prior_images = await collect_prior_image_attachments(
+ self.store,
+ session_id=session_id,
+ leaf_message_id=branch_parent_id,
+ exclude_urls={
+ str(r.get("url") or "") for r in attachment_records if r.get("url")
+ },
+ )
+ attachments.extend(
+ Attachment(
+ type="image",
+ url=rec["url"],
+ base64="",
+ filename=rec.get("filename", ""),
+ mime_type=rec.get("mime_type", ""),
+ id=rec.get("id", ""),
+ )
+ for rec in prior_images
+ )
+
sidebar_system_context = ""
if selection_tutor_context:
sidebar_system_context = _format_selection_tutor_context(
diff --git a/tests/api/test_unified_ws_turn_runtime.py b/tests/api/test_unified_ws_turn_runtime.py
index 2ace4c8e0..05f5bace9 100644
--- a/tests/api/test_unified_ws_turn_runtime.py
+++ b/tests/api/test_unified_ws_turn_runtime.py
@@ -1050,3 +1050,218 @@ async def test_a_null_mode_on_the_wire_keeps_the_conversation_in_the_mode_it_was
assert resolve("review", "outline") == "review"
# And a conversation that has never had one stays unrecorded.
assert resolve(None, None) is None
+
+
+async def test_prior_image_attachments_are_reattached_on_the_next_turn(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path,
+) -> None:
+ """An image attached in turn 1 must still reach a vision model on turn 2.
+
+ Multimodal blocks exist only on the upload turn and the source manifest
+ deliberately excludes images, so without re-attachment the model loses
+ the image entirely and asks the learner to resend it (#1438). The
+ executor re-attaches the conversation's earlier images (URL-only; the
+ multimodal layer resolves the bytes from the attachment store), and the
+ new message row must not duplicate them.
+ """
+ store = SQLiteSessionStore(tmp_path / "chat_history.db")
+ runtime = TurnRuntimeManager(store)
+ captured: list[list[SimpleNamespace]] = []
+
+ class FakeContextBuilder:
+ def __init__(self, *_args, **_kwargs) -> None:
+ pass
+
+ async def build(self, **kwargs):
+ return SimpleNamespace(
+ conversation_history=[],
+ conversation_summary="",
+ context_text="",
+ token_count=0,
+ budget=0,
+ )
+
+ class FakeOrchestrator:
+ async def handle(self, context):
+ captured.append(list(context.attachments or []))
+ yield StreamEvent(
+ type=StreamEventType.CONTENT,
+ source="chat",
+ stage="responding",
+ content="ok",
+ metadata={"call_kind": "llm_final_response"},
+ )
+ yield StreamEvent(type=StreamEventType.DONE, source="chat")
+
+ monkeypatch.setattr("deeptutor.services.llm.config.get_llm_config", lambda: SimpleNamespace())
+ monkeypatch.setattr(
+ "deeptutor.services.session.context_builder.ContextBuilder", FakeContextBuilder
+ )
+ monkeypatch.setattr("deeptutor.runtime.orchestrator.ChatOrchestrator", FakeOrchestrator)
+ monkeypatch.setattr(
+ "deeptutor.book.context.build_book_context",
+ lambda *_args, **_kwargs: SimpleNamespace(text="", references=[], warnings=[]),
+ )
+ monkeypatch.setattr(
+ "deeptutor.services.memory.get_memory_store",
+ lambda: SimpleNamespace(read_l3_concat=lambda: "", emit=_noop_async),
+ )
+ monkeypatch.setattr(
+ "deeptutor.services.skill.get_skill_service",
+ _fake_skill_service,
+ )
+ monkeypatch.setattr(
+ "deeptutor.services.persona.get_persona_service",
+ _fake_persona_service,
+ )
+
+ image_attachment = {
+ "type": "image",
+ "url": "/files/attachments/s1/img-1/shot.png",
+ "filename": "shot.png",
+ "mime_type": "image/png",
+ "base64": "",
+ }
+
+ session, turn1 = await runtime.start_turn(
+ {
+ "type": "start_turn",
+ "content": "what is in this picture?",
+ "session_id": None,
+ "capability": None,
+ "tools": [],
+ "knowledge_bases": [],
+ "attachments": [image_attachment],
+ "language": "en",
+ "config": {},
+ }
+ )
+ async for _event in runtime.subscribe_turn(turn1["id"], after_seq=0):
+ pass
+
+ _session2, turn2 = await runtime.start_turn(
+ {
+ "type": "start_turn",
+ "content": "and the top left corner?",
+ "session_id": session["id"],
+ "capability": None,
+ "tools": [],
+ "knowledge_bases": [],
+ "attachments": [],
+ "language": "en",
+ "config": {},
+ }
+ )
+ async for _event in runtime.subscribe_turn(turn2["id"], after_seq=0):
+ pass
+
+ assert [att.url for att in captured[0]] == [image_attachment["url"]]
+ # Turn 2 carries no payload attachment, yet the conversation's earlier
+ # image is re-attached for the model. (The payload contract has no
+ # attachment id, so the URL is the stable identity across turns.)
+ assert len(captured[1]) == 1
+ reattached = captured[1][0]
+ assert reattached.base64 == ""
+ assert reattached.url == image_attachment["url"]
+
+ # The turn-2 message row must not duplicate the attachment: the image
+ # belongs to turn 1's row and the re-attachment is per-turn context only.
+ rows = await store.get_messages(session["id"])
+ user_rows = [m for m in rows if m.get("role") == "user"]
+ assert user_rows[-1].get("attachments") == []
+
+
+async def test_reattaching_the_same_image_does_not_duplicate_it(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path,
+) -> None:
+ store = SQLiteSessionStore(tmp_path / "chat_history.db")
+ runtime = TurnRuntimeManager(store)
+ captured: list[list[SimpleNamespace]] = []
+
+ class FakeContextBuilder:
+ def __init__(self, *_args, **_kwargs) -> None:
+ pass
+
+ async def build(self, **kwargs):
+ return SimpleNamespace(
+ conversation_history=[],
+ conversation_summary="",
+ context_text="",
+ token_count=0,
+ budget=0,
+ )
+
+ class FakeOrchestrator:
+ async def handle(self, context):
+ captured.append(list(context.attachments or []))
+ yield StreamEvent(type=StreamEventType.DONE, source="chat")
+
+ monkeypatch.setattr("deeptutor.services.llm.config.get_llm_config", lambda: SimpleNamespace())
+ monkeypatch.setattr(
+ "deeptutor.services.session.context_builder.ContextBuilder", FakeContextBuilder
+ )
+ monkeypatch.setattr("deeptutor.runtime.orchestrator.ChatOrchestrator", FakeOrchestrator)
+ monkeypatch.setattr(
+ "deeptutor.book.context.build_book_context",
+ lambda *_args, **_kwargs: SimpleNamespace(text="", references=[], warnings=[]),
+ )
+ monkeypatch.setattr(
+ "deeptutor.services.memory.get_memory_store",
+ lambda: SimpleNamespace(read_l3_concat=lambda: "", emit=_noop_async),
+ )
+ monkeypatch.setattr(
+ "deeptutor.services.skill.get_skill_service",
+ _fake_skill_service,
+ )
+ monkeypatch.setattr(
+ "deeptutor.services.persona.get_persona_service",
+ _fake_persona_service,
+ )
+
+ image_attachment = {
+ "type": "image",
+ "url": "/files/attachments/s1/img-1/shot.png",
+ "filename": "shot.png",
+ "mime_type": "image/png",
+ "base64": "",
+ }
+ session, turn1 = await runtime.start_turn(
+ {
+ "type": "start_turn",
+ "content": "look",
+ "session_id": None,
+ "capability": None,
+ "tools": [],
+ "knowledge_bases": [],
+ "attachments": [image_attachment],
+ "language": "en",
+ "config": {},
+ }
+ )
+ async for _event in runtime.subscribe_turn(turn1["id"], after_seq=0):
+ pass
+
+ _session2, turn2 = await runtime.start_turn(
+ {
+ "type": "start_turn",
+ "content": "look again",
+ "session_id": session["id"],
+ "capability": None,
+ "tools": [],
+ "knowledge_bases": [],
+ "attachments": [image_attachment],
+ "language": "en",
+ "config": {},
+ }
+ )
+ async for _event in runtime.subscribe_turn(turn2["id"], after_seq=0):
+ pass
+
+ # The same file re-attached in turn 2 must not appear twice: the fresh
+ # record and the re-attached prior entry share one URL, and the URL is
+ # the dedupe key.
+ assert [att.url for att in captured[1]] == [image_attachment["url"]]
diff --git a/tests/services/session/test_source_inventory.py b/tests/services/session/test_source_inventory.py
index 741be032d..f963c5d86 100644
--- a/tests/services/session/test_source_inventory.py
+++ b/tests/services/session/test_source_inventory.py
@@ -11,6 +11,7 @@ from deeptutor.services.session.source_inventory import (
SourceEntry,
SourceInventory,
build_inventory,
+ collect_prior_image_attachments,
render_manifest,
serialize_referenced_transcript,
)
@@ -702,3 +703,349 @@ async def test_load_history_session_partner_missing_returns_empty(monkeypatch) -
text, _ = await _load_history_session(FakeStore(), "partner:ghost:dt-1")
assert text == ""
+
+
+# ---------------------------------------------------------------------------
+# Prior-image collection (#1438: images are the one attachment kind with no
+# cross-turn path — the manifest excludes them and multimodal blocks exist
+# only on the upload turn).
+# ---------------------------------------------------------------------------
+
+
+async def test_collect_prior_images_returns_branch_images_most_recent_first() -> None:
+ messages = [
+ {
+ "id": 1,
+ "role": "user",
+ "content": "first",
+ "parent_message_id": None,
+ "attachments": [
+ {
+ "id": "img-1",
+ "type": "image",
+ "filename": "first.png",
+ "mime_type": "image/png",
+ "url": "/files/attachments/s1/img-1/first.png",
+ }
+ ],
+ },
+ {"id": 2, "role": "assistant", "content": "ok", "parent_message_id": 1, "attachments": []},
+ {
+ "id": 3,
+ "role": "user",
+ "content": "second",
+ "parent_message_id": 2,
+ "attachments": [
+ {
+ "id": "img-2",
+ "type": "image",
+ "filename": "second.png",
+ "mime_type": "image/png",
+ "url": "/files/attachments/s1/img-2/second.png",
+ }
+ ],
+ },
+ ]
+ store = FakeStore(messages=messages)
+
+ collected = await collect_prior_image_attachments(store, session_id="s1", leaf_message_id=None)
+
+ assert [entry["id"] for entry in collected] == ["img-2", "img-1"]
+ assert all(entry["type"] == "image" for entry in collected)
+ assert collected[0]["url"].endswith("second.png")
+
+
+async def test_collect_prior_images_skips_non_images_and_url_less_entries() -> None:
+ messages = [
+ {
+ "id": 1,
+ "role": "user",
+ "content": "first",
+ "parent_message_id": None,
+ "attachments": [
+ {
+ "id": "doc-1",
+ "filename": "notes.pdf",
+ "mime_type": "application/pdf",
+ "url": "/files/attachments/s1/doc-1/notes.pdf",
+ },
+ {
+ "id": "img-nourl",
+ "type": "image",
+ "filename": "legacy.png",
+ "mime_type": "image/png",
+ "url": "",
+ },
+ ],
+ }
+ ]
+ store = FakeStore(messages=messages)
+
+ collected = await collect_prior_image_attachments(store, session_id="s1", leaf_message_id=None)
+
+ assert collected == []
+
+
+async def test_collect_prior_images_dedupes_and_excludes_current_ids() -> None:
+ messages = [
+ {
+ "id": 1,
+ "role": "user",
+ "content": "first",
+ "parent_message_id": None,
+ "attachments": [
+ {
+ "id": "img-1",
+ "type": "image",
+ "filename": "shot.png",
+ "mime_type": "image/png",
+ "url": "/files/attachments/s1/img-1/shot.png",
+ }
+ ],
+ },
+ {
+ "id": 2,
+ "role": "user",
+ "content": "again",
+ "parent_message_id": 1,
+ "attachments": [
+ {
+ "id": "img-1",
+ "type": "image",
+ "filename": "shot.png",
+ "mime_type": "image/png",
+ "url": "/files/attachments/s1/img-1/shot.png",
+ }
+ ],
+ },
+ ]
+ store = FakeStore(messages=messages)
+
+ collected = await collect_prior_image_attachments(store, session_id="s1", leaf_message_id=None)
+ assert [entry["id"] for entry in collected] == ["img-1"]
+
+ reattached = await collect_prior_image_attachments(
+ store,
+ session_id="s1",
+ leaf_message_id=None,
+ exclude_urls={"/files/attachments/s1/img-1/shot.png"},
+ )
+ assert reattached == []
+
+
+async def test_collect_prior_images_caps_at_limit() -> None:
+ messages = [
+ {
+ "id": idx + 1,
+ "role": "user" if idx % 2 == 0 else "assistant",
+ "content": f"m{idx}",
+ "parent_message_id": None if idx == 0 else idx,
+ "attachments": (
+ [
+ {
+ "id": f"img-{idx}",
+ "type": "image",
+ "filename": f"shot-{idx}.png",
+ "mime_type": "image/png",
+ "url": f"/files/attachments/s1/img-{idx}/shot-{idx}.png",
+ }
+ ]
+ if idx % 2 == 0
+ else []
+ ),
+ }
+ for idx in range(10)
+ ]
+ store = FakeStore(messages=messages)
+
+ collected = await collect_prior_image_attachments(
+ store, session_id="s1", leaf_message_id=None, limit=3
+ )
+
+ assert [entry["id"] for entry in collected] == ["img-8", "img-6", "img-4"]
+
+
+# ---------------------------------------------------------------------------
+# Unavailable-attachment surfacing (#1438 expected behavior 6: a file whose
+# text extraction produced nothing must show a reason in the manifest instead
+# of being silently skipped — a silent skip is why the model asks the learner
+# to re-upload without ever saying why).
+# ---------------------------------------------------------------------------
+
+
+def test_inventory_accepts_note_only_entries() -> None:
+ """An entry with no text but an availability reason is kept."""
+ inv = SourceInventory()
+ inv.add(
+ SourceEntry(
+ sid="at-foo",
+ kind="attachment",
+ name="scan.pdf",
+ full_text=" ",
+ fresh=True,
+ first_seen_turn=1,
+ availability_note="text extraction produced no content",
+ )
+ )
+ assert not inv.is_empty()
+
+
+async def test_fresh_attachment_without_extracted_text_shows_a_reason() -> None:
+ store = FakeStore(messages=[])
+ inv = await build_inventory(
+ store,
+ session_id="s1",
+ leaf_message_id=None,
+ current_turn_ordinal=1,
+ fresh_attachment_records=[
+ {
+ "id": "att-scan",
+ "type": "file",
+ "filename": "scan.pdf",
+ "mime_type": "application/pdf",
+ "extracted_text": "",
+ }
+ ],
+ fresh_notebook_records=[],
+ fresh_book_context_text="",
+ fresh_book_references=[],
+ fresh_history_session_ids=[],
+ fresh_question_entry_ids=[],
+ )
+ manifest, source_index = render_manifest(inv)
+
+ # The row exists so the model can name the file and say why it cannot
+ # quote it — instead of silently pretending nothing was attached.
+ assert "at-att-scan" in manifest
+ assert "scan.pdf" in manifest
+ assert "extraction" in manifest
+ # But there is no full text to serve: the sid must not advertise itself
+ # as readable through read_source.
+ assert "at-att-scan" not in source_index
+
+
+async def test_historical_attachment_without_extracted_text_shows_a_reason() -> None:
+ messages = [
+ {
+ "id": 1,
+ "role": "user",
+ "content": "first",
+ "parent_message_id": None,
+ "attachments": [
+ {
+ "id": "att-old",
+ "filename": "scanned.pdf",
+ "extracted_text": "",
+ "mime_type": "application/pdf",
+ }
+ ],
+ "metadata": {"request_snapshot": {}},
+ }
+ ]
+ store = FakeStore(messages=messages)
+ inv = await build_inventory(
+ store,
+ session_id="s1",
+ leaf_message_id=None,
+ current_turn_ordinal=2,
+ fresh_attachment_records=[],
+ fresh_notebook_records=[],
+ fresh_book_context_text="",
+ fresh_book_references=[],
+ fresh_history_session_ids=[],
+ fresh_question_entry_ids=[],
+ )
+ manifest, source_index = render_manifest(inv)
+
+ assert "at-att-old" in manifest
+ assert "extraction" in manifest
+ assert "at-att-old" not in source_index
+
+
+def _image_messages(count: int) -> list[dict[str, Any]]:
+ return [
+ {
+ "id": index,
+ "role": "user",
+ "attachments": [
+ {
+ "id": f"img-{index}",
+ "type": "image",
+ "filename": f"{index}.png",
+ "mime_type": "image/png",
+ "url": f"/files/attachments/s1/img-{index}/{index}.png",
+ }
+ ],
+ }
+ for index in range(1, count + 1)
+ ]
+
+
+async def test_prior_image_reinjection_is_bounded_by_system_settings(monkeypatch) -> None:
+ """The cap is deployment policy, not a number frozen into the collector.
+
+ Every later turn re-sends what this returns, so an operator whose model or
+ bandwidth cannot afford four images has to be able to say so.
+ """
+ store = FakeStore(messages=_image_messages(6))
+ monkeypatch.setattr(
+ "deeptutor.services.config.get_prior_image_reinject_limit",
+ lambda: 2,
+ )
+
+ collected = await collect_prior_image_attachments(store, session_id="s1", leaf_message_id=None)
+
+ assert [entry["id"] for entry in collected] == ["img-6", "img-5"]
+
+
+async def test_a_zero_limit_turns_prior_image_reinjection_off(monkeypatch) -> None:
+ """0 is a real setting: no re-injection, and no lineage read to do it."""
+ store = FakeStore(messages=_image_messages(3))
+ monkeypatch.setattr(
+ "deeptutor.services.config.get_prior_image_reinject_limit",
+ lambda: 0,
+ )
+
+ assert await collect_prior_image_attachments(store, session_id="s1", leaf_message_id=None) == []
+
+
+async def test_a_system_json_written_before_this_knob_existed_still_reinjects(
+ monkeypatch,
+) -> None:
+ """Every upgraded install has one, and it must not take the feature down.
+
+ Reading the knob by subscript turned a missing key into a KeyError raised
+ from inside turn setup, which surfaced as unrelated session tests failing.
+ """
+ from deeptutor.services.config import runtime_settings
+
+ monkeypatch.setattr(
+ runtime_settings,
+ "load_system_settings",
+ lambda: {"chat_attachment_max_file_mb": 20},
+ )
+ store = FakeStore(messages=_image_messages(2))
+
+ collected = await collect_prior_image_attachments(store, session_id="s1", leaf_message_id=None)
+
+ assert [entry["id"] for entry in collected] == ["img-2", "img-1"]
+
+
+def test_the_reinject_cap_is_clamped_into_a_sane_range() -> None:
+ from deeptutor.services.config.runtime_settings import (
+ CHAT_PRIOR_IMAGE_REINJECT_RANGE,
+ DEFAULT_SYSTEM_SETTINGS,
+ )
+
+ low, high = CHAT_PRIOR_IMAGE_REINJECT_RANGE
+ assert low == 0, "0 must stay reachable: it is how the feature is turned off"
+ assert low <= DEFAULT_SYSTEM_SETTINGS["chat_prior_image_reinject_max"] <= high