Skip to content

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

test(co-writer): lock router contract for CRUD, 4xx payloads, export failures (#1768)

evan188199-techf0348731de32
diff --git a/evidence/co-writer-tests-20261003/README.md b/evidence/co-writer-tests-20261003/README.md
new file mode 100644
index 000000000..600b3e043
--- /dev/null
+++ b/evidence/co-writer-tests-20261003/README.md
@@ -0,0 +1,72 @@
+# co_writer 路由契约补测 — 证据(2026-10-03)
+
+对应任务卡:AGEN-289(test: co_writer 路由契约补测,覆盖率备选 20)。
+基线:`origin/main` @ `ef2d9e5c3`(release: v1.6.12),来自 `audit/coverage-gaps-20261003` 证据的备选节:
+`deeptutor/api/routers/co_writer.py` — 246 缺失 / 40.0%。
+
+## 产物
+
+- 测试文件:`tests/api/routers/test_co_writer_contract.py`(新增目录 `tests/api/routers/`,含空 `__init__.py`)
+- 分支:`myfork/test/co-writer-contract-20261003`(基于 origin/main @ ef2d9e5c3)
+- 本目录:`evidence/co-writer-tests-20261003/`(说明 + 完整 pytest 输出)
+
+## 测试命令与数字
+
+```bash
+python -m pytest tests/api/routers/test_co_writer_contract.py -v
+# 40 passed in 0.51s
+
+python -m pytest tests/api/routers/test_co_writer_contract.py tests/api/test_co_writer.py -q
+# 74 passed(与既有 co_writer 测试同跑无互相污染)
+
+ruff check tests/api/routers/test_co_writer_contract.py # 通过
+ruff format --check 同文件 # 通过
+```
+
+运行环境:/Users/Shared/DeepTutor/.venv(Python 3.13.13, fastapi 0.141.1, pydantic 2.13.4, pytest 9.1.1)。
+
+## 结论(跑通:PASS)
+
+40/40 通过,0 失败。当前 origin/main 实现已满足本卡锁定的全部契约,**没有产生需要修复卡的失败用例**——"失败测试集"在此为空集;本集合的价值是把 40.0% 的路由契约空白固化为回归保护,后续任何改动破坏契约时会立即转红。
+
+## 契约覆盖清单
+
+会话/草稿 CRUD 请求形状(13 例)
+- POST /documents:完整响应形状 {id,title,content,created_at,updated_at};id 满足 ^[0-9a-f]{8,32}$;无标题时从首个 heading 派生;空请求体默认 "Untitled draft"
+- GET /documents:仅返回 summary 视图(无 content 字段),按 updated_at 倒序,preview 截断 ≤161 字符并以 … 结尾
+- GET/PUT/DELETE /documents/{id}:读写删除与持久化一致性;PUT 空对象为 no-op(字段保留)
+- 未知/畸形 doc id(合法形状缺失、大写、非 hex、过短、过长)在三条路由上一律 404,detail 为 "Document not found";DELETE 后重复删除 404(非幂等契约固化)
+
+非法 payload 4xx(10 例)
+- EditRequest:缺 text/instruction、非法 action/source 字面量、text 超 600,000、instruction 超 10,000 → 422,且验证失败不触达 agent
+- ReactEditRequest:非法 mode/tools 字面量、selected_text 超 120,000 → 422;mode=none 且空 instruction → 400;空白选区 → 400
+- edit-react/stream 预检:非法 payload 在进入 SSE 之前以 JSON 4xx 返回(不产生 event: 流)
+- ExportDocxRequest:content 超 600,000 → 422
+- CreateDocumentRequest/UpdateDocumentRequest:非字符串字段 → 422
+- import/docx:.doc 与非 .docx 后缀 → 400;空文件 → 400(detail 含 "empty")
+
+导出/导入失败分支(4 例)
+- export:converter 抛 DocxConversionError → 400(detail 透传);抛任意异常 → 500
+- export:Content-Disposition 对 `\/:*?"<>|` 等不安全字符统一替换为 "-"(filename="a-b-c-d-e-f-g-h-i.docx")
+- import:真实损坏字节 → 400(真实 DocxConversionError 路径);converter 抛任意异常 → 500
+
+Edit 动作与 agent 契约(7 例)
+- /documents/actions/edit:请求字段逐一透传给 agent(text/instruction/action/source/kb_name),响应锁定 {edited_text, operation_id}
+- /documents/actions/automark:text 透传,响应 {marked_text, operation_id}
+- agent 抛异常 → edit/automark 均 500 且 detail 含原始异常信息
+- edit-react:输出围栏剥离(```markdown…``` → 纯文本)、tools_used 上报、operation_id 形如 \d{8}_\d{6}_[0-9a-f]{6};rag 无 kb_name 时跳过、重复 tool 去重、kb_name 透传 gather_context;每次编辑落 history(action=react_edit)
+
+history / tool-calls 端点(2 例)
+- GET /documents/history → {history, total};GET /documents/history/{id} → 单条或 404 "Operation not found"
+- GET /documents/tool-calls/{id} → 读取 {op}_*.json 或 404 "Tool call not found"
+
+## 隔离与安全
+
+- 存储经 monkeypatch 指向 tmp_path(_StubPathService),agent 为纯 stub,history/tool-calls 写入 tmp_path,不触碰真实 workspace、不发起任何 LLM 调用。
+- 沿用 tests/api/test_co_writer.py 的模块级 load_config_with_main 桩(新 worktree 缺 data/user/settings/main.yaml,router 导入期需要)。
+- 未修改任何产品代码(git diff 仅新增测试与证据文件)。
+
+## 备注
+
+- `markdown_to_docx` 实际不抛 DocxConversionError,export 的 400 分支当前不可自然触达(测试通过 monkeypatch 验证该分支行为正确);这属于现状记录,不构成缺陷。
+- 遵守卡面规则:不向上游开 PR;PR 草稿标题/描述见完成评论,由人决定是否提交。
diff --git a/evidence/co-writer-tests-20261003/pytest-run.txt b/evidence/co-writer-tests-20261003/pytest-run.txt
new file mode 100644
index 000000000..80eae8b10
--- /dev/null
+++ b/evidence/co-writer-tests-20261003/pytest-run.txt
@@ -0,0 +1,51 @@
+============================= test session starts ==============================
+platform darwin -- Python 3.13.13, pytest-9.1.1, pluggy-1.6.0 -- /Users/Shared/DeepTutor/.venv/bin/python
+cachedir: .pytest_cache
+rootdir: /Users/xzh/services/ai-development/multica-pilot/workspaces/agents-plan-5fede2af789a/agen-289-c9175b250985/workdir/dt-cowriter-wt
+configfile: pyproject.toml
+plugins: cov-7.1.0, devtools-0.12.2, asyncio-1.4.0, anyio-4.14.2
+asyncio: mode=Mode.STRICT, debug=False, asyncio_default_fixture_loop_scope=function, asyncio_default_test_loop_scope=function
+collecting ... collected 40 items
+
+tests/api/routers/test_co_writer_contract.py::test_create_document_returns_full_document_shape PASSED [ 2%]
+tests/api/routers/test_co_writer_contract.py::test_create_document_without_title_derives_it_from_first_heading PASSED [ 5%]
+tests/api/routers/test_co_writer_contract.py::test_create_document_with_empty_body_uses_defaults PASSED [ 7%]
+tests/api/routers/test_co_writer_contract.py::test_create_document_rejects_non_string_fields PASSED [ 10%]
+tests/api/routers/test_co_writer_contract.py::test_list_documents_returns_summary_views_without_content PASSED [ 12%]
+tests/api/routers/test_co_writer_contract.py::test_list_documents_truncates_preview_at_160_chars PASSED [ 15%]
+tests/api/routers/test_co_writer_contract.py::test_get_document_returns_persisted_content PASSED [ 17%]
+tests/api/routers/test_co_writer_contract.py::test_update_document_applies_title_and_content PASSED [ 20%]
+tests/api/routers/test_co_writer_contract.py::test_update_document_with_empty_object_keeps_fields PASSED [ 22%]
+tests/api/routers/test_co_writer_contract.py::test_update_document_rejects_non_string_title PASSED [ 25%]
+tests/api/routers/test_co_writer_contract.py::test_delete_document_returns_deleted_true_then_404 PASSED [ 27%]
+tests/api/routers/test_co_writer_contract.py::test_unknown_or_malformed_doc_ids_return_404_on_crud_routes[ffffffffffff] PASSED [ 30%]
+tests/api/routers/test_co_writer_contract.py::test_unknown_or_malformed_doc_ids_return_404_on_crud_routes[A1B2C3D4E5F6] PASSED [ 32%]
+tests/api/routers/test_co_writer_contract.py::test_unknown_or_malformed_doc_ids_return_404_on_crud_routes[g1b2c3d4e5f6] PASSED [ 35%]
+tests/api/routers/test_co_writer_contract.py::test_unknown_or_malformed_doc_ids_return_404_on_crud_routes[abc123] PASSED [ 37%]
+tests/api/routers/test_co_writer_contract.py::test_unknown_or_malformed_doc_ids_return_404_on_crud_routes[aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa] PASSED [ 40%]
+tests/api/routers/test_co_writer_contract.py::test_not_found_details_name_the_document PASSED [ 42%]
+tests/api/routers/test_co_writer_contract.py::test_edit_action_rejects_missing_fields_and_bad_literals PASSED [ 45%]
+tests/api/routers/test_co_writer_contract.py::test_edit_action_rejects_oversized_text_and_instruction PASSED [ 47%]
+tests/api/routers/test_co_writer_contract.py::test_react_edit_rejects_invalid_mode_tools_and_oversized_selection PASSED [ 50%]
+tests/api/routers/test_co_writer_contract.py::test_react_edit_requires_instruction_when_mode_is_none PASSED [ 52%]
+tests/api/routers/test_co_writer_contract.py::test_react_edit_requires_a_non_blank_selection PASSED [ 55%]
+tests/api/routers/test_co_writer_contract.py::test_react_edit_stream_rejects_bad_payloads_before_streaming PASSED [ 57%]
+tests/api/routers/test_co_writer_contract.py::test_export_docx_rejects_oversized_content PASSED [ 60%]
+tests/api/routers/test_co_writer_contract.py::test_import_docx_rejects_missing_unsupported_and_empty_files PASSED [ 62%]
+tests/api/routers/test_co_writer_contract.py::test_export_docx_returns_400_when_converter_reports_bad_input PASSED [ 65%]
+tests/api/routers/test_co_writer_contract.py::test_export_docx_returns_500_on_unexpected_converter_error PASSED [ 67%]
+tests/api/routers/test_co_writer_contract.py::test_export_docx_sanitizes_unsafe_title_in_content_disposition PASSED [ 70%]
+tests/api/routers/test_co_writer_contract.py::test_import_docx_returns_400_for_corrupt_upload PASSED [ 72%]
+tests/api/routers/test_co_writer_contract.py::test_import_docx_returns_500_on_unexpected_conversion_error PASSED [ 75%]
+tests/api/routers/test_co_writer_contract.py::test_edit_action_forwards_request_fields_to_agent PASSED [ 77%]
+tests/api/routers/test_co_writer_contract.py::test_edit_action_maps_agent_exception_to_500 PASSED [ 80%]
+tests/api/routers/test_co_writer_contract.py::test_automark_forwards_text_and_returns_payload PASSED [ 82%]
+tests/api/routers/test_co_writer_contract.py::test_automark_maps_agent_exception_to_500 PASSED [ 85%]
+tests/api/routers/test_co_writer_contract.py::test_react_edit_strips_output_fence_and_reports_tools_used PASSED [ 87%]
+tests/api/routers/test_co_writer_contract.py::test_react_edit_skips_rag_tool_without_kb_name_and_deduplicates PASSED [ 90%]
+tests/api/routers/test_co_writer_contract.py::test_react_edit_forwards_kb_name_to_rag_gather PASSED [ 92%]
+tests/api/routers/test_co_writer_contract.py::test_react_edit_records_history_entry PASSED [ 95%]
+tests/api/routers/test_co_writer_contract.py::test_history_endpoints_return_recorded_operations PASSED [ 97%]
+tests/api/routers/test_co_writer_contract.py::test_tool_call_endpoint_serves_recorded_payload PASSED [100%]
+
+============================== 40 passed in 0.51s ==============================
diff --git a/tests/api/routers/test_co_writer_contract.py b/tests/api/routers/test_co_writer_contract.py
new file mode 100644
index 000000000..3261de32d
--- /dev/null
+++ b/tests/api/routers/test_co_writer_contract.py
@@ -0,0 +1,617 @@
+"""Contract tests for the Co-Writer router (`deeptutor/api/routers/co_writer.py`).
+
+Locks the HTTP contract of the collaborative-writing surface: document CRUD
+request/response shapes, illegal-payload 4xx handling, and the export/import
+failure branches. Storage and the edit agent are stubbed, so nothing here
+touches the real workspace or any LLM.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+import re
+
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+import pytest
+
+import deeptutor.services.config as _dt_config
+
+_dt_config.load_config_with_main = lambda *_a, **_k: {
+ "paths": {},
+ "logging": {},
+ "system": {"language": "en"},
+}
+
+from deeptutor.api.routers import co_writer as co_writer_router
+from deeptutor.co_writer import edit_agent
+from deeptutor.co_writer.docx_converter import DocxConversionError
+from deeptutor.co_writer.storage import CoWriterStorage
+
+MAX_DOC_CHARS = co_writer_router._MAX_DOC_CHARS
+MAX_SELECTION_CHARS = co_writer_router._MAX_SELECTION_CHARS
+MAX_INSTRUCTION_CHARS = co_writer_router._MAX_INSTRUCTION_CHARS
+
+_DOC_ID_RE = re.compile(r"^[0-9a-f]{8,32}$")
+
+
+class _StubPathService:
+ def __init__(self, root: Path):
+ self.root = root
+
+ def get_co_writer_dir(self) -> Path:
+ return self.root
+
+ def get_co_writer_history_file(self) -> Path:
+ return self.root / "history.json"
+
+ def get_co_writer_tool_calls_dir(self) -> Path:
+ return self.root / "tool_calls"
+
+ def get_co_writer_docs_dir(self) -> Path:
+ return self.root / "documents"
+
+ def get_co_writer_doc_root(self, doc_id: str) -> Path:
+ return self.get_co_writer_docs_dir() / f"doc_{doc_id}"
+
+ def get_co_writer_doc_manifest(self, doc_id: str) -> Path:
+ return self.get_co_writer_doc_root(doc_id) / "manifest.json"
+
+
+class _StubEditAgent:
+ """Deterministic stand-in for EditAgent; records every call it receives."""
+
+ def __init__(self):
+ self.calls: list[tuple] = []
+ self.language = "en"
+ self.binding = None
+ self.fail_process_with: Exception | None = None
+ self.fail_auto_mark_with: Exception | None = None
+ self.stream_chunks = ["```markdown\n", "Edited body\n", "```"]
+
+ def refresh_config(self) -> None:
+ self.calls.append(("refresh_config",))
+
+ def get_model(self) -> str:
+ return "stub-model"
+
+ async def process(self, **kwargs):
+ self.calls.append(("process", kwargs))
+ if self.fail_process_with is not None:
+ raise self.fail_process_with
+ return {
+ "edited_text": f"edited::{kwargs['text']}",
+ "operation_id": "op-edit-0001",
+ }
+
+ async def auto_mark(self, *, text):
+ self.calls.append(("auto_mark", text))
+ if self.fail_auto_mark_with is not None:
+ raise self.fail_auto_mark_with
+ return {"marked_text": f"marked::{text}", "operation_id": "op-mark-0001"}
+
+ async def gather_context(self, *, source, query, kb_name, operation_id):
+ self.calls.append(("gather_context", source, kb_name, query))
+ return (f"{source}-context", None)
+
+ async def stream_llm(self, *, user_prompt, system_prompt, stage):
+ self.calls.append(("stream_llm", stage, user_prompt, system_prompt))
+ for chunk in self.stream_chunks:
+ yield chunk
+
+
+def storage(tmp_path):
+ return CoWriterStorage(path_service=_StubPathService(tmp_path))
+
+
+def agent(monkeypatch, tmp_path):
+ stub = _StubEditAgent()
+ monkeypatch.setattr(co_writer_router, "get_edit_agent", lambda: stub)
+ monkeypatch.setattr(
+ edit_agent, "get_path_service", lambda: _StubPathService(tmp_path / "agent")
+ )
+ return stub
+
+
+def client(monkeypatch, storage):
+ monkeypatch.setattr(co_writer_router, "get_co_writer_storage", lambda: storage)
+ app = FastAPI()
+ app.include_router(co_writer_router.router)
+ with TestClient(app) as test_client:
+ yield test_client
+
+
+# ── Document CRUD: request/response shapes ───────────────────────────────
+
+
+def test_create_document_returns_full_document_shape(client, storage):
+ response = client.post("/documents", json={"title": "My Draft", "content": "# Hi\nBody"})
+ assert response.status_code == 200, response.text
+ payload = response.json()
+ assert set(payload) == {"id", "title", "content", "created_at", "updated_at"}
+ assert _DOC_ID_RE.fullmatch(payload["id"])
+ assert payload["title"] == "My Draft"
+ assert payload["content"] == "# Hi\nBody"
+ assert isinstance(payload["created_at"], float)
+ assert isinstance(payload["updated_at"], float)
+ stored = storage.load_document(payload["id"])
+ assert stored is not None and stored.title == "My Draft"
+
+
+def test_create_document_without_title_derives_it_from_first_heading(client):
+ payload = client.post("/documents", json={"content": "# Derived Title\nbody text"}).json()
+ assert payload["title"] == "Derived Title"
+
+
+def test_create_document_with_empty_body_uses_defaults(client):
+ response = client.post("/documents", json={})
+ assert response.status_code == 200, response.text
+ payload = response.json()
+ assert payload["title"] == "Untitled draft"
+ assert payload["content"] == ""
+
+
+def test_create_document_rejects_non_string_fields(client):
+ assert client.post("/documents", json={"title": 123}).status_code == 422
+ assert client.post("/documents", json={"content": ["not", "a", "string"]}).status_code == 422
+
+
+def test_list_documents_returns_summary_views_without_content(client, storage):
+ first = storage.create_document(title="first", content="alpha body")
+ second = storage.create_document(title="second", content="beta body")
+ storage.update_document(first.id, content="alpha body v2")
+
+ response = client.get("/documents")
+ assert response.status_code == 200, response.text
+ payload = response.json()
+ assert set(payload) == {"documents"}
+ summaries = payload["documents"]
+ assert {s["id"] for s in summaries} == {first.id, second.id}
+ assert summaries[0]["id"] == first.id, "most recently updated document must sort first"
+ for summary in summaries:
+ assert set(summary) == {"id", "title", "created_at", "updated_at", "preview"}
+ assert "content" not in summary
+
+
+def test_list_documents_truncates_preview_at_160_chars(client, storage):
+ storage.create_document(title="long", content="x" * 300)
+ summary = client.get("/documents").json()["documents"][0]
+ assert summary["preview"].endswith("…")
+ assert len(summary["preview"]) <= 161
+
+
+def test_get_document_returns_persisted_content(client, storage):
+ created = storage.create_document(title="Get me", content="# Get\nbody")
+ response = client.get(f"/documents/{created.id}")
+ assert response.status_code == 200, response.text
+ payload = response.json()
+ assert payload["id"] == created.id
+ assert payload["title"] == "Get me"
+ assert payload["content"] == "# Get\nbody"
+
+
+def test_update_document_applies_title_and_content(client, storage):
+ created = storage.create_document(title="Before", content="old body")
+ response = client.put(
+ f"/documents/{created.id}", json={"title": "After", "content": "new body"}
+ )
+ assert response.status_code == 200, response.text
+ payload = response.json()
+ assert payload["title"] == "After"
+ assert payload["content"] == "new body"
+ assert storage.load_document(created.id).content == "new body"
+
+
+def test_update_document_with_empty_object_keeps_fields(client, storage):
+ created = storage.create_document(title="Stable", content="keep me")
+ before = storage.load_document(created.id)
+ response = client.put(f"/documents/{created.id}", json={})
+ assert response.status_code == 200, response.text
+ payload = response.json()
+ assert payload["title"] == "Stable"
+ assert payload["content"] == "keep me"
+ after = storage.load_document(created.id)
+ assert after.updated_at >= before.updated_at
+
+
+def test_update_document_rejects_non_string_title(client, storage):
+ created = storage.create_document(title="Typed", content="body")
+ response = client.put(f"/documents/{created.id}", json={"title": [1]})
+ assert response.status_code == 422
+
+
+def test_delete_document_returns_deleted_true_then_404(client, storage):
+ created = storage.create_document(title="Doomed", content="body")
+ response = client.delete(f"/documents/{created.id}")
+ assert response.status_code == 200, response.text
+ assert response.json() == {"deleted": True}
+ assert storage.load_document(created.id) is None
+ assert client.delete(f"/documents/{created.id}").status_code == 404
+
+
+# ── Unknown / malformed doc ids → 404 on every route ─────────────────────
+
+
+ "bad_id",
+ [
+ "ffffffffffff", # well-formed shape, no such document
+ "A1B2C3D4E5F6", # uppercase is not a generated id
+ "g1b2c3d4e5f6", # non-hex
+ "abc123", # too short
+ "a" * 40, # too long
+ ],
+)
+def test_unknown_or_malformed_doc_ids_return_404_on_crud_routes(client, bad_id):
+ assert client.get(f"/documents/{bad_id}").status_code == 404
+ assert client.put(f"/documents/{bad_id}", json={"title": "x"}).status_code == 404
+ assert client.delete(f"/documents/{bad_id}").status_code == 404
+
+
+def test_not_found_details_name_the_document(client):
+ missing = "ffffffffffff"
+ assert client.get(f"/documents/{missing}").json()["detail"] == "Document not found"
+ assert client.delete(f"/documents/{missing}").json()["detail"] == "Document not found"
+
+
+# ── Illegal payloads → 4xx before any agent work ─────────────────────────
+
+
+def test_edit_action_rejects_missing_fields_and_bad_literals(client, agent):
+ assert client.post("/documents/actions/edit", json={}).status_code == 422
+ assert (
+ client.post("/documents/actions/edit", json={"text": "abc"}).status_code == 422
+ ) # instruction required
+ assert (
+ client.post(
+ "/documents/actions/edit",
+ json={"text": "abc", "instruction": "do", "action": "delete"},
+ ).status_code
+ == 422
+ )
+ assert (
+ client.post(
+ "/documents/actions/edit",
+ json={"text": "abc", "instruction": "do", "source": "books"},
+ ).status_code
+ == 422
+ )
+ assert agent.calls == [], "validation failures must never reach the agent"
+
+
+def test_edit_action_rejects_oversized_text_and_instruction(client, agent):
+ response = client.post(
+ "/documents/actions/edit",
+ json={"text": "x" * (MAX_DOC_CHARS + 1), "instruction": "do"},
+ )
+ assert response.status_code == 422
+ response = client.post(
+ "/documents/actions/edit",
+ json={"text": "abc", "instruction": "y" * (MAX_INSTRUCTION_CHARS + 1)},
+ )
+ assert response.status_code == 422
+ assert agent.calls == []
+
+
+def test_react_edit_rejects_invalid_mode_tools_and_oversized_selection(client, agent):
+ base = {"selected_text": "abc"}
+ assert (
+ client.post("/documents/actions/edit-react", json={**base, "mode": "summarize"}).status_code
+ == 422
+ )
+ assert (
+ client.post("/documents/actions/edit-react", json={**base, "tools": ["evil"]}).status_code
+ == 422
+ )
+ assert (
+ client.post(
+ "/documents/actions/edit-react",
+ json={"selected_text": "s" * (MAX_SELECTION_CHARS + 1), "instruction": "do"},
+ ).status_code
+ == 422
+ )
+ assert (
+ client.post(
+ "/documents/actions/edit-react",
+ json={"selected_text": "abc", "instruction": "z" * (MAX_INSTRUCTION_CHARS + 1)},
+ ).status_code
+ == 422
+ )
+ assert agent.calls == []
+
+
+def test_react_edit_requires_instruction_when_mode_is_none(client, agent):
+ response = client.post(
+ "/documents/actions/edit-react",
+ json={"selected_text": "abc", "mode": "none", "instruction": " "},
+ )
+ assert response.status_code == 400
+ detail = response.json()["detail"]
+ assert isinstance(detail, str) and detail
+ assert agent.calls == []
+
+
+def test_react_edit_requires_a_non_blank_selection(client, agent):
+ response = client.post(
+ "/documents/actions/edit-react",
+ json={"selected_text": "\n\n \n", "instruction": "polish"},
+ )
+ assert response.status_code == 400
+ detail = response.json()["detail"]
+ assert isinstance(detail, str) and detail
+ assert agent.calls == []
+
+
+def test_react_edit_stream_rejects_bad_payloads_before_streaming(client, agent):
+ response = client.post(
+ "/documents/actions/edit-react/stream",
+ json={"selected_text": "abc", "mode": "none", "instruction": ""},
+ )
+ assert response.status_code == 400
+ assert response.headers["content-type"].startswith("application/json")
+ assert not response.text.startswith("event:")
+ response = client.post(
+ "/documents/actions/edit-react/stream",
+ json={"selected_text": "abc", "mode": "bogus"},
+ )
+ assert response.status_code == 422
+ assert agent.calls == []
+
+
+def test_export_docx_rejects_oversized_content(client):
+ response = client.post(
+ "/documents/export/docx",
+ json={"title": "big", "content": "x" * (MAX_DOC_CHARS + 1)},
+ )
+ assert response.status_code == 422
+
+
+def test_import_docx_rejects_missing_unsupported_and_empty_files(client, storage):
+ doc = client.post(
+ "/documents/import/docx",
+ files={"file": ("legacy.doc", b"OLE2", "application/msword")},
+ )
+ assert doc.status_code == 400
+ assert "docx" in doc.json()["detail"].lower()
+
+ txt = client.post(
+ "/documents/import/docx",
+ files={"file": ("notes.txt", b"hello", "text/plain")},
+ )
+ assert txt.status_code == 400
+
+ empty = client.post(
+ "/documents/import/docx",
+ files={
+ "file": (
+ "empty.docx",
+ b"",
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
+ )
+ },
+ )
+ assert empty.status_code == 400
+ assert "empty" in empty.json()["detail"].lower()
+ assert storage.list_documents() == []
+
+
+# ── Export / import failure branches ─────────────────────────────────────
+
+
+def test_export_docx_returns_400_when_converter_reports_bad_input(client, monkeypatch):
+ def _raise(content, title):
+ raise DocxConversionError("simulated converter rejection")
+
+ monkeypatch.setattr(co_writer_router, "markdown_to_docx", _raise)
+ response = client.post("/documents/export/docx", json={"title": "T", "content": "# hi"})
+ assert response.status_code == 400
+ assert "simulated converter rejection" in response.json()["detail"]
+
+
+def test_export_docx_returns_500_on_unexpected_converter_error(client, monkeypatch):
+ def _raise(content, title):
+ raise RuntimeError("converter exploded")
+
+ monkeypatch.setattr(co_writer_router, "markdown_to_docx", _raise)
+ response = client.post("/documents/export/docx", json={"title": "T", "content": "# hi"})
+ assert response.status_code == 500
+ assert "converter exploded" in response.json()["detail"]
+
+
+def test_export_docx_sanitizes_unsafe_title_in_content_disposition(client):
+ response = client.post(
+ "/documents/export/docx",
+ json={"title": 'a"b/c:d*e?f<g>h|i', "content": "# hi"},
+ )
+ assert response.status_code == 200, response.text
+ disposition = response.headers["content-disposition"]
+ assert 'filename="a-b-c-d-e-f-g-h-i.docx"' in disposition
+
+
+def test_import_docx_returns_400_for_corrupt_upload(client, storage):
+ response = client.post(
+ "/documents/import/docx",
+ files={"file": ("broken.docx", b"not-a-real-docx", "application/octet-stream")},
+ )
+ assert response.status_code == 400
+ assert storage.list_documents() == []
+
+
+def test_import_docx_returns_500_on_unexpected_conversion_error(client, monkeypatch):
+ def _raise(data, filename):
+ raise RuntimeError("parser exploded")
+
+ monkeypatch.setattr(co_writer_router, "docx_to_markdown", _raise)
+ response = client.post(
+ "/documents/import/docx",
+ files={"file": ("ok.docx", b"PK\x03\x04payload", "application/octet-stream")},
+ )
+ assert response.status_code == 500
+ assert "parser exploded" in response.json()["detail"]
+
+
+# ── Edit actions: agent request/response contracts ───────────────────────
+
+
+def test_edit_action_forwards_request_fields_to_agent(client, agent):
+ response = client.post(
+ "/documents/actions/edit",
+ json={
+ "text": "draft text",
+ "instruction": "make it shorter",
+ "action": "shorten",
+ "source": None,
+ "kb_name": None,
+ },
+ )
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "edited_text": "edited::draft text",
+ "operation_id": "op-edit-0001",
+ }
+ assert agent.calls[0] == (
+ "process",
+ {
+ "text": "draft text",
+ "instruction": "make it shorter",
+ "action": "shorten",
+ "source": None,
+ "kb_name": None,
+ },
+ )
+
+
+def test_edit_action_maps_agent_exception_to_500(client, agent):
+ agent.fail_process_with = ValueError("boom")
+ response = client.post("/documents/actions/edit", json={"text": "abc", "instruction": "do"})
+ assert response.status_code == 500
+ assert "boom" in response.json()["detail"]
+
+
+def test_automark_forwards_text_and_returns_payload(client, agent):
+ response = client.post("/documents/actions/automark", json={"text": "mark me"})
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "marked_text": "marked::mark me",
+ "operation_id": "op-mark-0001",
+ }
+ assert agent.calls[0] == ("auto_mark", "mark me")
+
+
+def test_automark_maps_agent_exception_to_500(client, agent):
+ agent.fail_auto_mark_with = RuntimeError("nope")
+ response = client.post("/documents/actions/automark", json={"text": "mark me"})
+ assert response.status_code == 500
+ assert "nope" in response.json()["detail"]
+
+
+def test_react_edit_strips_output_fence_and_reports_tools_used(client, agent):
+ response = client.post(
+ "/documents/actions/edit-react",
+ json={"selected_text": "source text", "instruction": "shorten", "tools": ["web"]},
+ )
+ assert response.status_code == 200, response.text
+ payload = response.json()
+ assert set(payload) == {"edited_text", "operation_id", "tools_used"}
+ assert payload["edited_text"] == "Edited body"
+ assert payload["tools_used"] == ["web"]
+ assert _DOC_ID_RE_OR_TIMESTAMP(payload["operation_id"])
+ gathered = [call for call in agent.calls if call[0] == "gather_context"]
+ assert gathered == [("gather_context", "web", None, "shorten")]
+
+
+def test_react_edit_skips_rag_tool_without_kb_name_and_deduplicates(client, agent):
+ response = client.post(
+ "/documents/actions/edit-react",
+ json={
+ "selected_text": "abc",
+ "instruction": "do",
+ "mode": "rewrite",
+ "tools": ["rag", "web", "rag", "web"],
+ },
+ )
+ assert response.status_code == 200, response.text
+ gathered = [call for call in agent.calls if call[0] == "gather_context"]
+ assert [call[1] for call in gathered] == ["web"], (
+ "rag without kb_name must be skipped; duplicate tools must be deduplicated"
+ )
+
+
+def test_react_edit_forwards_kb_name_to_rag_gather(client, agent, monkeypatch):
+ import deeptutor.services.rag.pipelines.pageindex as pageindex
+
+ monkeypatch.setattr(pageindex, "is_pageindex_kb", lambda kb_name: False)
+ response = client.post(
+ "/documents/actions/edit-react",
+ json={
+ "selected_text": "abc",
+ "instruction": "cite",
+ "tools": ["rag"],
+ "kb_name": "my-kb",
+ },
+ )
+ assert response.status_code == 200, response.text
+ gathered = [call for call in agent.calls if call[0] == "gather_context"]
+ assert gathered == [("gather_context", "rag", "my-kb", "cite")]
+ assert response.json()["tools_used"] == ["rag"]
+
+
+def test_react_edit_records_history_entry(client, agent, tmp_path):
+ response = client.post(
+ "/documents/actions/edit-react",
+ json={"selected_text": "abc", "instruction": "do", "mode": "expand"},
+ )
+ assert response.status_code == 200, response.text
+ operation_id = response.json()["operation_id"]
+ history = edit_agent.load_history()
+ entry = next(item for item in history if item.get("id") == operation_id)
+ assert entry["action"] == "react_edit"
+ assert entry["mode"] == "expand"
+ assert entry["output"]["edited_text"] == "Edited body"
+
+
+# ── History and tool-call endpoints ──────────────────────────────────────
+
+
+def test_history_endpoints_return_recorded_operations(client, agent):
+ edit_agent.append_history({"id": "op-1", "action": "react_edit"})
+ edit_agent.append_history({"id": "op-2", "action": "react_edit"})
+
+ listing = client.get("/documents/history")
+ assert listing.status_code == 200, listing.text
+ payload = listing.json()
+ assert set(payload) == {"history", "total"}
+ assert payload["total"] == 2
+ assert [item["id"] for item in payload["history"]] == ["op-1", "op-2"]
+
+ single = client.get("/documents/history/op-2")
+ assert single.status_code == 200, single.text
+ assert single.json()["id"] == "op-2"
+
+ missing = client.get("/documents/history/op-404")
+ assert missing.status_code == 404
+ assert missing.json()["detail"] == "Operation not found"
+
+
+def test_tool_call_endpoint_serves_recorded_payload(client, agent, tmp_path):
+ tool_calls_dir = edit_agent.tool_calls_dir()
+ tool_calls_dir.mkdir(parents=True, exist_ok=True)
+ (tool_calls_dir / "op-9_details.json").write_text(
+ '{"id": "op-9", "tool": "web"}', encoding="utf-8"
+ )
+
+ found = client.get("/documents/tool-calls/op-9")
+ assert found.status_code == 200, found.text
+ assert found.json() == {"id": "op-9", "tool": "web"}
+
+ missing = client.get("/documents/tool-calls/op-404")
+ assert missing.status_code == 404
+ assert missing.json()["detail"] == "Tool call not found"
+
+
+def _DOC_ID_RE_OR_TIMESTAMP(operation_id: str) -> bool:
+ # operation ids are `<YYYYmmdd_HHMMSS>_<6 hex chars>`
+ return bool(re.fullmatch(r"\d{8}_\d{6}_[0-9a-f]{6}", operation_id))