diff --git a/deeptutor/agents/question/capability.py b/deeptutor/agents/question/capability.py index 6753560a7..8870c706f 100644 --- a/deeptutor/agents/question/capability.py +++ b/deeptutor/agents/question/capability.py @@ -18,7 +18,7 @@ from typing import Any from deeptutor.agents._shared.capability_result import emit_capability_result from deeptutor.core.capability_protocol import TurnCapability -from deeptutor.core.context import UnifiedContext +from deeptutor.core.context import Attachment, UnifiedContext from deeptutor.core.trace import merge_trace_metadata from deeptutor.i18n import StatusI18n from deeptutor.runtime.agentic.usage import UsageTracker @@ -238,7 +238,8 @@ class DeepQuestionCapability(TurnCapability): async with stream.stage("exploring", source=self.name): await stream.thinking(message, source=self.name, stage="exploring") - if pdf_attachment and pdf_attachment.base64: + paper_bytes = await _uploaded_paper_bytes(pdf_attachment, context.session_id) + if paper_bytes is not None: # Bridge MinerU's progress lines (emitted from the parser worker # thread) back onto the event loop so the trace panel streams them # live — model downloads and per-page parsing would otherwise look @@ -266,7 +267,7 @@ class DeepQuestionCapability(TurnCapability): # so write the file and close it before parsing. with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as temp_dir: temp_pdf = Path(temp_dir) / "paper.pdf" - temp_pdf.write_bytes(base64.b64decode(pdf_attachment.base64)) + temp_pdf.write_bytes(paper_bytes) templates, _ = await parse_exam_paper_to_templates( temp_pdf, max_questions=max_questions, @@ -466,3 +467,26 @@ class DeepQuestionCapability(TurnCapability): ) return _trace_bridge + + +async def _uploaded_paper_bytes(attachment: Attachment | None, session_id: str) -> bytes | None: + """Bytes of the uploaded exam paper, or ``None`` when the turn has none. + + The turn executor keeps every upload in the attachment store and clears the + inline ``base64`` of each document it has extracted, so a paper sent from + the web composer arrives here as a stored attachment only. + """ + if attachment is None: + return None + if attachment.base64: + return base64.b64decode(attachment.base64) + if not (attachment.id and session_id): + return None + from deeptutor.services.storage import get_attachment_store + + path = get_attachment_store().resolve_path( + session_id=session_id, attachment_id=attachment.id, filename=attachment.filename + ) + if path is None: + return None + return await asyncio.to_thread(path.read_bytes) diff --git a/tests/core/test_capabilities_runtime.py b/tests/core/test_capabilities_runtime.py index 7c2313e5d..755da0c06 100644 --- a/tests/core/test_capabilities_runtime.py +++ b/tests/core/test_capabilities_runtime.py @@ -398,6 +398,92 @@ async def test_deep_question_mimic_parses_a_closed_copy_of_the_uploaded_pdf( assert not captured["path"].exists() # the temporary copy is cleaned up +@pytest.mark.asyncio +async def test_deep_question_mimic_reads_a_pruned_upload_from_the_attachment_store( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, +) -> None: + # The turn executor keeps the uploaded bytes in the attachment store and + # clears ``base64`` on every document it extracted, so a web upload reaches + # the capability without inline bytes. Mimic must still parse the paper + # instead of falling back to the plain-text "[Attached Documents]" hint. + import deeptutor.agents.question.history as question_history + import deeptutor.agents.question.mimic_source as mimic_source + import deeptutor.agents.question.pipeline as question_pipeline + import deeptutor.agents.question.request_config as request_config + import deeptutor.services.config as services_config + import deeptutor.services.storage as storage + from deeptutor.services.storage.attachment_store import LocalDiskAttachmentStore + + paper = b"%PDF-1.4\n% final exam\n" + store = LocalDiskAttachmentStore(root=tmp_path / "attachments") + url = await store.put( + session_id="sess-1", + attachment_id="att-1", + filename="final.pdf", + data=paper, + mime_type="application/pdf", + ) + captured: dict[str, Any] = {} + + async def fake_parse(paper_path: str | Path, **kwargs: Any) -> tuple[list, dict]: + captured["bytes"] = Path(paper_path).read_bytes() + captured["paper_mode"] = kwargs["paper_mode"] + return [], {} + + class FakePipeline: + def __init__(self, **_kwargs: Any) -> None: + pass + + async def run(self, **kwargs: Any) -> None: + captured["templates_override"] = kwargs.get("templates_override") + captured["user_message"] = kwargs["user_message"] + + async def no_history(_session_id: str) -> list: + return [] + + monkeypatch.setattr(storage, "get_attachment_store", lambda: store) + monkeypatch.setattr(mimic_source, "parse_exam_paper_to_templates", fake_parse) + monkeypatch.setattr(question_pipeline, "QuestionPipeline", FakePipeline) + monkeypatch.setattr(question_history, "load_session_quiz_history", no_history) + monkeypatch.setattr(request_config, "build_question_runtime_config", lambda **_kw: {}) + monkeypatch.setattr(services_config, "load_config_with_main", lambda _name: {}) + + context = UnifiedContext( + session_id="sess-1", + user_message="[Attached Documents]\n--- final.pdf ---\nTask 1 ...\n\nMake questions like this", + language="en", + attachments=[ + Attachment( + type="pdf", + id="att-1", + url=url, + filename="final.pdf", + mime_type="application/pdf", + base64="", + extracted_text="Task 1 ...", + ) + ], + config_overrides={"mode": "mimic"}, + ) + capability = DeepQuestionCapability() + await _collect_events( + lambda bus: capability._run_mimic_mode( + context=context, + stream=bus, + kb_name=None, + output_dir=tmp_path / "out", + overrides={"mode": "mimic"}, + history_context="", + num_questions=1, + ) + ) + + assert captured.get("paper_mode") == "upload" + assert captured["bytes"] == paper + assert captured["templates_override"] == [] + + @pytest.mark.asyncio async def test_deep_research_capability_delegates_to_pipeline( monkeypatch: pytest.MonkeyPatch,