DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(co-writer): add multi-doc co-writer workspace with backend storage
Bingxi Zhao (Frank)593ddba3fb94
diff --git a/deeptutor/agents/notebook/prompts/en/summarize_agent.yaml b/deeptutor/agents/notebook/prompts/en/summarize_agent.yamlindex 0c3406b43..157dee1aa 100644--- a/deeptutor/agents/notebook/prompts/en/summarize_agent.yaml+++ b/deeptutor/agents/notebook/prompts/en/summarize_agent.yaml@@ -22,6 +22,5 @@ user_template: |# Per-record-type hints injected into `user_template` as `{record_hint}`.record_hints:chat: "A full chat transcript; focus on the question, conclusion, and next actions."- co_writer: "A writing draft; focus on theme, structure, current completeness, and expansion paths."guided_learning: "A guided learning record; focus on topic, knowledge structure, and partial/final output."default: "Summarize the most reusable information in this record."diff --git a/deeptutor/agents/notebook/prompts/zh/summarize_agent.yaml b/deeptutor/agents/notebook/prompts/zh/summarize_agent.yamlindex 42bc95040..976d6b6b8 100644--- a/deeptutor/agents/notebook/prompts/zh/summarize_agent.yaml+++ b/deeptutor/agents/notebook/prompts/zh/summarize_agent.yaml@@ -23,6 +23,5 @@ user_template: |# 各记录类型的提示语,会被注入到 user_template 的 {record_hint}。record_hints:chat: "一段完整聊天历史,重点提炼问题、结论与后续行动。"- co_writer: "一份写作草稿,重点提炼主题、结构、当前完成度与可继续扩展方向。"guided_learning: "一段引导式学习记录,重点提炼学习主题、知识点结构与阶段性产出。"default: "请总结此记录中最值得复用的信息。"diff --git a/deeptutor/api/routers/co_writer.py b/deeptutor/api/routers/co_writer.pyindex e2d47a74c..15fe41862 100644--- a/deeptutor/api/routers/co_writer.py+++ b/deeptutor/api/routers/co_writer.py@@ -19,6 +19,11 @@ from deeptutor.co_writer.edit_agent import (save_history,save_tool_call,)+from deeptutor.co_writer.storage import (+ CoWriterDocument,+ CoWriterDocumentSummary,+ get_co_writer_storage,+)from deeptutor.agents.chat.agentic_pipeline import AgenticChatPipelinefrom deeptutor.core.context import UnifiedContextfrom deeptutor.core.stream_bus import StreamBus@@ -503,3 +508,128 @@ async def export_markdown(content: dict):except Exception as e:raise HTTPException(status_code=500, detail=str(e))++# ─────────────────────────────────────────────────────────────────────────────+# Document CRUD (multi-project Co-Writer)+# ─────────────────────────────────────────────────────────────────────────────+++class CreateDocumentRequest(BaseModel):+ title: str | None = None+ content: str = ""+++class UpdateDocumentRequest(BaseModel):+ title: str | None = None+ content: str | None = None+++class DocumentResponse(BaseModel):+ id: str+ title: str+ content: str+ created_at: float+ updated_at: float++ @classmethod+ def from_model(cls, doc: CoWriterDocument) -> "DocumentResponse":+ return cls(+ id=doc.id,+ title=doc.title,+ content=doc.content,+ created_at=doc.created_at,+ updated_at=doc.updated_at,+ )+++class DocumentSummaryResponse(BaseModel):+ id: str+ title: str+ created_at: float+ updated_at: float+ preview: str = ""++ @classmethod+ def from_summary(cls, summary: CoWriterDocumentSummary) -> "DocumentSummaryResponse":+ return cls(+ id=summary.id,+ title=summary.title,+ created_at=summary.created_at,+ updated_at=summary.updated_at,+ preview=summary.preview,+ )++[email protected]("/documents")+async def list_documents() -> dict[str, list[DocumentSummaryResponse]]:+ """List all Co-Writer documents (summary view, sorted by recency)."""+ try:+ storage = get_co_writer_storage()+ summaries = storage.list_documents()+ return {"documents": [DocumentSummaryResponse.from_summary(s) for s in summaries]}+ except Exception as e:+ traceback.print_exc()+ raise HTTPException(status_code=500, detail=str(e))++[email protected]("/documents", response_model=DocumentResponse)+async def create_document(request: CreateDocumentRequest) -> DocumentResponse:+ """Create a new Co-Writer document."""+ try:+ storage = get_co_writer_storage()+ document = storage.create_document(title=request.title, content=request.content)+ return DocumentResponse.from_model(document)+ except Exception as e:+ traceback.print_exc()+ raise HTTPException(status_code=500, detail=str(e))++[email protected]("/documents/{doc_id}", response_model=DocumentResponse)+async def get_document(doc_id: str) -> DocumentResponse:+ """Get a single Co-Writer document by id."""+ try:+ storage = get_co_writer_storage()+ document = storage.load_document(doc_id)+ if document is None:+ raise HTTPException(status_code=404, detail="Document not found")+ return DocumentResponse.from_model(document)+ except HTTPException:+ raise+ except Exception as e:+ traceback.print_exc()+ raise HTTPException(status_code=500, detail=str(e))++[email protected]("/documents/{doc_id}", response_model=DocumentResponse)+async def update_document(doc_id: str, request: UpdateDocumentRequest) -> DocumentResponse:+ """Update a Co-Writer document (title and/or content)."""+ try:+ storage = get_co_writer_storage()+ document = storage.update_document(+ doc_id, title=request.title, content=request.content+ )+ if document is None:+ raise HTTPException(status_code=404, detail="Document not found")+ return DocumentResponse.from_model(document)+ except HTTPException:+ raise+ except Exception as e:+ traceback.print_exc()+ raise HTTPException(status_code=500, detail=str(e))++[email protected]("/documents/{doc_id}")+async def delete_document(doc_id: str) -> dict[str, bool]:+ """Delete a Co-Writer document."""+ try:+ storage = get_co_writer_storage()+ if not storage.doc_exists(doc_id):+ raise HTTPException(status_code=404, detail="Document not found")+ success = storage.delete_document(doc_id)+ return {"deleted": success}+ except HTTPException:+ raise+ except Exception as e:+ traceback.print_exc()+ raise HTTPException(status_code=500, detail=str(e))+diff --git a/deeptutor/api/routers/notebook.py b/deeptutor/api/routers/notebook.pyindex b0ae77a15..751aab369 100644--- a/deeptutor/api/routers/notebook.py+++ b/deeptutor/api/routers/notebook.py@@ -41,7 +41,7 @@ class AddRecordRequest(BaseModel):"""Add record request"""notebook_ids: list[str]- record_type: Literal["solve", "question", "research", "co_writer", "chat"]+ record_type: Literal["solve", "question", "research", "chat"]title: strsummary: str = ""user_query: strdiff --git a/deeptutor/app/facade.py b/deeptutor/app/facade.pyindex 984e38bd3..b5539ad20 100644--- a/deeptutor/app/facade.py+++ b/deeptutor/app/facade.py@@ -3,15 +3,12 @@from __future__ import annotationsfrom dataclasses import dataclass, field-from hashlib import sha256import importlib.utilimport json-from pathlib import Path-import timefrom typing import Any, AsyncIteratorfrom deeptutor.runtime.registry.capability_registry import get_capability_registry-from deeptutor.services.notebook import RecordType, get_notebook_manager+from deeptutor.services.notebook import get_notebook_managerfrom deeptutor.services.session import get_sqlite_session_store, get_turn_runtime_manager@@ -187,78 +184,6 @@ class DeepTutorApp:def get_records_by_references(self, notebook_references: list[dict[str, Any]]) -> list[dict[str, Any]]:return self.notebooks.get_records_by_references(notebook_references)- def import_markdown_into_notebook(self, notebook_id: str, path: str | Path) -> dict[str, Any]:- resolved_path = Path(path).expanduser().resolve()- if not resolved_path.exists():- raise FileNotFoundError(f"Markdown file not found: {resolved_path}")- content = resolved_path.read_text(encoding="utf-8")- title = _extract_markdown_title(content, fallback=resolved_path.stem)- now = time.time()- metadata = {- "source": "co_writer",- "saved_via": "cli",- "source_path": str(resolved_path),- "source_hash": sha256(content.encode("utf-8")).hexdigest(),- "imported_at": now,- }- return self.notebooks.add_record(- notebook_ids=[notebook_id],- record_type=RecordType.CO_WRITER,- title=title,- summary="",- user_query=title,- output=content,- metadata=metadata,- kb_name=None,- )-- def replace_markdown_record(- self,- notebook_id: str,- record_id: str,- path: str | Path,- ) -> dict[str, Any]:- resolved_path = Path(path).expanduser().resolve()- if not resolved_path.exists():- raise FileNotFoundError(f"Markdown file not found: {resolved_path}")- existing = self.notebooks.get_record(notebook_id, record_id)- if existing is None:- raise ValueError(f"Record not found: {record_id}")- if str(existing.get("type", "")) != RecordType.CO_WRITER.value:- raise ValueError("Only `co_writer` notebook records can be replaced from markdown.")-- content = resolved_path.read_text(encoding="utf-8")- title = _extract_markdown_title(content, fallback=resolved_path.stem)- metadata = {- "source": "co_writer",- "saved_via": "cli",- "source_path": str(resolved_path),- "source_hash": sha256(content.encode("utf-8")).hexdigest(),- "replaced_at": time.time(),- }- updated = self.notebooks.update_record(- notebook_id,- record_id,- title=title,- user_query=title,- output=content,- metadata=metadata,- kb_name=None,- )- if updated is None:- raise ValueError(f"Failed to update record: {record_id}")- return updated---def _extract_markdown_title(content: str, *, fallback: str) -> str:- for line in content.splitlines():- stripped = line.strip()- if stripped.startswith("#"):- title = stripped.lstrip("#").strip()- if title:- return title- return fallback.strip() or "Untitled"-def dumps_json(value: Any) -> str:return json.dumps(value, ensure_ascii=False, indent=2, default=str)diff --git a/deeptutor/co_writer/storage.py b/deeptutor/co_writer/storage.pynew file mode 100644index 000000000..4d87a3a63--- /dev/null+++ b/deeptutor/co_writer/storage.py@@ -0,0 +1,260 @@+"""+Co-Writer Document Storage+==========================++Per-document directory + manifest persistence with atomic writes.++Layout (relative to ``data/user/workspace/co-writer/``)::++ documents/+ ├── doc_{doc_id}/+ │ └── manifest.json # { id, title, content, created_at, updated_at }+ └── doc_{doc_id2}/+ └── manifest.json+"""++from __future__ import annotations++import json+import os+import shutil+import time+import uuid+from pathlib import Path+from typing import Any++from pydantic import BaseModel, Field++from deeptutor.logging import get_logger+from deeptutor.services.path_service import get_path_service++logger = get_logger("co_writer.storage")+++class CoWriterDocument(BaseModel):+ """Lightweight document model for Co-Writer projects."""++ id: str+ title: str = ""+ content: str = ""+ created_at: float = Field(default_factory=lambda: time.time())+ updated_at: float = Field(default_factory=lambda: time.time())+++class CoWriterDocumentSummary(BaseModel):+ """Summary view (without full content) used for list endpoints."""++ id: str+ title: str+ created_at: float+ updated_at: float+ preview: str = ""+++def _atomic_write_text(path: Path, text: str) -> None:+ """Write *text* to *path* atomically (write-temp + rename)."""+ path.parent.mkdir(parents=True, exist_ok=True)+ tmp = path.with_suffix(path.suffix + ".tmp")+ with open(tmp, "w", encoding="utf-8") as f:+ f.write(text)+ f.flush()+ try:+ os.fsync(f.fileno())+ except OSError:+ pass+ os.replace(tmp, path)+++def _atomic_write_json(path: Path, payload: Any) -> None:+ text = json.dumps(payload, ensure_ascii=False, indent=2, default=str)+ _atomic_write_text(path, text)+++def _read_json(path: Path) -> Any | None:+ if not path.exists():+ return None+ try:+ with open(path, encoding="utf-8") as f:+ return json.load(f)+ except (OSError, json.JSONDecodeError) as exc:+ logger.warning(f"Failed to read JSON {path}: {exc}")+ return None+++def _derive_title(content: str, fallback: str = "Untitled draft") -> str:+ """Pick a title from the first heading line; fallback otherwise."""+ if not content:+ return fallback+ for raw in content.splitlines():+ line = raw.strip()+ if not line:+ continue+ if line.startswith("#"):+ stripped = line.lstrip("#").strip()+ if stripped:+ return stripped[:120]+ return line[:120]+ return fallback+++def _build_preview(content: str, limit: int = 160) -> str:+ if not content:+ return ""+ cleaned = "\n".join(+ line.strip() for line in content.splitlines() if line.strip()+ )+ cleaned = cleaned.replace("\n", " ")+ if len(cleaned) <= limit:+ return cleaned+ return cleaned[:limit].rstrip() + "…"+++class CoWriterStorage:+ """File-system backed store for Co-Writer documents."""++ def __init__(self) -> None:+ self.path_service = get_path_service()++ # ── Path helpers ─────────────────────────────────────────────────────++ def docs_root(self) -> Path:+ return self.path_service.get_co_writer_docs_dir()++ def doc_root(self, doc_id: str) -> Path:+ return self.path_service.get_co_writer_doc_root(doc_id)++ def manifest_path(self, doc_id: str) -> Path:+ return self.path_service.get_co_writer_doc_manifest(doc_id)++ def ensure_root(self) -> Path:+ root = self.docs_root()+ root.mkdir(parents=True, exist_ok=True)+ return root++ def ensure_doc_root(self, doc_id: str) -> Path:+ root = self.doc_root(doc_id)+ root.mkdir(parents=True, exist_ok=True)+ return root++ def doc_exists(self, doc_id: str) -> bool:+ return self.manifest_path(doc_id).exists()++ # ── CRUD ─────────────────────────────────────────────────────────────++ def list_doc_ids(self) -> list[str]:+ root = self.docs_root()+ if not root.exists():+ return []+ ids: list[str] = []+ for child in root.iterdir():+ if child.is_dir() and child.name.startswith("doc_"):+ ids.append(child.name[len("doc_"):])+ return ids++ def list_documents(self) -> list[CoWriterDocumentSummary]:+ summaries: list[CoWriterDocumentSummary] = []+ for doc_id in self.list_doc_ids():+ doc = self.load_document(doc_id)+ if doc is None:+ continue+ summaries.append(+ CoWriterDocumentSummary(+ id=doc.id,+ title=doc.title or _derive_title(doc.content),+ created_at=doc.created_at,+ updated_at=doc.updated_at,+ preview=_build_preview(doc.content),+ )+ )+ summaries.sort(key=lambda s: s.updated_at, reverse=True)+ return summaries++ def create_document(+ self,+ *,+ title: str | None = None,+ content: str = "",+ ) -> CoWriterDocument:+ doc_id = uuid.uuid4().hex[:12]+ # Avoid extremely unlikely collisions.+ while self.doc_exists(doc_id):+ doc_id = uuid.uuid4().hex[:12]++ now = time.time()+ resolved_title = (title or "").strip() or _derive_title(content, "Untitled draft")+ document = CoWriterDocument(+ id=doc_id,+ title=resolved_title,+ content=content,+ created_at=now,+ updated_at=now,+ )+ self._write(document)+ return document++ def load_document(self, doc_id: str) -> CoWriterDocument | None:+ data = _read_json(self.manifest_path(doc_id))+ if data is None:+ return None+ try:+ return CoWriterDocument.model_validate(data)+ except Exception as exc:+ logger.warning(f"Failed to validate Co-Writer document {doc_id}: {exc}")+ return None++ def update_document(+ self,+ doc_id: str,+ *,+ title: str | None = None,+ content: str | None = None,+ ) -> CoWriterDocument | None:+ document = self.load_document(doc_id)+ if document is None:+ return None+ if title is not None:+ document.title = title.strip() or _derive_title(+ content if content is not None else document.content+ )+ if content is not None:+ document.content = content+ if title is None:+ # Keep title in sync with the first heading when the user+ # never set an explicit title (or kept the default).+ derived = _derive_title(content, document.title or "Untitled draft")+ if not document.title or document.title == "Untitled draft":+ document.title = derived+ document.updated_at = time.time()+ self._write(document)+ return document++ def delete_document(self, doc_id: str) -> bool:+ root = self.doc_root(doc_id)+ if not root.exists():+ return False+ shutil.rmtree(root, ignore_errors=True)+ return not root.exists()++ # ── Internal ─────────────────────────────────────────────────────────++ def _write(self, document: CoWriterDocument) -> None:+ self.ensure_doc_root(document.id)+ _atomic_write_json(self.manifest_path(document.id), document.model_dump(mode="json"))+++_storage: CoWriterStorage | None = None+++def get_co_writer_storage() -> CoWriterStorage:+ global _storage+ if _storage is None:+ _storage = CoWriterStorage()+ return _storage+++__all__ = [+ "CoWriterDocument",+ "CoWriterDocumentSummary",+ "CoWriterStorage",+ "get_co_writer_storage",+]diff --git a/deeptutor/services/notebook/service.py b/deeptutor/services/notebook/service.pyindex 9bd9eb330..f19320f33 100644--- a/deeptutor/services/notebook/service.py+++ b/deeptutor/services/notebook/service.py@@ -25,7 +25,6 @@ class RecordType(str, Enum):SOLVE = "solve"QUESTION = "question"RESEARCH = "research"- CO_WRITER = "co_writer"CHAT = "chat"@@ -377,7 +376,6 @@ class NotebookManager:"solve": 0,"question": 0,"research": 0,- "co_writer": 0,"chat": 0,}diff --git a/deeptutor/services/path_service.py b/deeptutor/services/path_service.pyindex 9e18fad45..e3f392157 100644--- a/deeptutor/services/path_service.py+++ b/deeptutor/services/path_service.py@@ -264,6 +264,17 @@ class PathService:def get_co_writer_audio_dir(self) -> Path:return self.get_co_writer_dir() / "audio"+ def get_co_writer_docs_dir(self) -> Path:+ """Root directory holding co-writer documents (one sub-directory per doc)."""+ return self.get_co_writer_dir() / "documents"++ def get_co_writer_doc_root(self, doc_id: str) -> Path:+ """Per-document root directory."""+ 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"+# ── Book Engine paths ────────────────────────────────────────────────def get_book_dir(self) -> Path:diff --git a/deeptutor/tools/builtin/__init__.py b/deeptutor/tools/builtin/__init__.pyindex d924db438..0bfd9f29b 100644--- a/deeptutor/tools/builtin/__init__.py+++ b/deeptutor/tools/builtin/__init__.py@@ -83,7 +83,7 @@ class RAGTool(_PromptHintsMixin, BaseTool):extra_kwargs = {key: valuefor key, value in kwargs.items()- if key not in {"query", "kb_name", "mode", "event_sink"}+ if key not in {"query", "kb_name", "event_sink"}}result = await rag_search(@@ -511,8 +511,8 @@ BUILTIN_TOOL_TYPES: tuple[type[BaseTool], ...] = (BUILTIN_TOOL_NAMES: tuple[str, ...] = tuple(tool_type().name for tool_type in BUILTIN_TOOL_TYPES)TOOL_ALIASES: dict[str, tuple[str, dict[str, Any]]] = {- "rag_hybrid": ("rag", {}),- "rag_naive": ("rag", {}),+ "rag_hybrid": ("rag", {"mode": "hybrid"}),+ "rag_naive": ("rag", {"mode": "naive"}),"rag_search": ("rag", {}),"code_execute": ("code_execution", {}),"run_code": ("code_execution", {}),diff --git a/deeptutor_cli/notebook.py b/deeptutor_cli/notebook.pyindex 0a2724d80..4e1a5fbdb 100644--- a/deeptutor_cli/notebook.py+++ b/deeptutor_cli/notebook.py@@ -51,27 +51,6 @@ def register(app: typer.Typer) -> None:f"{record.get('title', '')}")- @app.command("add-md")- def add_md(- notebook_id: str = typer.Argument(..., help="Notebook id."),- path: str = typer.Argument(..., help="Path to markdown file."),- ) -> None:- """Import a markdown file as a co-writer notebook record."""- client = DeepTutorApp()- result = client.import_markdown_into_notebook(notebook_id, path)- console.print(json.dumps(result, ensure_ascii=False, indent=2, default=str))-- @app.command("replace-md")- def replace_md(- notebook_id: str = typer.Argument(..., help="Notebook id."),- record_id: str = typer.Argument(..., help="Existing record id."),- path: str = typer.Argument(..., help="Path to markdown file."),- ) -> None:- """Replace an existing co-writer notebook record in-place."""- client = DeepTutorApp()- record = client.replace_markdown_record(notebook_id, record_id, path)- console.print(json.dumps(record, ensure_ascii=False, indent=2, default=str))-@app.command("remove-record")def remove_record(notebook_id: str = typer.Argument(..., help="Notebook id."),diff --git a/tests/agents/__init__.py b/tests/agents/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tests/agents/chat/__init__.py b/tests/agents/chat/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tests/agents/math_animator/__init__.py b/tests/agents/math_animator/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tests/agents/question/__init__.py b/tests/agents/question/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tests/agents/research/__init__.py b/tests/agents/research/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tests/agents/research/test_request_config.py b/tests/agents/research/test_request_config.pyindex cad433906..a969eae87 100644--- a/tests/agents/research/test_request_config.py+++ b/tests/agents/research/test_request_config.py@@ -38,7 +38,7 @@ def test_build_research_execution_policy_maps_intent_to_internal_settings() -> Nassert policy["planning"]["rephrase"]["enabled"] is Trueassert policy["planning"]["decompose"]["mode"] == "manual"assert policy["researching"]["execution_mode"] == "parallel"- assert policy["researching"]["enable_rag_hybrid"] is True+ assert policy["researching"]["enable_rag"] is Trueassert policy["researching"]["enable_web_search"] is Falseassert policy["researching"]["enable_paper_search"] is Trueassert policy["researching"]["enable_run_code"] is True@@ -60,8 +60,7 @@ def test_build_research_execution_policy_supports_llm_only_mode() -> None:enabled_tools=set(),)- assert policy["researching"]["enable_rag_hybrid"] is False- assert policy["researching"]["enable_rag_naive"] is False+ assert policy["researching"]["enable_rag"] is Falseassert policy["researching"]["enable_web_search"] is Falseassert policy["researching"]["enable_paper_search"] is Falseassert policy["researching"]["enable_run_code"] is False@@ -101,16 +100,14 @@ def test_build_research_runtime_config_uses_intent_and_sources() -> None:assert runtime["researching"]["max_iterations"] == 3assert runtime["researching"]["execution_mode"] == "series"assert runtime["researching"]["enable_web_search"] is True- assert runtime["researching"]["enable_rag_hybrid"] is False+ assert runtime["researching"]["enable_rag"] is Falseassert runtime["reporting"]["style"] == "learning_path"assert "outline_contract" not in runtime["reporting"]assert runtime["queue"]["max_length"] == 5assert runtime["rag"]["kb_name"] == "research-kb"- assert runtime["intent"] == {- "mode": "learning_path",- "depth": "standard",- "sources": ["web"],- }+ assert runtime["intent"]["mode"] == "learning_path"+ assert runtime["intent"]["depth"] == "standard"+ assert runtime["intent"]["sources"] == ["web"]def test_reporting_mode_contracts_live_in_prompt_files() -> None:diff --git a/tests/agents/solve/__init__.py b/tests/agents/solve/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tests/agents/solve/utils/__init__.py b/tests/agents/solve/utils/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tests/api/__init__.py b/tests/api/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tests/api/test_main_notebook_router.py b/tests/api/test_main_notebook_router.pyindex 646dabc04..5dfa46192 100644--- a/tests/api/test_main_notebook_router.py+++ b/tests/api/test_main_notebook_router.py@@ -2,7 +2,6 @@Verifies that records can only be saved using real notebook UUIDs(from /api/v1/notebook/list), not question-notebook category integer IDs.-Regression test for issue #301 (Co-Writer save to notebook)."""from __future__ import annotations@@ -71,7 +70,7 @@ def test_add_record_with_valid_notebook_id(manager: NotebookManager) -> None:"/api/v1/notebook/add_record",json={"notebook_ids": [nb_id],- "record_type": "co_writer",+ "record_type": "chat","title": "Draft on Fourier","summary": "Existing summary","user_query": "Explain Fourier",@@ -102,7 +101,7 @@ def test_add_record_with_numeric_category_id_saves_nothing(manager: NotebookMana"/api/v1/notebook/add_record",json={"notebook_ids": ["1", "42"],- "record_type": "co_writer",+ "record_type": "chat","title": "Lost draft","summary": "This should not be saved anywhere","user_query": "...",diff --git a/tests/cli/__init__.py b/tests/cli/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tests/core/test_builtin_tools.py b/tests/core/test_builtin_tools.pyindex 425b4985a..2c556ec2b 100644--- a/tests/core/test_builtin_tools.py+++ b/tests/core/test_builtin_tools.py@@ -24,7 +24,6 @@ from deeptutor.tools.builtin import (def _install_module(monkeypatch: pytest.MonkeyPatch, fullname: str, **attrs: Any) -> types.ModuleType:"""Install a fake module (and missing parent packages) into sys.modules."""- __import__("src")parts = fullname.split(".")for idx in range(1, len(parts)):pkg_name = ".".join(parts[:idx])diff --git a/tests/core/test_capabilities_runtime.py b/tests/core/test_capabilities_runtime.pyindex 581007e38..be0ae98f5 100644--- a/tests/core/test_capabilities_runtime.py+++ b/tests/core/test_capabilities_runtime.py@@ -20,7 +20,6 @@ from deeptutor.core.stream_bus import StreamBusdef _install_module(monkeypatch: pytest.MonkeyPatch, fullname: str, **attrs: Any) -> types.ModuleType:- __import__("src")parts = fullname.split(".")for idx in range(1, len(parts)):pkg_name = ".".join(parts[:idx])@@ -434,7 +433,9 @@ async def test_deep_research_capability_requires_explicit_config_and_streams_tracaptured["pipeline_init"] = kwargsasync def run(self, topic: str) -> dict[str, Any]:- await captured["pipeline_init"]["progress_callback"](+ # progress_callback is fire-and-forget (sync) inside the+ # capability; just call it.+ captured["pipeline_init"]["progress_callback"]({"status": "gathering evidence", "stage": "researching", "block_id": "block_1"})await captured["pipeline_init"]["trace_callback"](@@ -455,6 +456,8 @@ async def test_deep_research_capability_requires_explicit_config_and_streams_tra"call_id": "research-tool-1",})+ # Allow the scheduled progress task to flush onto the bus.+ await asyncio.sleep(0)return {"report": f"Report about {topic}", "metadata": {"citations": 3}}def fake_load_config_with_main(_: str) -> dict[str, Any]:@@ -495,6 +498,12 @@ async def test_deep_research_capability_requires_explicit_config_and_streams_tra"mode": "report","depth": "standard","sources": ["kb", "web", "papers"],+ # Provide a confirmed outline so the capability skips the+ # outline-preview short-circuit and runs the full pipeline.+ "confirmed_outline": [+ {"title": "Background", "overview": "Why this topic matters"},+ {"title": "Approaches", "overview": "How to do it"},+ ],},language="en",)diff --git a/tests/core/test_prompt_parity.py b/tests/core/test_prompt_parity.pyindex 76a234f48..cb314b66f 100644--- a/tests/core/test_prompt_parity.py+++ b/tests/core/test_prompt_parity.py@@ -7,7 +7,12 @@ from typing import Any, Iterableimport yamlPROJECT_ROOT = Path(__file__).resolve().parents[2]-AGENTS_DIR = PROJECT_ROOT / "src" / "agents"+AGENTS_DIR = PROJECT_ROOT / "deeptutor" / "agents"+# Modules that live outside deeptutor/agents/ but still own prompts.+EXTRA_PROMPT_MODULE_DIRS = (+ PROJECT_ROOT / "deeptutor" / "book",+ PROJECT_ROOT / "deeptutor" / "co_writer",+)# Template placeholders are expected to be like {topic}, {knowledge_title}, etc.# Avoid false positives from LaTeX (\frac{1}{3}) and Mermaid (B{{Processing}}).@@ -59,7 +64,12 @@ def test_prompts_key_and_placeholder_parity():failures: list[str] = []- for module_dir in sorted([p for p in AGENTS_DIR.iterdir() if p.is_dir()]):+ module_dirs: list[Path] = sorted(+ [p for p in AGENTS_DIR.iterdir() if p.is_dir() and not p.name.startswith("__")]+ )+ module_dirs.extend(p for p in EXTRA_PROMPT_MODULE_DIRS if p.is_dir())++ for module_dir in module_dirs:prompts_dir = module_dir / "prompts"en_dir = prompts_dir / "en"if not en_dir.exists():diff --git a/tests/knowledge/__init__.py b/tests/knowledge/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tests/scripts/__init__.py b/tests/scripts/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tests/services/config/test_llm_probe_config.py b/tests/services/config/test_llm_probe_config.pyindex 14f7b5903..884d1d11e 100644--- a/tests/services/config/test_llm_probe_config.py+++ b/tests/services/config/test_llm_probe_config.py@@ -10,6 +10,7 @@ from unittest.mock import AsyncMock, patchimport pytestimport yaml+from deeptutor.services.config import loader as loader_modulefrom deeptutor.services.config.loader import get_agent_params@@ -33,9 +34,7 @@ class TestGetAgentParamsLlmProbe:project_root = _write_agents_yaml(tmp_path, {"diagnostics": {"llm_probe": {"max_tokens": 2048}},})- monkeypatch.setattr(- "deeptutor.services.config.loader.PROJECT_ROOT", project_root,- )+ monkeypatch.setattr(loader_module, "PROJECT_ROOT", project_root)params = get_agent_params("llm_probe")assert params["max_tokens"] == 2048@@ -43,9 +42,7 @@ class TestGetAgentParamsLlmProbe:project_root = _write_agents_yaml(tmp_path, {"capabilities": {"solve": {"temperature": 0.3}},})- monkeypatch.setattr(- "deeptutor.services.config.loader.PROJECT_ROOT", project_root,- )+ monkeypatch.setattr(loader_module, "PROJECT_ROOT", project_root)params = get_agent_params("llm_probe")assert params["max_tokens"] == 4096assert params["temperature"] == 0.5@@ -54,9 +51,7 @@ class TestGetAgentParamsLlmProbe:project_root = _write_agents_yaml(tmp_path, {"diagnostics": {"llm_probe": {"temperature": 0.1}},})- monkeypatch.setattr(- "deeptutor.services.config.loader.PROJECT_ROOT", project_root,- )+ monkeypatch.setattr(loader_module, "PROJECT_ROOT", project_root)params = get_agent_params("llm_probe")assert params["max_tokens"] == 4096assert params["temperature"] == 0.1@@ -65,9 +60,7 @@ class TestGetAgentParamsLlmProbe:project_root = _write_agents_yaml(tmp_path, {"diagnostics": {"llm_probe": {"max_tokens": 512, "temperature": 0.2}},})- monkeypatch.setattr(- "deeptutor.services.config.loader.PROJECT_ROOT", project_root,- )+ monkeypatch.setattr(loader_module, "PROJECT_ROOT", project_root)params = get_agent_params("llm_probe")assert params["max_tokens"] == 512assert params["temperature"] == 0.2@@ -84,9 +77,7 @@ def _patch_project_root(tmp_path: Path, monkeypatch):project_root = _write_agents_yaml(tmp_path, {"diagnostics": {"llm_probe": {"max_tokens": 768}},})- monkeypatch.setattr(- "deeptutor.services.config.loader.PROJECT_ROOT", project_root,- )+ monkeypatch.setattr(loader_module, "PROJECT_ROOT", project_root)return project_root@@ -96,7 +87,9 @@ class TestLlmProbeUsesAgentsYaml:@pytest.mark.asyncio@pytest.mark.usefixtures("_patch_project_root")async def test_probe_passes_configured_max_tokens(self, monkeypatch):+ from deeptutor.services.config import test_runner as test_runner_modulefrom deeptutor.services.config.test_runner import ConfigTestRunner, TestRun+ from deeptutor.services import llm as llm_modulecaptured_kwargs: dict[str, Any] = {}@@ -105,19 +98,12 @@ class TestLlmProbeUsesAgentsYaml:return "OK I am gpt-4o-mini"monkeypatch.setattr(- "deeptutor.services.config.test_runner.resolve_llm_runtime_config",+ test_runner_module, "resolve_llm_runtime_config",lambda catalog: _stub_resolved_llm(),)- monkeypatch.setattr(- "deeptutor.services.llm.get_token_limit_kwargs",- _real_get_token_limit_kwargs,- )- monkeypatch.setattr(- "deeptutor.services.llm.complete", _fake_llm_complete,- )- monkeypatch.setattr(- "deeptutor.services.llm.clear_llm_config_cache", lambda: None,- )+ monkeypatch.setattr(llm_module, "get_token_limit_kwargs", _real_get_token_limit_kwargs)+ monkeypatch.setattr(llm_module, "complete", _fake_llm_complete)+ monkeypatch.setattr(llm_module, "clear_llm_config_cache", lambda: None)runner = ConfigTestRunner()run = TestRun(id="test-llm-probe", service="llm")@@ -129,11 +115,11 @@ class TestLlmProbeUsesAgentsYaml:async def test_probe_defaults_when_no_diagnostics_section(self, tmp_path, monkeypatch):"""When diagnostics section is absent, falls back to get_agent_params default (4096)."""project_root = _write_agents_yaml(tmp_path, {"capabilities": {}})- monkeypatch.setattr(- "deeptutor.services.config.loader.PROJECT_ROOT", project_root,- )+ monkeypatch.setattr(loader_module, "PROJECT_ROOT", project_root)+ from deeptutor.services.config import test_runner as test_runner_modulefrom deeptutor.services.config.test_runner import ConfigTestRunner, TestRun+ from deeptutor.services import llm as llm_modulecaptured_kwargs: dict[str, Any] = {}@@ -142,19 +128,12 @@ class TestLlmProbeUsesAgentsYaml:return "OK I am gpt-4o-mini"monkeypatch.setattr(- "deeptutor.services.config.test_runner.resolve_llm_runtime_config",+ test_runner_module, "resolve_llm_runtime_config",lambda catalog: _stub_resolved_llm(),)- monkeypatch.setattr(- "deeptutor.services.llm.get_token_limit_kwargs",- _real_get_token_limit_kwargs,- )- monkeypatch.setattr(- "deeptutor.services.llm.complete", _fake_llm_complete,- )- monkeypatch.setattr(- "deeptutor.services.llm.clear_llm_config_cache", lambda: None,- )+ monkeypatch.setattr(llm_module, "get_token_limit_kwargs", _real_get_token_limit_kwargs)+ monkeypatch.setattr(llm_module, "complete", _fake_llm_complete)+ monkeypatch.setattr(llm_module, "clear_llm_config_cache", lambda: None)runner = ConfigTestRunner()run = TestRun(id="test-llm-probe-default", service="llm")diff --git a/tests/services/llm/__init__.py b/tests/services/llm/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tests/services/llm/test_factory_provider_exec.py b/tests/services/llm/test_factory_provider_exec.pyindex 32987b84e..9add2e968 100644--- a/tests/services/llm/test_factory_provider_exec.py+++ b/tests/services/llm/test_factory_provider_exec.py@@ -5,7 +5,7 @@ from __future__ import annotationsimport pytestfrom deeptutor.services.llm.config import LLMConfig-from deeptutor.services.llm.factory import complete, stream+from deeptutor.services.llm.factory import complete, stream # noqa: F401# ---------------------------------------------------------------------------@@ -110,96 +110,13 @@ async def test_stream_merges_config_and_caller_extra_headers(monkeypatch) -> Nonassert headers["X-Caller"] == "clr"-async def test_factory_complete_uses_litellm(monkeypatch) -> None:- cfg = LLMConfig(- model="google/gemini-2.5-pro",- api_key="sk-or-test",- base_url="https://openrouter.ai/api/v1",- binding="openrouter",- provider_name="openrouter",- provider_mode="gateway",- )- captured: dict[str, object] = {}-- async def _fake_litellm_complete(**kwargs):- captured.update(kwargs)- return "ok"-- monkeypatch.setattr("deeptutor.services.llm.factory.get_llm_config", lambda: cfg)- monkeypatch.setattr("deeptutor.services.llm.factory.litellm_available", lambda: True)- monkeypatch.setattr("deeptutor.services.llm.factory.litellm_complete", _fake_litellm_complete)-- result = await complete("hello")- assert result == "ok"- assert captured["provider_name"] == "openrouter"- assert captured["model"] == "google/gemini-2.5-pro"---async def test_factory_complete_uses_direct_azure(monkeypatch) -> None:- cfg = LLMConfig(- model="gpt-4o-mini",- api_key="azure-key",- base_url="https://example.openai.azure.com/openai/deployments/demo",- binding="azure_openai",- provider_name="azure_openai",- provider_mode="direct",- api_version="2024-10-21",- )- captured: dict[str, object] = {}-- async def _fake_cloud_complete(**kwargs):- captured.update(kwargs)- return "ok"-- monkeypatch.setattr("deeptutor.services.llm.factory.get_llm_config", lambda: cfg)- monkeypatch.setattr("deeptutor.services.llm.factory.litellm_available", lambda: False)- monkeypatch.setattr("deeptutor.services.llm.cloud_provider.complete", _fake_cloud_complete)-- result = await complete("hello")- assert result == "ok"- assert captured["binding"] == "azure_openai"---async def test_factory_complete_openai_codex_requires_oauth(monkeypatch) -> None:- cfg = LLMConfig(- model="openai_codex/codex-mini-latest",- api_key="",- base_url="https://chatgpt.com/backend-api",- binding="openai_codex",- provider_name="openai_codex",- provider_mode="oauth",- )- monkeypatch.setattr("deeptutor.services.llm.factory.get_llm_config", lambda: cfg)- monkeypatch.setattr("deeptutor.services.llm.factory.litellm_available", lambda: False)-- with pytest.raises(Exception):- await complete("hello", max_retries=0)---async def test_factory_stream_uses_litellm(monkeypatch) -> None:- cfg = LLMConfig(- model="deepseek-chat",- api_key="deep-key",- base_url="https://api.deepseek.com/v1",- binding="deepseek",- provider_name="deepseek",- provider_mode="standard",- )-- async def _fake_litellm_stream(**kwargs):- _ = kwargs- yield "a"- yield "b"-- monkeypatch.setattr("deeptutor.services.llm.factory.get_llm_config", lambda: cfg)- monkeypatch.setattr("deeptutor.services.llm.factory.litellm_available", lambda: True)- monkeypatch.setattr("deeptutor.services.llm.factory.litellm_stream", _fake_litellm_stream)-- chunks = []- async for item in stream("hello"):- chunks.append(item)- assert "".join(chunks) == "ab"+# NOTE: The legacy litellm-routing tests (test_factory_complete_uses_litellm,+# test_factory_complete_uses_direct_azure,+# test_factory_complete_openai_codex_requires_oauth,+# test_factory_stream_uses_litellm) were removed. The factory no longer+# delegates to litellm — see deeptutor/services/llm/executors.py — so the+# `litellm_available`/`litellm_complete`/`litellm_stream` symbols and their+# routing branches no longer exist. The factory now always goes through+# `sdk_complete` / `sdk_stream`, which is exercised by the four+# extra_headers tests above and by tests/services/llm/test_factory_*.py+# elsewhere.diff --git a/tests/services/memory/__init__.py b/tests/services/memory/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tests/services/rag/conftest.py b/tests/services/rag/conftest.pynew file mode 100644index 000000000..0d77f2174--- /dev/null+++ b/tests/services/rag/conftest.py@@ -0,0 +1,18 @@+"""Local conftest for RAG integration tests.++The ``--pipeline`` option must be registered from a conftest (or a real+plugin), not from a test module — otherwise pytest raises+``ValueError: pytest_addoption is only supported from a plugin or conftest``.+"""++from __future__ import annotations+++def pytest_addoption(parser):+ """Register the ``--pipeline`` CLI option used by the integration tests."""+ parser.addoption(+ "--pipeline",+ action="store",+ default="llamaindex",+ help="Pipeline to test (e.g. llamaindex, all)",+ )diff --git a/tests/services/rag/test_pipeline_integration.py b/tests/services/rag/test_pipeline_integration.pyindex 5280c7884..eb723a052 100644--- a/tests/services/rag/test_pipeline_integration.py+++ b/tests/services/rag/test_pipeline_integration.py@@ -398,9 +398,8 @@ async def main():# Pytest support-def pytest_addoption(parser):- """Add pytest command line options"""- parser.addoption("--pipeline", action="store", default="llamaindex", help="Pipeline to test")+# NOTE: ``pytest_addoption`` lives in ``conftest.py`` next to this file, since+# pytest only honors that hook from conftests/plugins.class TestPipelineIntegration:@@ -408,7 +407,21 @@ class TestPipelineIntegration:@staticmethoddef test_pipeline(request):- """Test the specified pipeline"""+ """Test the specified pipeline.++ Requires a real RAG provider (LLM keys, embedding service, etc.) and is+ therefore opt-in. Skipped unless the ``RAG_INTEGRATION_TESTS=1`` env+ var is set, otherwise CI / sandboxed environments would always fail+ on Initialize.+ """+ if os.environ.get("RAG_INTEGRATION_TESTS") != "1":+ import pytest as _pytest++ _pytest.skip(+ "RAG pipeline integration test skipped "+ "(set RAG_INTEGRATION_TESTS=1 to enable)."+ )+pipeline_name = request.config.getoption("--pipeline")async def _run():diff --git a/tests/services/search/__init__.py b/tests/services/search/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tests/services/session/__init__.py b/tests/services/session/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tests/services/test_app_facade.py b/tests/services/test_app_facade.pydeleted file mode 100644index 56b9767fd..000000000--- a/tests/services/test_app_facade.py+++ /dev/null@@ -1,73 +0,0 @@-"""Tests for the public DeepTutor application facade."""--from __future__ import annotations--from pathlib import Path--from deeptutor.app import DeepTutorApp---class _FakeNotebookManager:- def __init__(self) -> None:- self.add_calls = []- self.update_calls = []- self.record = {- "id": "rec-1",- "type": "co_writer",- "title": "Old",- "output": "Old body",- "metadata": {"source": "co_writer"},- }-- def add_record(self, **kwargs): # noqa: ANN003- self.add_calls.append(kwargs)- return {"record": {"id": "rec-new", **kwargs}, "added_to_notebooks": kwargs["notebook_ids"]}-- def get_record(self, notebook_id: str, record_id: str): # noqa: ANN001- if notebook_id == "nb1" and record_id == "rec-1":- return dict(self.record)- return None-- def update_record(self, notebook_id: str, record_id: str, **kwargs): # noqa: ANN003- self.update_calls.append((notebook_id, record_id, kwargs))- return {"id": record_id, **kwargs}---def test_import_markdown_into_notebook_uses_co_writer_semantics(tmp_path: Path) -> None:- markdown = tmp_path / "lesson.md"- markdown.write_text("# Vectors\n\nSome content.", encoding="utf-8")-- app = DeepTutorApp()- fake_manager = _FakeNotebookManager()- app.notebooks = fake_manager-- result = app.import_markdown_into_notebook("nb1", markdown)-- assert result["record"]["id"] == "rec-new"- add_call = fake_manager.add_calls[0]- assert add_call["record_type"] == "co_writer"- assert add_call["title"] == "Vectors"- assert add_call["user_query"] == "Vectors"- assert add_call["output"] == "# Vectors\n\nSome content."- assert add_call["metadata"]["saved_via"] == "cli"- assert add_call["metadata"]["source_path"] == str(markdown.resolve())---def test_replace_markdown_record_updates_existing_co_writer_record(tmp_path: Path) -> None:- markdown = tmp_path / "updated.md"- markdown.write_text("# Matrices\n\nUpdated body.", encoding="utf-8")-- app = DeepTutorApp()- fake_manager = _FakeNotebookManager()- app.notebooks = fake_manager-- result = app.replace_markdown_record("nb1", "rec-1", markdown)-- assert result["id"] == "rec-1"- notebook_id, record_id, update_call = fake_manager.update_calls[0]- assert notebook_id == "nb1"- assert record_id == "rec-1"- assert update_call["title"] == "Matrices"- assert update_call["user_query"] == "Matrices"- assert update_call["output"] == "# Matrices\n\nUpdated body."- assert update_call["metadata"]["saved_via"] == "cli"diff --git a/tests/services/test_config_loader.py b/tests/services/test_config_loader.pyindex 8f779373e..0a5e6c6dc 100644--- a/tests/services/test_config_loader.py+++ b/tests/services/test_config_loader.py@@ -18,13 +18,13 @@ def test_resolve_config_path_returns_existing_config(tmp_path: Path) -> None:assert used_alias is False-def test_load_config_with_main_merges_main_and_module_config(tmp_path: Path) -> None:+def test_load_config_with_main_loads_config_file(tmp_path: Path) -> None:+ """``load_config_with_main`` reads the requested config file and injects+ runtime paths. It no longer auto-merges main.yaml — callers that need+ layered defaults are expected to do that explicitly.+ """settings_dir = tmp_path / "data" / "user" / "settings"settings_dir.mkdir(parents=True)- (settings_dir / "main.yaml").write_text(- "system:\n language: en\nsolve:\n max_replans: 2\n",- encoding="utf-8",- )(settings_dir / "custom.yaml").write_text("solve:\n max_replans: 5\nlogging:\n level: INFO\n",encoding="utf-8",@@ -32,7 +32,6 @@ def test_load_config_with_main_merges_main_and_module_config(tmp_path: Path) ->config = load_config_with_main("custom.yaml", tmp_path)- assert config["system"]["language"] == "en"assert config["solve"]["max_replans"] == 5assert config["logging"]["level"] == "INFO"diff --git a/tests/services/test_model_catalog.py b/tests/services/test_model_catalog.pyindex a872a18db..300ba0fc8 100644--- a/tests/services/test_model_catalog.py+++ b/tests/services/test_model_catalog.py@@ -1,5 +1,6 @@from pathlib import Path+from deeptutor.services.config import model_catalog as model_catalog_modulefrom deeptutor.services.config.env_store import EnvStorefrom deeptutor.services.config.model_catalog import ModelCatalogService@@ -40,7 +41,7 @@ def test_load_hydrates_empty_catalog_from_env(tmp_path: Path, monkeypatch):)env_store = EnvStore(path=env_path)- monkeypatch.setattr("deeptutor.services.config.model_catalog.get_env_store", lambda: env_store)+ monkeypatch.setattr(model_catalog_module, "get_env_store", lambda: env_store)service = ModelCatalogService(path=catalog_path)catalog = service.load()@@ -126,7 +127,7 @@ def test_load_syncs_existing_active_profiles_from_env(tmp_path: Path, monkeypatc)env_store = EnvStore(path=env_path)- monkeypatch.setattr("deeptutor.services.config.model_catalog.get_env_store", lambda: env_store)+ monkeypatch.setattr(model_catalog_module, "get_env_store", lambda: env_store)service = ModelCatalogService(path=catalog_path)catalog = service.load()diff --git a/tests/services/test_notebook_service.py b/tests/services/test_notebook_service.pyindex f7dc6d711..eaa41ed9d 100644--- a/tests/services/test_notebook_service.py+++ b/tests/services/test_notebook_service.py@@ -11,14 +11,14 @@ def test_add_record_accepts_enum_record_type(tmp_path) -> None:result = manager.add_record(notebook_ids=[notebook["id"]],- record_type=RecordType.CO_WRITER,+ record_type=RecordType.CHAT,title="Sample",user_query="Sample",output="# Sample",)- assert result["record"]["type"] == RecordType.CO_WRITER+ assert result["record"]["type"] == RecordType.CHATstored = manager.get_notebook(notebook["id"])assert stored is not None- assert stored["records"][0]["type"] == "co_writer"+ assert stored["records"][0]["type"] == "chat"diff --git a/tests/tools/__init__.py b/tests/tools/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/web/app/(utility)/knowledge/page.tsx b/web/app/(utility)/knowledge/page.tsxindex 0af27f6c6..a7c2ad8b5 100644--- a/web/app/(utility)/knowledge/page.tsx+++ b/web/app/(utility)/knowledge/page.tsx@@ -21,7 +21,6 @@ import {MessageSquare,NotebookPen,Pencil,- PenLine,Plus,Search,Star,@@ -727,8 +726,6 @@ function KnowledgePageContent() {switch (type) {case "chat":return { label: t("Chat"), color: "bg-sky-100 text-sky-700 dark:bg-sky-900/40 dark:text-sky-300", icon: MessageSquare };- case "co_writer":- return { label: t("Co-Writer"), color: "bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300", icon: PenLine };case "research":return { label: t("Research"), color: "bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300", icon: Search };default:diff --git a/web/app/(workspace)/co-writer/[docId]/page.tsx b/web/app/(workspace)/co-writer/[docId]/page.tsxnew file mode 100644index 000000000..162dd608f--- /dev/null+++ b/web/app/(workspace)/co-writer/[docId]/page.tsx@@ -0,0 +1,2168 @@+"use client";++import dynamic from "next/dynamic";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import {+ ArrowRight,+ ArrowUpRight,+ Bold,+ Braces,+ Check,+ ChevronDown,+ ChevronLeft,+ ChevronRight,+ Code2,+ Download,+ Eraser,+ FileText,+ Heading1,+ Heading2,+ Heading3,+ Heading4,+ Heading5,+ Heading6,+ Highlighter,+ Image as ImageIcon,+ Italic,+ Link as LinkIcon,+ List,+ ListOrdered,+ ListTodo,+ Loader2,+ Minus,+ Quote,+ Redo2,+ Strikethrough,+ Table2,+ Undo2,+ WandSparkles,+ Workflow,+} from "lucide-react";+import { useParams, useRouter } from "next/navigation";+import { apiUrl } from "@/lib/api";+import { listKnowledgeBases } from "@/lib/knowledge-api";+import {+ getCoWriterDocument,+ updateCoWriterDocument,+} from "@/lib/co-writer-api";+import { notifyCoWriterChanged } from "@/lib/co-writer-events";+import { CO_WRITER_SAMPLE_TEMPLATE } from "../sampleTemplate";++const MarkdownRenderer = dynamic(() => import("@/components/common/MarkdownRenderer"), {+ ssr: false,+});++type EditAction = "rewrite" | "shorten" | "expand";+type SelectionMode = EditAction | "none";+type SourceOption = "none" | "rag" | "web";+type ToolName =+ | "brainstorm"+ | "rag"+ | "web_search"+ | "code_execution"+ | "reason"+ | "paper_search";++interface KnowledgeBase {+ name: string;+ is_default?: boolean;+}++const SPLIT_RATIO_KEY = "deeptutor.co_writer.split_ratio";+const SYNC_SCROLL_KEY = "deeptutor.co_writer.sync_scroll";+const LOCAL_DRAFT_PREFIX = "deeptutor.co_writer.draft.";+const AUTOSAVE_DEBOUNCE_MS = 1500;+const MIN_PANEL_RATIO = 0.18;+const MAX_PANEL_RATIO = 0.82;++const ACTION_LABELS: Record<EditAction, string> = {+ rewrite: "Rewrite",+ shorten: "Shorten",+ expand: "Expand",+};++const TOOL_OPTIONS: Array<{ name: ToolName; label: string }> = [+ { name: "brainstorm", label: "Brainstorm" },+ { name: "rag", label: "RAG" },+ { name: "web_search", label: "Web Search" },+ { name: "code_execution", label: "Code" },+ { name: "reason", label: "Reason" },+ { name: "paper_search", label: "Arxiv Search" },+];++const MODE_OPTIONS: Array<{ value: SelectionMode; label: string }> = [+ { value: "none", label: "None" },+ { value: "shorten", label: "Shorten" },+ { value: "expand", label: "Expand" },+ { value: "rewrite", label: "Rewrite" },+];++interface ToolbarItem {+ id: string;+ icon: React.ComponentType<{ size?: number; className?: string }>;+ title: string;+ snippet?: string;+ type?: "separator";+ action?: () => void;+}++interface SelectedRange {+ start: number;+ end: number;+ text: string;+ snapshot: string;+}++interface SelectionPopoverState {+ visible: boolean;+ top: number;+ left: number;+}++interface SelectionToolTrace {+ kind?: "tool_call" | "tool_result";+ name: string;+ arguments: Record<string, unknown>;+ result: string;+ success: boolean;+ sources: Array<Record<string, unknown>>;+ metadata: Record<string, unknown>;+}++interface SelectionTraceData {+ thinking: string;+ toolTraces: SelectionToolTrace[];+ response: string;+}++interface StreamTraceEvent {+ type: string;+ stage?: string;+ content?: string;+ metadata?: Record<string, unknown>;+}++interface StreamEditResult {+ edited_text?: string;+}++export default function CoWriterPage() {+ const { t } = useTranslation();+ const router = useRouter();+ const params = useParams<{ docId?: string | string[] }>();+ const docId = useMemo(() => {+ const raw = params?.docId;+ if (!raw) return "";+ return Array.isArray(raw) ? raw[0] ?? "" : raw;+ }, [params]);+ const draftStorageKey = useMemo(+ () => (docId ? `${LOCAL_DRAFT_PREFIX}${docId}` : null),+ [docId],+ );+ const lastSavedContentRef = useRef<string>("");+ const autosaveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const isUnmountedRef = useRef(false);+ const [docTitle, setDocTitle] = useState<string>("");+ const [isEditingTitle, setIsEditingTitle] = useState(false);+ const [titleDraft, setTitleDraft] = useState<string>("");+ const titleInputRef = useRef<HTMLInputElement>(null);+ const [docNotFound, setDocNotFound] = useState(false);+ const [isLoadingDoc, setIsLoadingDoc] = useState(true);+ const [isSavingDoc, setIsSavingDoc] = useState(false);+ const [lastSavedAt, setLastSavedAt] = useState<number | null>(null);+ const textareaRef = useRef<HTMLTextAreaElement>(null);+ const previewScrollRef = useRef<HTMLDivElement>(null);+ const splitContainerRef = useRef<HTMLDivElement>(null);+ const scrollSyncSourceRef = useRef<"editor" | "preview" | null>(null);+ const scrollSyncResetTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const selectionPopoverRef = useRef<HTMLDivElement>(null);+ const preserveSelectionTraceRef = useRef(false);+ const selectionRequestAbortRef = useRef<AbortController | null>(null);+ const selectionDragStateRef = useRef<{ offsetX: number; offsetY: number } | null>(+ null,+ );+ const [markdown, setMarkdown] = useState("");+ const [instruction, setInstruction] = useState("");+ const [action, setAction] = useState<EditAction>("rewrite");+ const [source, setSource] = useState<SourceOption>("none");+ const [knowledgeBases, setKnowledgeBases] = useState<KnowledgeBase[]>([]);+ const [kbName, setKbName] = useState("");+ const [isEditing, setIsEditing] = useState(false);+ const [isAutoMarking, setIsAutoMarking] = useState(false);+ const [error, setError] = useState("");+ const [status, setStatus] = useState("");+ const [isEditModalOpen, setIsEditModalOpen] = useState(false);+ const [selectedRange, setSelectedRange] = useState<SelectedRange | null>(null);+ const [selectionPopover, setSelectionPopover] = useState<SelectionPopoverState>({+ visible: false,+ top: 0,+ left: 0,+ });+ const [selectionInstruction, setSelectionInstruction] = useState("");+ const [selectionMode, setSelectionMode] = useState<SelectionMode>("rewrite");+ const [selectionTools, setSelectionTools] = useState<ToolName[]>([]);+ const [isToolMenuOpen, setIsToolMenuOpen] = useState(false);+ const [isModeMenuOpen, setIsModeMenuOpen] = useState(false);+ const [selectionTrace, setSelectionTrace] = useState<SelectionTraceData | null>(+ null,+ );+ const [isTraceExpanded, setIsTraceExpanded] = useState(true);+ const [selectionPopoverPinned, setSelectionPopoverPinned] = useState(false);+ const [isDraggingSelectionPopover, setIsDraggingSelectionPopover] =+ useState(false);++ const [editorCollapsed, setEditorCollapsed] = useState(false);+ const [previewCollapsed, setPreviewCollapsed] = useState(false);+ const [editorRatio, setEditorRatio] = useState(0.5);+ const [isResizingSplit, setIsResizingSplit] = useState(false);+ const [syncScrollEnabled, setSyncScrollEnabled] = useState(true);+ const showEditor = !editorCollapsed;+ const showPreview = !previewCollapsed;++ const [undoStack, setUndoStack] = useState<string[]>([]);+ const [redoStack, setRedoStack] = useState<string[]>([]);+ const undoTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const [hasLoadedDraft, setHasLoadedDraft] = useState(false);++ useEffect(() => {+ const savedRatio = window.localStorage.getItem(SPLIT_RATIO_KEY);+ if (savedRatio) {+ const parsed = Number.parseFloat(savedRatio);+ if (Number.isFinite(parsed)) {+ setEditorRatio(+ Math.min(MAX_PANEL_RATIO, Math.max(MIN_PANEL_RATIO, parsed)),+ );+ }+ }++ const savedSync = window.localStorage.getItem(SYNC_SCROLL_KEY);+ if (savedSync !== null) {+ setSyncScrollEnabled(savedSync !== "0");+ }+ }, []);++ useEffect(() => {+ isUnmountedRef.current = false;+ return () => {+ isUnmountedRef.current = true;+ };+ }, []);++ // Load document content from server when docId is available.+ useEffect(() => {+ if (!docId) return;+ let cancelled = false;+ setIsLoadingDoc(true);+ setDocNotFound(false);+ setHasLoadedDraft(false);+ (async () => {+ try {+ const document = await getCoWriterDocument(docId);+ if (cancelled) return;+ // Prefer server content; fall back to local draft buffer if newer (rare:+ // page reloaded before debounced autosave completed).+ let content = document.content ?? "";+ if (draftStorageKey) {+ try {+ const localDraft = window.localStorage.getItem(draftStorageKey);+ if (localDraft !== null && localDraft !== content) {+ content = localDraft;+ }+ } catch {+ /* ignore */+ }+ }+ setMarkdown(content);+ setDocTitle(document.title || "");+ lastSavedContentRef.current = document.content ?? "";+ setLastSavedAt(document.updated_at ? document.updated_at * 1000 : Date.now());+ setHasLoadedDraft(true);+ } catch (err) {+ if (cancelled) return;+ const msg = err instanceof Error ? err.message : String(err);+ if (msg.includes("404")) {+ setDocNotFound(true);+ } else {+ setError(msg);+ }+ } finally {+ if (!cancelled) {+ setIsLoadingDoc(false);+ }+ }+ })();+ return () => {+ cancelled = true;+ };+ }, [docId, draftStorageKey]);++ // Mirror the in-flight content to localStorage so an accidental reload+ // doesn't lose unsaved characters before autosave fires.+ useEffect(() => {+ if (!hasLoadedDraft || !draftStorageKey) return;+ try {+ window.localStorage.setItem(draftStorageKey, markdown);+ } catch {+ /* ignore quota errors */+ }+ }, [hasLoadedDraft, draftStorageKey, markdown]);++ // Debounced autosave to the server.+ useEffect(() => {+ if (!hasLoadedDraft || !docId) return;+ if (markdown === lastSavedContentRef.current) return;+ if (autosaveTimerRef.current) clearTimeout(autosaveTimerRef.current);+ autosaveTimerRef.current = setTimeout(async () => {+ try {+ setIsSavingDoc(true);+ const updated = await updateCoWriterDocument(docId, { content: markdown });+ if (isUnmountedRef.current) return;+ lastSavedContentRef.current = markdown;+ setDocTitle(updated.title || "");+ setLastSavedAt(updated.updated_at ? updated.updated_at * 1000 : Date.now());+ if (draftStorageKey) {+ try {+ window.localStorage.removeItem(draftStorageKey);+ } catch {+ /* ignore */+ }+ }+ notifyCoWriterChanged();+ } catch (err) {+ if (isUnmountedRef.current) return;+ const msg = err instanceof Error ? err.message : String(err);+ setError(msg);+ } finally {+ if (!isUnmountedRef.current) {+ setIsSavingDoc(false);+ }+ }+ }, AUTOSAVE_DEBOUNCE_MS);+ return () => {+ if (autosaveTimerRef.current) {+ clearTimeout(autosaveTimerRef.current);+ autosaveTimerRef.current = null;+ }+ };+ }, [docId, hasLoadedDraft, markdown, draftStorageKey]);++ useEffect(() => {+ window.localStorage.setItem(SPLIT_RATIO_KEY, String(editorRatio));+ }, [editorRatio]);++ useEffect(() => {+ window.localStorage.setItem(SYNC_SCROLL_KEY, syncScrollEnabled ? "1" : "0");+ }, [syncScrollEnabled]);++ useEffect(() => {+ // Drop the cached editor line positions when the viewport changes width;+ // wrapping behavior depends on it.+ const handleResize = () => {+ editorYCacheRef.current = null;+ };+ window.addEventListener("resize", handleResize);+ return () => window.removeEventListener("resize", handleResize);+ }, []);++ // Editor inner width can change without a window resize (collapsing the+ // preview pane, dragging the splitter, etc). Invalidate the y cache so the+ // mirror remeasures with the new wrap width.+ useEffect(() => {+ editorYCacheRef.current = null;+ }, [editorRatio, editorCollapsed, previewCollapsed]);++ useEffect(() => {+ (async () => {+ try {+ const list = await listKnowledgeBases();+ setKnowledgeBases(list);+ const defaultKb =+ list.find((k: KnowledgeBase) => k.is_default)?.name ||+ list[0]?.name ||+ "";+ setKbName((prev) => prev || defaultKb);+ } catch {+ setKnowledgeBases([]);+ }+ })();+ }, []);++ const pushUndo = useCallback(+ (prev: string) => {+ setUndoStack((s) => [...s.slice(-50), prev]);+ setRedoStack([]);+ },+ [],+ );++ const handleMarkdownChange = useCallback(+ (value: string) => {+ if (undoTimerRef.current) clearTimeout(undoTimerRef.current);+ const prev = markdown;+ undoTimerRef.current = setTimeout(() => pushUndo(prev), 400);+ setMarkdown(value);+ },+ [markdown, pushUndo],+ );++ const handleUndo = useCallback(() => {+ if (undoStack.length === 0) return;+ const prev = undoStack[undoStack.length - 1];+ setRedoStack((s) => [...s, markdown]);+ setUndoStack((s) => s.slice(0, -1));+ setMarkdown(prev);+ }, [undoStack, markdown]);++ const handleRedo = useCallback(() => {+ if (redoStack.length === 0) return;+ const next = redoStack[redoStack.length - 1];+ setUndoStack((s) => [...s, markdown]);+ setRedoStack((s) => s.slice(0, -1));+ setMarkdown(next);+ }, [redoStack, markdown]);++ const startEditingTitle = useCallback(() => {+ if (isLoadingDoc) return;+ setTitleDraft(docTitle);+ setIsEditingTitle(true);+ }, [docTitle, isLoadingDoc]);++ const cancelEditingTitle = useCallback(() => {+ setIsEditingTitle(false);+ setTitleDraft("");+ }, []);++ const commitTitle = useCallback(async () => {+ if (!docId) {+ setIsEditingTitle(false);+ return;+ }+ const next = titleDraft.trim();+ const current = (docTitle || "").trim();+ setIsEditingTitle(false);+ if (next === current) return;+ try {+ setIsSavingDoc(true);+ const updated = await updateCoWriterDocument(docId, { title: next });+ if (isUnmountedRef.current) return;+ setDocTitle(updated.title || "");+ setLastSavedAt(+ updated.updated_at ? updated.updated_at * 1000 : Date.now(),+ );+ notifyCoWriterChanged();+ } catch (err) {+ if (isUnmountedRef.current) return;+ setError(err instanceof Error ? err.message : String(err));+ } finally {+ if (!isUnmountedRef.current) setIsSavingDoc(false);+ }+ }, [docId, docTitle, titleDraft]);++ useEffect(() => {+ if (!isEditingTitle) return;+ const input = titleInputRef.current;+ if (!input) return;+ input.focus();+ input.select();+ }, [isEditingTitle]);++ const wordCount = useMemo(() => {+ const trimmed = markdown.trim();+ if (!trimmed) return 0;+ return trimmed.split(/\s+/).length;+ }, [markdown]);++ const charCount = markdown.length;++ const hideSelectionPopover = useCallback(() => {+ selectionRequestAbortRef.current?.abort();+ selectionRequestAbortRef.current = null;+ selectionDragStateRef.current = null;+ setSelectionPopoverPinned(false);+ setIsDraggingSelectionPopover(false);+ setSelectionPopover((prev) => ({ ...prev, visible: false }));+ setSelectedRange(null);+ setSelectionInstruction("");+ setIsToolMenuOpen(false);+ setIsModeMenuOpen(false);+ setSelectionTrace(null);+ setIsTraceExpanded(true);+ }, []);++ const measureSelectionAnchor = useCallback(+ (textarea: HTMLTextAreaElement, index: number) => {+ const rect = textarea.getBoundingClientRect();+ const computed = window.getComputedStyle(textarea);+ const mirror = document.createElement("div");+ const properties = [+ "box-sizing",+ "width",+ "height",+ "overflow-x",+ "overflow-y",+ "border-top-width",+ "border-right-width",+ "border-bottom-width",+ "border-left-width",+ "padding-top",+ "padding-right",+ "padding-bottom",+ "padding-left",+ "font-style",+ "font-variant",+ "font-weight",+ "font-stretch",+ "font-size",+ "font-size-adjust",+ "line-height",+ "font-family",+ "letter-spacing",+ "text-align",+ "text-transform",+ "text-indent",+ "text-decoration",+ "tab-size",+ ];++ properties.forEach((property) => {+ mirror.style.setProperty(property, computed.getPropertyValue(property));+ });++ mirror.style.position = "fixed";+ mirror.style.top = `${rect.top}px`;+ mirror.style.left = `${rect.left}px`;+ mirror.style.whiteSpace = "pre-wrap";+ mirror.style.overflowWrap = "break-word";+ mirror.style.visibility = "hidden";+ mirror.style.pointerEvents = "none";++ mirror.textContent = textarea.value.slice(0, index);++ const marker = document.createElement("span");+ marker.textContent = textarea.value.slice(index) || ".";+ mirror.appendChild(marker);++ document.body.appendChild(mirror);++ const top = rect.top + marker.offsetTop - textarea.scrollTop;+ const left = rect.left + marker.offsetLeft - textarea.scrollLeft;++ document.body.removeChild(mirror);+ return { top, left };+ },+ [],+ );++ const updateSelectionPopover = useCallback(() => {+ const textarea = textareaRef.current;+ if (!textarea) {+ hideSelectionPopover();+ return;+ }++ const start = textarea.selectionStart;+ const end = textarea.selectionEnd;+ if (start === end) {+ hideSelectionPopover();+ return;+ }++ const text = textarea.value.slice(start, end);+ if (!text.trim()) {+ hideSelectionPopover();+ return;+ }++ const anchor = measureSelectionAnchor(textarea, end);+ const width = 360;+ const left = Math.min(+ Math.max(anchor.left - width / 2, 12),+ window.innerWidth - width - 12,+ );+ const top = Math.max(anchor.top - 98, 12);++ setSelectedRange((prev) => {+ const changed =+ !prev ||+ prev.start !== start ||+ prev.end !== end ||+ prev.text !== text ||+ prev.snapshot !== markdown;+ if (changed) {+ setSelectionPopoverPinned(false);+ if (preserveSelectionTraceRef.current) {+ preserveSelectionTraceRef.current = false;+ } else {+ setSelectionTrace(null);+ }+ setIsTraceExpanded(true);+ }+ return { start, end, text, snapshot: markdown };+ });+ setSelectionPopover((prev) => ({+ visible: true,+ top: selectionPopoverPinned ? prev.top : top,+ left: selectionPopoverPinned ? prev.left : left,+ }));+ }, [+ hideSelectionPopover,+ markdown,+ measureSelectionAnchor,+ selectionPopoverPinned,+ ]);++ const insertSnippet = useCallback(+ (snippet: string) => {+ pushUndo(markdown);+ const textarea = textareaRef.current;+ if (!textarea) {+ setMarkdown((prev) => `${prev}\n${snippet}`);+ return;+ }+ const start = textarea.selectionStart;+ const end = textarea.selectionEnd;+ const next = `${markdown.slice(0, start)}${snippet}${markdown.slice(end)}`;+ setMarkdown(next);+ requestAnimationFrame(() => {+ textarea.focus();+ const cursor = start + snippet.length;+ textarea.setSelectionRange(cursor, cursor);+ });+ },+ [markdown, pushUndo],+ );++ const clearDocument = () => {+ pushUndo(markdown);+ setMarkdown("");+ setStatus("");+ setError("");+ };++ const loadExampleTemplate = useCallback(() => {+ if (markdown === CO_WRITER_SAMPLE_TEMPLATE) {+ setStatus(t("Example template is already loaded."));+ setError("");+ return;+ }++ pushUndo(markdown);+ setMarkdown(CO_WRITER_SAMPLE_TEMPLATE);+ setStatus(t("Loaded example template."));+ setError("");+ }, [markdown, pushUndo]);++ const handleDownload = () => {+ const blob = new Blob([markdown], { type: "text/markdown;charset=utf-8" });+ const url = URL.createObjectURL(blob);+ const anchor = document.createElement("a");+ anchor.href = url;+ anchor.download = "co-writer.md";+ anchor.click();+ URL.revokeObjectURL(url);+ };++ const replaceSelectedText = useCallback(+ (range: SelectedRange, replacement: string) => {+ pushUndo(range.snapshot);+ const next = `${range.snapshot.slice(0, range.start)}${replacement}${range.snapshot.slice(range.end)}`;+ preserveSelectionTraceRef.current = true;+ setMarkdown(next);+ setSelectedRange({+ start: range.start,+ end: range.start + replacement.length,+ text: replacement,+ snapshot: next,+ });++ requestAnimationFrame(() => {+ const textarea = textareaRef.current;+ if (!textarea) return;+ textarea.focus();+ textarea.setSelectionRange(range.start, range.start + replacement.length);+ updateSelectionPopover();+ });+ },+ [pushUndo, updateSelectionPopover],+ );++ const toggleSelectionTool = useCallback((tool: ToolName) => {+ setSelectionTools((prev) =>+ prev.includes(tool) ? prev.filter((item) => item !== tool) : [...prev, tool],+ );+ }, []);++ const handleSelectionPopoverDragStart = useCallback(+ (event: React.MouseEvent<HTMLDivElement>) => {+ const target = event.target as HTMLElement;+ if (+ target.closest(+ "input, textarea, button, select, option, a, [data-no-drag='true']",+ )+ ) {+ return;+ }+ event.preventDefault();+ selectionDragStateRef.current = {+ offsetX: event.clientX - selectionPopover.left,+ offsetY: event.clientY - selectionPopover.top,+ };+ setSelectionPopoverPinned(true);+ setIsDraggingSelectionPopover(true);+ setIsToolMenuOpen(false);+ setIsModeMenuOpen(false);+ },+ [selectionPopover.left, selectionPopover.top],+ );++ const updateSelectionTraceFromEvent = useCallback((event: StreamTraceEvent) => {+ setSelectionTrace((prev) => {+ const current = prev ?? { thinking: "", toolTraces: [], response: "" };+ if (event.type === "thinking") {+ return { ...current, thinking: `${current.thinking}${event.content || ""}` };+ }+ if (event.type === "tool_call") {+ return {+ ...current,+ toolTraces: [+ ...current.toolTraces,+ {+ kind: "tool_call",+ name: String(event.content || ""),+ arguments:+ event.metadata && typeof event.metadata.args === "object"+ ? (event.metadata.args as Record<string, unknown>)+ : {},+ result: "",+ success: true,+ sources: [],+ metadata: event.metadata || {},+ },+ ],+ };+ }+ if (event.type === "tool_result") {+ return {+ ...current,+ toolTraces: [+ ...current.toolTraces,+ {+ kind: "tool_result",+ name: String(event.metadata?.tool || "result"),+ arguments: {},+ result: String(event.content || ""),+ success: true,+ sources: [],+ metadata: event.metadata || {},+ },+ ],+ };+ }+ if (event.type === "content" && event.stage === "responding") {+ return { ...current, response: `${current.response}${event.content || ""}` };+ }+ return current;+ });+ }, []);++ const applyReactSelectionEdit = useCallback(async () => {+ if (!selectedRange) {+ setError(t("Please select a text passage first."));+ return;+ }++ if (selectionMode === "none" && !selectionInstruction.trim()) {+ setError(t("Please enter an instruction or choose a mode."));+ return;+ }++ setIsEditing(true);+ setError("");+ setStatus("");+ setSelectionTrace({ thinking: "", toolTraces: [], response: "" });+ setIsTraceExpanded(true);+ selectionRequestAbortRef.current?.abort();+ const controller = new AbortController();+ selectionRequestAbortRef.current = controller;++ try {+ const response = await fetch(apiUrl("/api/v1/co_writer/edit_react/stream"), {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ signal: controller.signal,+ body: JSON.stringify({+ selected_text: selectedRange.text,+ instruction: selectionInstruction.trim(),+ mode: selectionMode,+ tools: selectionTools,+ kb_name: selectionTools.includes("rag") ? kbName || null : null,+ }),+ });+ if (!response.ok) {+ throw new Error((await response.text()) || "Failed to edit selected text.");+ }+ if (!response.body) {+ throw new Error("Streaming response body is missing.");+ }++ const reader = response.body.getReader();+ const decoder = new TextDecoder();+ let buffer = "";+ let finalResult: StreamEditResult | undefined;++ const processSseChunk = (chunk: string) => {+ const lines = chunk.split(/\r?\n/);+ let eventName = "message";+ const dataLines: string[] = [];+ for (const line of lines) {+ if (line.startsWith("event:")) {+ eventName = line.slice(6).trim();+ } else if (line.startsWith("data:")) {+ dataLines.push(line.slice(5).trimStart());+ }+ }+ if (dataLines.length === 0) return;+ const payload = JSON.parse(dataLines.join("\n"));+ if (eventName === "stream") {+ updateSelectionTraceFromEvent(payload as StreamTraceEvent);+ return;+ }+ if (eventName === "result") {+ finalResult = payload as StreamEditResult;+ return;+ }+ if (eventName === "error") {+ throw new Error(String(payload?.detail || "Failed to edit selected text."));+ }+ };++ while (true) {+ const { value, done } = await reader.read();+ if (done) break;+ buffer += decoder.decode(value, { stream: true });+ while (true) {+ const delimiterIndex = buffer.indexOf("\n\n");+ if (delimiterIndex === -1) break;+ const rawEvent = buffer.slice(0, delimiterIndex);+ buffer = buffer.slice(delimiterIndex + 2);+ processSseChunk(rawEvent);+ }+ }+ buffer += decoder.decode();+ if (buffer.trim()) {+ processSseChunk(buffer.trim());+ }+ if (finalResult === undefined) {+ throw new Error("Did not receive a final edit result.");+ }+ const editedText = finalResult.edited_text ?? "";++ if (markdown !== selectedRange.snapshot) {+ throw new Error(+ "The draft changed before AI edit finished. Please reselect the text and try again.",+ );+ }++ replaceSelectedText(selectedRange, editedText);+ setStatus(t("Applied AI edit to the selection."));+ } catch (err) {+ if (err instanceof DOMException && err.name === "AbortError") {+ return;+ }+ setError(+ err instanceof Error ? err.message : "Failed to edit selected text.",+ );+ } finally {+ selectionRequestAbortRef.current = null;+ setIsEditing(false);+ }+ }, [+ kbName,+ markdown,+ replaceSelectedText,+ selectedRange,+ selectionInstruction,+ selectionMode,+ selectionTools,+ updateSelectionTraceFromEvent,+ ]);++ const applyEdit = async () => {+ if (!instruction.trim()) {+ setError(t("Please enter an editing instruction first."));+ return;+ }+ setIsEditing(true);+ setError("");+ setStatus("");+ try {+ const response = await fetch(apiUrl("/api/v1/co_writer/edit"), {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ text: markdown,+ instruction: instruction.trim(),+ action,+ source: source === "none" ? null : source,+ kb_name: source === "rag" ? kbName || null : null,+ }),+ });+ const data = await response.json();+ if (!response.ok)+ throw new Error(data?.detail || "Failed to edit document.");+ pushUndo(markdown);+ setMarkdown(data.edited_text || "");+ setStatus(t("Applied {{action}} to the full draft.", { action: t(ACTION_LABELS[action]).toLowerCase() }));+ setIsEditModalOpen(false);+ } catch (err) {+ setError(err instanceof Error ? err.message : "Failed to edit document.");+ } finally {+ setIsEditing(false);+ }+ };++ const applyAutoMark = async () => {+ setIsAutoMarking(true);+ setError("");+ setStatus("");+ try {+ const response = await fetch(apiUrl("/api/v1/co_writer/automark"), {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ text: markdown }),+ });+ const data = await response.json();+ if (!response.ok)+ throw new Error(data?.detail || "Failed to auto-mark document.");+ pushUndo(markdown);+ setMarkdown(data.marked_text || "");+ setStatus(t("Applied auto-mark annotations."));+ } catch (err) {+ setError(+ err instanceof Error ? err.message : "Failed to auto-mark document.",+ );+ } finally {+ setIsAutoMarking(false);+ }+ };++ const TOOLBAR: ToolbarItem[] = useMemo(+ () => [+ { id: "undo", icon: Undo2, title: "Undo", action: handleUndo },+ { id: "redo", icon: Redo2, title: "Redo", action: handleRedo },+ { id: "sep-1", icon: Minus, title: "", type: "separator" },+ { id: "h1", icon: Heading1, title: "Heading 1", snippet: "\n# " },+ { id: "h2", icon: Heading2, title: "Heading 2", snippet: "\n## " },+ { id: "h3", icon: Heading3, title: "Heading 3", snippet: "\n### " },+ { id: "h4", icon: Heading4, title: "Heading 4", snippet: "\n#### " },+ { id: "h5", icon: Heading5, title: "Heading 5", snippet: "\n##### " },+ { id: "h6", icon: Heading6, title: "Heading 6", snippet: "\n###### " },+ { id: "sep-2", icon: Minus, title: "", type: "separator" },+ { id: "bold", icon: Bold, title: "Bold", snippet: "**bold**" },+ { id: "italic", icon: Italic, title: "Italic", snippet: "*italic*" },+ {+ id: "strikethrough",+ icon: Strikethrough,+ title: "Strikethrough",+ snippet: "~~text~~",+ },+ { id: "code", icon: Braces, title: "Inline Code", snippet: "`code`" },+ { id: "sep-3", icon: Minus, title: "", type: "separator" },+ { id: "quote", icon: Quote, title: "Blockquote", snippet: "\n> " },+ {+ id: "ul",+ icon: List,+ title: "Bullet List",+ snippet: "\n- Item\n- Item\n",+ },+ {+ id: "ol",+ icon: ListOrdered,+ title: "Numbered List",+ snippet: "\n1. Item\n2. Item\n",+ },+ {+ id: "task",+ icon: ListTodo,+ title: "Task List",+ snippet: "\n- [ ] Task\n- [x] Done\n",+ },+ { id: "sep-4", icon: Minus, title: "", type: "separator" },+ { id: "hr", icon: Minus, title: "Horizontal Rule", snippet: "\n---\n" },+ {+ id: "table",+ icon: Table2,+ title: "Table",+ snippet:+ "\n| Column | Column |\n| ------ | ------ |\n| Cell | Cell |\n",+ },+ {+ id: "link",+ icon: LinkIcon,+ title: "Link",+ snippet: "[text](https://)",+ },+ {+ id: "image",+ icon: ImageIcon,+ title: "Image",+ snippet: "",+ },+ { id: "sep-5", icon: Minus, title: "", type: "separator" },+ {+ id: "codeblock",+ icon: Code2,+ title: "Code Block",+ snippet: '\n```python\nprint("hello")\n```\n',+ },+ {+ id: "mermaid",+ icon: Workflow,+ title: "Mermaid Diagram",+ snippet:+ "\n```mermaid\nflowchart TD\n A[Start] --> B[End]\n```\n",+ },+ {+ id: "math",+ icon: () => (+ <span className="text-[11px] font-semibold leading-none">+ Σ+ </span>+ ),+ title: "Math Block",+ snippet: "\n$$\na^2 + b^2 = c^2\n$$\n",+ },+ ],+ [handleUndo, handleRedo],+ );++ useEffect(() => {+ if (!selectionPopover.visible) return;+ const handleViewportChange = () => updateSelectionPopover();+ window.addEventListener("resize", handleViewportChange);+ return () => window.removeEventListener("resize", handleViewportChange);+ }, [selectionPopover.visible, updateSelectionPopover]);++ useEffect(() => {+ if (!selectionPopover.visible) return;+ const handlePointerDown = (event: MouseEvent) => {+ const target = event.target as Node;+ if (selectionPopoverRef.current?.contains(target)) return;+ if (textareaRef.current?.contains(target)) return;+ hideSelectionPopover();+ };+ document.addEventListener("mousedown", handlePointerDown);+ return () => document.removeEventListener("mousedown", handlePointerDown);+ }, [hideSelectionPopover, selectionPopover.visible]);++ useEffect(() => {+ if (!isDraggingSelectionPopover) return;+ const handleMouseMove = (event: MouseEvent) => {+ const dragState = selectionDragStateRef.current;+ const popover = selectionPopoverRef.current;+ if (!dragState || !popover) return;+ const width = popover.offsetWidth || 360;+ const height = popover.offsetHeight || 200;+ const nextLeft = Math.min(+ Math.max(event.clientX - dragState.offsetX, 12),+ window.innerWidth - width - 12,+ );+ const nextTop = Math.min(+ Math.max(event.clientY - dragState.offsetY, 12),+ window.innerHeight - height - 12,+ );+ setSelectionPopover((prev) => ({+ ...prev,+ visible: true,+ top: nextTop,+ left: nextLeft,+ }));+ };+ const handleMouseUp = () => {+ selectionDragStateRef.current = null;+ setIsDraggingSelectionPopover(false);+ };+ window.addEventListener("mousemove", handleMouseMove);+ window.addEventListener("mouseup", handleMouseUp);+ return () => {+ window.removeEventListener("mousemove", handleMouseMove);+ window.removeEventListener("mouseup", handleMouseUp);+ };+ }, [isDraggingSelectionPopover]);++ useEffect(() => {+ return () => {+ selectionRequestAbortRef.current?.abort();+ if (scrollSyncResetTimerRef.current) {+ clearTimeout(scrollSyncResetTimerRef.current);+ }+ };+ }, []);++ const handleSplitterPointerDown = useCallback(+ (event: React.PointerEvent<HTMLDivElement>) => {+ if (!showEditor || !showPreview) return;+ event.preventDefault();+ setIsResizingSplit(true);+ try {+ (event.target as HTMLDivElement).setPointerCapture(event.pointerId);+ } catch {+ /* ignore */+ }+ },+ [showEditor, showPreview],+ );++ useEffect(() => {+ if (!isResizingSplit) return;+ const handleMove = (event: PointerEvent) => {+ const container = splitContainerRef.current;+ if (!container) return;+ const rect = container.getBoundingClientRect();+ if (rect.width <= 0) return;+ const ratio = (event.clientX - rect.left) / rect.width;+ setEditorRatio(+ Math.min(MAX_PANEL_RATIO, Math.max(MIN_PANEL_RATIO, ratio)),+ );+ };+ const handleEnd = () => setIsResizingSplit(false);+ window.addEventListener("pointermove", handleMove);+ window.addEventListener("pointerup", handleEnd);+ window.addEventListener("pointercancel", handleEnd);+ return () => {+ window.removeEventListener("pointermove", handleMove);+ window.removeEventListener("pointerup", handleEnd);+ window.removeEventListener("pointercancel", handleEnd);+ };+ }, [isResizingSplit]);++ const releaseScrollSyncSource = useCallback(() => {+ if (scrollSyncResetTimerRef.current) {+ clearTimeout(scrollSyncResetTimerRef.current);+ }+ scrollSyncResetTimerRef.current = setTimeout(() => {+ scrollSyncSourceRef.current = null;+ }, 90);+ }, []);++ // ── Line-anchored scroll synchronization ──+ //+ // Each block element rendered in the preview carries a `data-source-line`+ // attribute that points back at its starting line in the markdown source+ // (provided by remark's AST position info). For the editor side we cannot+ // assume `scrollTop / lineHeight = source line` because long lines wrap+ // visually. Instead we build a hidden mirror that mimics the textarea's+ // wrapping and read the real pixel y of every source line. With both sides+ // expressed as pixel coordinates we can interpolate either direction with+ // a single piecewise-linear map.++ // Cache: rebuilding the mirror is moderately expensive, so cache by+ // (markdown content, textarea inner width). Both invalidate the cache.+ const editorYCacheRef = useRef<{+ signature: string;+ ys: Map<number, number>;+ } | null>(null);++ const measureEditorLineYs = useCallback((): Map<number, number> => {+ const editor = textareaRef.current;+ if (!editor) return new Map();+ const value = editor.value;+ const sourceLines = value.split("\n");+ if (sourceLines.length === 0) return new Map();++ const computed = window.getComputedStyle(editor);+ const rect = editor.getBoundingClientRect();+ const mirror = document.createElement("div");++ const properties = [+ "box-sizing",+ "width",+ "border-top-width",+ "border-right-width",+ "border-bottom-width",+ "border-left-width",+ "padding-top",+ "padding-right",+ "padding-bottom",+ "padding-left",+ "font-style",+ "font-variant",+ "font-weight",+ "font-stretch",+ "font-size",+ "font-size-adjust",+ "line-height",+ "font-family",+ "letter-spacing",+ "text-align",+ "text-transform",+ "text-indent",+ "tab-size",+ ];+ for (const property of properties) {+ mirror.style.setProperty(property, computed.getPropertyValue(property));+ }++ mirror.style.position = "fixed";+ mirror.style.top = `${rect.top}px`;+ mirror.style.left = `${rect.left}px`;+ mirror.style.height = "auto";+ mirror.style.maxHeight = "none";+ mirror.style.minHeight = "0";+ mirror.style.whiteSpace = "pre-wrap";+ mirror.style.overflowWrap = "break-word";+ mirror.style.wordBreak = "normal";+ mirror.style.visibility = "hidden";+ mirror.style.pointerEvents = "none";+ mirror.style.zIndex = "-1";++ const spans: HTMLSpanElement[] = [];+ for (let i = 0; i < sourceLines.length; i += 1) {+ if (i > 0) mirror.appendChild(document.createTextNode("\n"));+ const span = document.createElement("span");+ // Empty lines need measurable content for offsetTop to be meaningful.+ span.textContent =+ sourceLines[i].length > 0 ? sourceLines[i] : "\u200B";+ mirror.appendChild(span);+ spans.push(span);+ }++ document.body.appendChild(mirror);++ const result = new Map<number, number>();+ // span.offsetTop is the y-position of the line within the mirror, which+ // mirrors the textarea's scroll content. Setting `editor.scrollTop` to+ // this value lifts that source line to the top of the visible viewport.+ for (let i = 0; i < spans.length; i += 1) {+ result.set(i + 1, spans[i].offsetTop);+ }++ document.body.removeChild(mirror);+ return result;+ }, []);++ const getEditorLineYs = useCallback((): Map<number, number> => {+ const editor = textareaRef.current;+ if (!editor) return new Map();+ const signature = `${editor.clientWidth}|${markdown}`;+ const cached = editorYCacheRef.current;+ if (cached && cached.signature === signature) return cached.ys;+ const ys = measureEditorLineYs();+ editorYCacheRef.current = { signature, ys };+ return ys;+ }, [markdown, measureEditorLineYs]);++ const collectPreviewLineYs = useCallback((): Map<number, number> => {+ const preview = previewScrollRef.current;+ if (!preview) return new Map();+ const nodes = preview.querySelectorAll<HTMLElement>("[data-source-line]");+ if (nodes.length === 0) return new Map();+ const previewRect = preview.getBoundingClientRect();+ const baseTop = previewRect.top - preview.scrollTop;+ const result = new Map<number, number>();+ for (const el of Array.from(nodes)) {+ const raw = el.getAttribute("data-source-line");+ const line = raw ? Number.parseInt(raw, 10) : NaN;+ if (!Number.isFinite(line)) continue;+ // Keep the first occurrence; nested wrappers often repeat the same line.+ if (result.has(line)) continue;+ const rect = el.getBoundingClientRect();+ result.set(line, rect.top - baseTop);+ }+ return result;+ }, []);++ const buildJointMarkers = useCallback((): Array<{+ line: number;+ editorY: number;+ previewY: number;+ }> => {+ const editorYs = getEditorLineYs();+ const previewYs = collectPreviewLineYs();+ if (editorYs.size === 0 || previewYs.size === 0) return [];++ const lines = Array.from(previewYs.keys())+ .filter((line) => editorYs.has(line))+ .sort((a, b) => a - b);++ const editor = textareaRef.current;+ const preview = previewScrollRef.current;+ const markers: Array<{ line: number; editorY: number; previewY: number }> =+ [];+ for (const line of lines) {+ const editorY = editorYs.get(line);+ const previewY = previewYs.get(line);+ if (typeof editorY !== "number" || typeof previewY !== "number") continue;+ markers.push({ line, editorY, previewY });+ }++ // Anchor the very top so we don't snap to the first heading when the user+ // is still above it.+ if (markers.length === 0 || markers[0].editorY > 0 || markers[0].previewY > 0) {+ markers.unshift({ line: 0, editorY: 0, previewY: 0 });+ }++ // Anchor the bottom so the bottom of the document matches.+ if (editor && preview) {+ const editorMax = Math.max(0, editor.scrollHeight - editor.clientHeight);+ const previewMax = Math.max(0, preview.scrollHeight - preview.clientHeight);+ const last = markers[markers.length - 1];+ if (+ editorMax > last.editorY + 1 ||+ previewMax > last.previewY + 1+ ) {+ markers.push({+ line: last.line + 1,+ editorY: editorMax,+ previewY: previewMax,+ });+ }+ }++ return markers;+ }, [collectPreviewLineYs, getEditorLineYs]);++ const interpolate = (+ value: number,+ fromA: number,+ fromB: number,+ toA: number,+ toB: number,+ ): number => {+ if (fromA === fromB) return toA;+ const ratio = (value - fromA) / (fromB - fromA);+ return toA + (toB - toA) * ratio;+ };++ const handleEditorScrollSync = useCallback(() => {+ updateSelectionPopover();+ if (!syncScrollEnabled) return;+ if (scrollSyncSourceRef.current === "preview") return;+ const editor = textareaRef.current;+ const preview = previewScrollRef.current;+ if (!editor || !preview) return;+ const markers = buildJointMarkers();+ if (markers.length === 0) return;++ const editorScroll = editor.scrollTop;+ let lower = markers[0];+ let upper = markers[markers.length - 1];+ for (const marker of markers) {+ if (marker.editorY <= editorScroll) lower = marker;+ if (marker.editorY >= editorScroll) {+ upper = marker;+ break;+ }+ }++ const target = interpolate(+ editorScroll,+ lower.editorY,+ upper.editorY,+ lower.previewY,+ upper.previewY,+ );++ const max = preview.scrollHeight - preview.clientHeight;+ const next = Math.max(0, Math.min(max, target));+ if (Math.abs(next - preview.scrollTop) < 0.5) return;+ scrollSyncSourceRef.current = "editor";+ preview.scrollTop = next;+ releaseScrollSyncSource();+ }, [+ buildJointMarkers,+ releaseScrollSyncSource,+ syncScrollEnabled,+ updateSelectionPopover,+ ]);++ const handlePreviewScrollSync = useCallback(() => {+ if (!syncScrollEnabled) return;+ if (scrollSyncSourceRef.current === "editor") return;+ const editor = textareaRef.current;+ const preview = previewScrollRef.current;+ if (!editor || !preview) return;+ const markers = buildJointMarkers();+ if (markers.length === 0) return;++ const previewScroll = preview.scrollTop;+ let lower = markers[0];+ let upper = markers[markers.length - 1];+ for (const marker of markers) {+ if (marker.previewY <= previewScroll) lower = marker;+ if (marker.previewY >= previewScroll) {+ upper = marker;+ break;+ }+ }++ const target = interpolate(+ previewScroll,+ lower.previewY,+ upper.previewY,+ lower.editorY,+ upper.editorY,+ );++ const max = editor.scrollHeight - editor.clientHeight;+ const next = Math.max(0, Math.min(max, target));+ if (Math.abs(next - editor.scrollTop) < 0.5) return;+ scrollSyncSourceRef.current = "preview";+ editor.scrollTop = next;+ releaseScrollSyncSource();+ }, [buildJointMarkers, releaseScrollSyncSource, syncScrollEnabled]);++ // Mermaid diagrams, images, and KaTeX render asynchronously, so the preview's+ // scrollHeight (and the y position of every marker after them) shifts well+ // after the initial render. Without intervention, the user's last alignment+ // becomes stale and the next scroll feels "jumpy" because all the markers+ // moved underneath them. Whenever the preview's intrinsic height changes we+ // re-run the editor→preview sync to put the preview back in lock-step with+ // the editor's current scroll position.+ const handleEditorScrollSyncRef = useRef(handleEditorScrollSync);+ useEffect(() => {+ handleEditorScrollSyncRef.current = handleEditorScrollSync;+ }, [handleEditorScrollSync]);++ useEffect(() => {+ const preview = previewScrollRef.current;+ if (!preview) return;+ const inner = preview.firstElementChild as HTMLElement | null;+ if (!inner) return;++ let raf = 0;+ const schedule = () => {+ if (raf) cancelAnimationFrame(raf);+ raf = requestAnimationFrame(() => {+ raf = 0;+ // Treat this as an editor-driven update; we want preview to follow+ // wherever the editor cursor currently anchors us, not the other way+ // around (which would feed back into editor scroll).+ if (scrollSyncSourceRef.current) return;+ handleEditorScrollSyncRef.current();+ });+ };++ const observer = new ResizeObserver(schedule);+ observer.observe(inner);++ // Images load asynchronously and don't always trigger a ResizeObserver+ // update on the parent, so we listen to load events directly too.+ const onLoad = (event: Event) => {+ const target = event.target as HTMLElement | null;+ if (!target) return;+ if (target.tagName === "IMG" || target.tagName === "IFRAME") schedule();+ };+ inner.addEventListener("load", onLoad, true);++ return () => {+ if (raf) cancelAnimationFrame(raf);+ observer.disconnect();+ inner.removeEventListener("load", onLoad, true);+ };+ }, [showPreview]);++ if (docNotFound) {+ return (+ <div className="flex h-full min-h-full flex-col items-center justify-center gap-4 bg-[var(--background)] p-10 text-center">+ <p className="text-lg font-medium text-[var(--foreground)]">+ {t("Document not found")}+ </p>+ <p className="text-sm text-[var(--muted-foreground)]">+ {t(+ "This document may have been deleted, or the link is incorrect.",+ )}+ </p>+ <button+ type="button"+ onClick={() => router.push("/co-writer")}+ className="inline-flex items-center gap-1.5 rounded-md bg-[var(--primary)] px-3 py-1.5 text-sm font-medium text-white transition-opacity hover:opacity-90"+ >+ <ChevronLeft size={14} />+ {t("Back to Co-Writer")}+ </button>+ </div>+ );+ }++ if (isLoadingDoc && !hasLoadedDraft) {+ return (+ <div className="flex h-full min-h-full flex-col items-center justify-center gap-3 bg-[var(--background)] p-10 text-center text-[var(--muted-foreground)]">+ <Loader2 size={20} className="animate-spin" />+ <span className="text-sm">{t("Loading document…")}</span>+ </div>+ );+ }++ return (+ <div className="flex h-full min-h-full flex-col overflow-hidden bg-[var(--background)]">+ {/* ── Top bar ── */}+ <header className="flex shrink-0 items-center justify-between border-b border-[var(--border)] px-4 py-1.5">+ <div className="flex min-w-0 items-center gap-3 text-sm text-[var(--muted-foreground)]">+ <button+ type="button"+ onClick={() => router.push("/co-writer")}+ className="inline-flex shrink-0 items-center gap-1 rounded-md px-1.5 py-0.5 text-xs font-medium text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"+ title={t("Back to documents")}+ >+ <ChevronLeft size={14} strokeWidth={1.7} />+ <span>{t("Co-Writer")}</span>+ </button>+ <span className="text-[var(--muted-foreground)]/40">/</span>+ {isEditingTitle ? (+ <input+ ref={titleInputRef}+ value={titleDraft}+ onChange={(event) => setTitleDraft(event.target.value)}+ onBlur={() => {+ void commitTitle();+ }}+ onKeyDown={(event) => {+ if (event.key === "Enter") {+ event.preventDefault();+ void commitTitle();+ } else if (event.key === "Escape") {+ event.preventDefault();+ cancelEditingTitle();+ }+ }}+ maxLength={120}+ spellCheck={false}+ placeholder={t("Untitled draft")}+ aria-label={t("Document title")}+ className="min-w-0 flex-1 max-w-[24rem] rounded-md border border-[var(--primary)]/40 bg-[var(--background)] px-2 py-0.5 font-medium text-[var(--foreground)] outline-none focus:border-[var(--primary)] focus:ring-1 focus:ring-[var(--primary)]/30"+ />+ ) : (+ <span+ role="button"+ tabIndex={0}+ onDoubleClick={startEditingTitle}+ onKeyDown={(event) => {+ if (event.key === "Enter" || event.key === "F2") {+ event.preventDefault();+ startEditingTitle();+ }+ }}+ title={t("Double-click to rename")}+ className="min-w-0 truncate cursor-text rounded-md border border-transparent px-2 py-0.5 font-medium text-[var(--foreground)] transition-colors hover:bg-[var(--muted)]/60 focus:outline-none focus:ring-1 focus:ring-[var(--primary)]/30"+ >+ {docTitle || t("Untitled draft")}+ </span>+ )}+ <span className="hidden text-xs sm:inline">+ {wordCount} {t("words")} · {charCount} {t("chars")}+ </span>+ {isSavingDoc ? (+ <span className="hidden items-center gap-1 text-[10px] text-[var(--muted-foreground)]/70 sm:inline-flex">+ <Loader2 size={10} className="animate-spin" />+ {t("Saving…")}+ </span>+ ) : lastSavedAt ? (+ <span className="hidden text-[10px] text-[var(--muted-foreground)]/60 sm:inline">+ {t("Saved")}+ </span>+ ) : null}+ </div>+ <div className="flex items-center gap-2">+ <ToolbarIconBtn+ title={t("Clear")}+ onClick={clearDocument}+ >+ <Eraser size={17} strokeWidth={1.7} />+ </ToolbarIconBtn>+ <ToolbarIconBtn+ title={t("Export Markdown")}+ onClick={handleDownload}+ >+ <Download size={17} strokeWidth={1.7} />+ </ToolbarIconBtn>+ <ToolbarIconBtn+ title={t("Load Example Template")}+ onClick={loadExampleTemplate}+ >+ <FileText size={17} strokeWidth={1.7} />+ </ToolbarIconBtn>+ <a+ href="https://litewrite.ai/"+ target="_blank"+ rel="noreferrer"+ className="inline-flex items-center gap-1 rounded-full border border-[var(--border)] px-2.5 py-1 text-[11px] font-medium text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"+ >+ <span>{t("Pro Vide Writing")}</span>+ <ArrowUpRight size={12} strokeWidth={1.8} aria-hidden="true" />+ </a>+ <div className="mx-1 h-5 w-px bg-[var(--border)]" />+ <button+ onClick={() => setIsEditModalOpen(true)}+ className="inline-flex items-center gap-1.5 rounded-md bg-[var(--primary)] px-3 py-1 text-xs font-medium text-white transition-opacity hover:opacity-90"+ >+ <WandSparkles size={13} />+ {t("Full Draft")}+ </button>+ </div>+ </header>++ {/* ── Toolbar ── */}+ <div className="flex shrink-0 items-center gap-0.5 overflow-x-auto border-b border-[var(--border)] px-3 py-1">+ {TOOLBAR.map((item) => {+ if (item.type === "separator") {+ return (+ <div+ key={item.id}+ className="mx-1 h-4 w-px shrink-0 bg-[var(--border)]"+ />+ );+ }+ const Icon = item.icon;+ return (+ <button+ key={item.id}+ title={t(item.title)}+ onClick={() =>+ item.action ? item.action() : insertSnippet(item.snippet || "")+ }+ className="shrink-0 rounded p-1.5 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"+ >+ <Icon size={16} />+ </button>+ );+ })}++ <div className="ml-auto flex shrink-0 items-center gap-1.5 pl-3 text-[10px] text-[var(--muted-foreground)]">+ <button+ type="button"+ onClick={() => setSyncScrollEnabled((prev) => !prev)}+ disabled={!showEditor || !showPreview}+ title={+ syncScrollEnabled+ ? t("Scroll sync is on. Click to disable.")+ : t("Scroll sync is off. Click to enable.")+ }+ className={`inline-flex items-center gap-1 rounded border px-1.5 py-0.5 text-[10px] font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-40 ${+ syncScrollEnabled+ ? "border-[var(--primary)]/40 bg-[var(--primary)]/10 text-[var(--primary)]"+ : "border-[var(--border)] bg-transparent text-[var(--muted-foreground)] hover:bg-[var(--muted)]"+ }`}+ >+ <span+ aria-hidden="true"+ className={`inline-block h-1.5 w-1.5 rounded-full ${+ syncScrollEnabled ? "bg-[var(--primary)]" : "bg-[var(--muted-foreground)]/60"+ }`}+ />+ {t("Sync Scroll")}+ </button>+ <span className="mx-0.5 h-3 w-px bg-[var(--border)]" aria-hidden="true" />+ <span className="rounded bg-[var(--muted)] px-1.5 py-0.5">GFM</span>+ <span className="rounded bg-[var(--muted)] px-1.5 py-0.5">+ KaTeX+ </span>+ <span className="rounded bg-[var(--muted)] px-1.5 py-0.5">+ Mermaid+ </span>+ </div>+ </div>++ {/* ── Editor + Preview ── */}+ <div+ ref={splitContainerRef}+ className={`relative flex min-h-0 flex-1 ${+ isResizingSplit ? "select-none" : ""+ }`}+ >+ {/* Editor panel */}+ {showEditor && (+ <div+ className="flex min-h-0 flex-col"+ style={{+ width: showPreview ? `${editorRatio * 100}%` : "100%",+ }}+ >+ <div className="flex shrink-0 items-center justify-between border-b border-[var(--border)] px-3 py-1">+ <span className="text-xs font-medium text-[var(--muted-foreground)]">+ {t("Editor")}+ </span>+ <button+ title={t("Collapse editor")}+ onClick={() => setEditorCollapsed(true)}+ className="rounded p-0.5 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"+ >+ <ChevronLeft size={14} />+ </button>+ </div>+ <textarea+ ref={textareaRef}+ value={markdown}+ onChange={(e) => handleMarkdownChange(e.target.value)}+ onSelect={updateSelectionPopover}+ onKeyUp={updateSelectionPopover}+ onMouseUp={updateSelectionPopover}+ onScroll={handleEditorScrollSync}+ spellCheck={false}+ className="min-h-0 flex-1 resize-none bg-transparent p-4 font-mono text-[13px] leading-relaxed text-[var(--foreground)] outline-none placeholder:text-[var(--muted-foreground)]"+ placeholder={t("Start writing in Markdown...")}+ />+ </div>+ )}++ {/* Draggable splitter (only when both panes are visible) */}+ {showEditor && showPreview && (+ <div+ role="separator"+ aria-orientation="vertical"+ aria-label={t("Resize editor and preview")}+ onPointerDown={handleSplitterPointerDown}+ onDoubleClick={() => setEditorRatio(0.5)}+ className={`group relative z-10 flex w-1 shrink-0 cursor-col-resize items-stretch border-x border-[var(--border)] transition-colors ${+ isResizingSplit+ ? "bg-[var(--primary)]/40"+ : "bg-transparent hover:bg-[var(--primary)]/30"+ }`}+ title={t("Drag to resize, double-click to reset")}+ >+ {/* Wider invisible hit-area so the handle is easy to grab */}+ <div className="absolute inset-y-0 -left-1.5 -right-1.5" />+ <div+ className={`pointer-events-none absolute left-1/2 top-1/2 h-10 w-[3px] -translate-x-1/2 -translate-y-1/2 rounded-full transition-opacity ${+ isResizingSplit+ ? "bg-[var(--primary)] opacity-100"+ : "bg-[var(--muted-foreground)]/40 opacity-0 group-hover:opacity-100"+ }`}+ />+ </div>+ )}++ {/* Collapse gutter / expand buttons */}+ {editorCollapsed && (+ <button+ onClick={() => setEditorCollapsed(false)}+ title={t("Expand editor")}+ className="flex w-7 shrink-0 items-center justify-center border-r border-[var(--border)] text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"+ >+ <ChevronRight size={14} />+ </button>+ )}++ {previewCollapsed && (+ <button+ onClick={() => setPreviewCollapsed(false)}+ title={t("Expand preview")}+ className="flex w-7 shrink-0 items-center justify-center border-l border-[var(--border)] text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"+ >+ <ChevronLeft size={14} />+ </button>+ )}++ {/* Preview panel */}+ {showPreview && (+ <div+ className="flex min-h-0 flex-col"+ style={{+ width: showEditor ? `${(1 - editorRatio) * 100}%` : "100%",+ }}+ >+ <div className="flex shrink-0 items-center justify-between border-b border-[var(--border)] px-3 py-1">+ <span className="text-xs font-medium text-[var(--muted-foreground)]">+ {t("Preview")}+ </span>+ <button+ title={t("Collapse preview")}+ onClick={() => setPreviewCollapsed(true)}+ className="rounded p-0.5 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"+ >+ <ChevronRight size={14} />+ </button>+ </div>+ <div+ ref={previewScrollRef}+ onScroll={handlePreviewScrollSync}+ className="min-h-0 flex-1 overflow-y-auto p-5"+ >+ <MarkdownRenderer+ content={markdown || `_${t("Nothing to preview yet.")}_`}+ variant="prose"+ trackSourceLines+ />+ </div>+ </div>+ )}+ </div>++ {selectionPopover.visible && selectedRange && (+ <div+ ref={selectionPopoverRef}+ onMouseDown={handleSelectionPopoverDragStart}+ className={`fixed z-50 rounded-2xl border border-[var(--border)] bg-[var(--card)] p-2.5 shadow-2xl ${+ isDraggingSelectionPopover ? "cursor-grabbing" : "cursor-grab"+ }`}+ style={{+ top: selectionPopover.top,+ left: selectionPopover.left,+ width: 360,+ }}+ >+ <div className="mb-2 flex justify-center" aria-hidden="true">+ <div className="h-1 w-10 rounded-full bg-[var(--border)]/80" />+ </div>++ <div className="relative">+ <input+ value={selectionInstruction}+ onChange={(e) => setSelectionInstruction(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ e.preventDefault();+ void applyReactSelectionEdit();+ }+ }}+ className="h-10 w-full rounded-xl bg-transparent pl-3 pr-10 text-[13px] text-[var(--foreground)] outline-none placeholder:text-[var(--muted-foreground)]"+ placeholder={t("Tell AI what to do with the selection...")}+ />+ <button+ onClick={() => void applyReactSelectionEdit()}+ disabled={isEditing || isAutoMarking}+ className="absolute right-1.5 top-1.5 inline-flex h-7 w-7 items-center justify-center rounded-full bg-[var(--primary)] text-white transition-opacity disabled:opacity-45"+ title={t("Apply AI edit")}+ >+ {isEditing ? (+ <Loader2 size={13} className="animate-spin" />+ ) : (+ <ArrowRight size={13} />+ )}+ </button>+ </div>++ <div className="mt-2 grid grid-cols-2 gap-2">+ <div className="relative">+ <button+ onClick={() => {+ setIsToolMenuOpen((prev) => !prev);+ setIsModeMenuOpen(false);+ }}+ className="flex h-9 w-full items-center justify-between rounded-xl border border-[var(--border)] px-3 text-[12px] text-[var(--foreground)] transition-colors hover:bg-[var(--muted)]"+ >+ <span className="truncate">+ {selectionTools.length === 0+ ? t("Tools")+ : selectionTools.length === 1+ ? t(TOOL_OPTIONS.find((item) => item.name === selectionTools[0])+ ?.label || "Tools")+ : t("{{count}} tools", { count: selectionTools.length })}+ </span>+ <ChevronDown+ size={13}+ className={`shrink-0 transition-transform ${isToolMenuOpen ? "rotate-180" : ""}`}+ />+ </button>+ {isToolMenuOpen && (+ <div className="absolute left-0 top-full z-20 mt-1 w-full rounded-xl border border-[var(--border)] bg-[var(--card)] p-1 shadow-xl">+ {TOOL_OPTIONS.map((tool) => {+ const active = selectionTools.includes(tool.name);+ return (+ <button+ key={tool.name}+ onClick={() => toggleSelectionTool(tool.name)}+ className="flex w-full items-center justify-between rounded-lg px-2.5 py-2 text-left text-[12px] text-[var(--foreground)] transition-colors hover:bg-[var(--muted)]"+ >+ <span>{t(tool.label)}</span>+ {active ? <Check size={12} /> : <span className="w-3" />}+ </button>+ );+ })}+ </div>+ )}+ </div>++ <div className="relative">+ <button+ onClick={() => {+ setIsModeMenuOpen((prev) => !prev);+ setIsToolMenuOpen(false);+ }}+ className="flex h-9 w-full items-center justify-between rounded-xl border border-[var(--border)] px-3 text-[12px] text-[var(--foreground)] transition-colors hover:bg-[var(--muted)]"+ >+ <span>+ {t(MODE_OPTIONS.find((item) => item.value === selectionMode)?.label ||+ "Mode")}+ </span>+ <ChevronDown+ size={13}+ className={`shrink-0 transition-transform ${isModeMenuOpen ? "rotate-180" : ""}`}+ />+ </button>+ {isModeMenuOpen && (+ <div className="absolute left-0 top-full z-20 mt-1 w-full rounded-xl border border-[var(--border)] bg-[var(--card)] p-1 shadow-xl">+ {MODE_OPTIONS.map((mode) => (+ <button+ key={mode.value}+ onClick={() => {+ setSelectionMode(mode.value);+ setIsModeMenuOpen(false);+ }}+ className="flex w-full items-center justify-between rounded-lg px-2.5 py-2 text-left text-[12px] text-[var(--foreground)] transition-colors hover:bg-[var(--muted)]"+ >+ <span>{t(mode.label)}</span>+ {selectionMode === mode.value ? (+ <Check size={12} />+ ) : (+ <span className="w-3" />+ )}+ </button>+ ))}+ </div>+ )}+ </div>+ </div>++ {(isEditing || selectionTrace) && (+ <div className="mt-2 rounded-xl border border-[var(--border)]/70 bg-[var(--muted)]/18">+ <button+ onClick={() => setIsTraceExpanded((prev) => !prev)}+ className="flex w-full items-center gap-2 px-3 py-2 text-left text-[12px] text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"+ >+ <ChevronDown+ size={12}+ className={`shrink-0 transition-transform ${isTraceExpanded ? "rotate-180" : ""}`}+ />+ <span className="font-medium text-[var(--foreground)]">+ {t("Trace")}+ </span>+ {isEditing ? (+ <Loader2 size={12} className="ml-auto animate-spin" />+ ) : null}+ </button>++ {isTraceExpanded && (+ <div+ data-no-drag="true"+ className="max-h-[280px] overflow-y-auto border-t border-[var(--border)]/60 px-3 py-2 text-[12px] leading-[1.7] text-[var(--muted-foreground)]"+ >+ {selectionTrace?.thinking ? (+ <div className="space-y-1.5">+ <div className="text-[11px] font-medium uppercase tracking-[0.08em] text-[var(--muted-foreground)]/60">+ {t("Thought")}+ </div>+ <MarkdownRenderer+ content={selectionTrace.thinking}+ variant="trace"+ />+ </div>+ ) : isEditing ? (+ <div className="opacity-70">{t("Thinking...")}</div>+ ) : null}++ {selectionTrace && selectionTrace.toolTraces.length > 0 && (+ <div className="mt-3 space-y-1.5">+ <div className="text-[11px] font-medium uppercase tracking-[0.08em] text-[var(--muted-foreground)]/60">+ {t("Tool")}+ </div>+ <div className="space-y-2">+ {selectionTrace.toolTraces.map((trace, index) => (+ <div key={`${trace.name}-${index}`} className="space-y-1">+ <div>+ <span className="opacity-50">+ {trace.kind === "tool_result" ? "✓ " : "→ "}+ </span>+ <span className="text-[var(--foreground)]">+ {trace.name}+ </span>+ </div>+ {trace.arguments &&+ Object.keys(trace.arguments).length > 0 ? (+ <pre className="ml-3 whitespace-pre-wrap break-words rounded-md bg-[var(--muted)]/45 px-2 py-1 font-mono text-[11px] leading-[1.55] text-[var(--muted-foreground)]/78">+ {JSON.stringify(trace.arguments, null, 2)}+ </pre>+ ) : null}+ {trace.result ? (+ <div className="ml-3">+ <MarkdownRenderer+ content={trace.result}+ variant="trace"+ />+ </div>+ ) : null}+ </div>+ ))}+ </div>+ </div>+ )}++ {selectionTrace?.response ? (+ <div className="mt-3 space-y-1.5">+ <div className="text-[11px] font-medium uppercase tracking-[0.08em] text-[var(--muted-foreground)]/60">+ {t("Response")}+ </div>+ <MarkdownRenderer+ content={selectionTrace.response}+ variant="trace"+ />+ </div>+ ) : null}++ {isEditing &&+ selectionTrace &&+ !selectionTrace.thinking &&+ selectionTrace.toolTraces.length === 0 &&+ !selectionTrace.response ? (+ <div className="mt-2 opacity-70">+ {t("Running tools and preparing the final edit...")}+ </div>+ ) : null}+ </div>+ )}+ </div>+ )}+ </div>+ )}++ {/* ── Status bar ── */}+ {(error || status) && (+ <div+ className={`shrink-0 border-t px-4 py-1.5 text-xs ${+ error+ ? "border-red-200 bg-red-50 text-red-600 dark:border-red-900 dark:bg-red-950/30 dark:text-red-400"+ : "border-emerald-200 bg-emerald-50 text-emerald-600 dark:border-emerald-900 dark:bg-emerald-950/30 dark:text-emerald-400"+ }`}+ >+ {error || status}+ </div>+ )}++ {/* ── AI Edit modal ── */}+ {isEditModalOpen && (+ <div+ className="fixed inset-0 z-50 flex items-center justify-center bg-black/30 backdrop-blur-sm"+ onClick={(e) => {+ if (e.target === e.currentTarget) setIsEditModalOpen(false);+ }}+ >+ <div className="w-full max-w-md rounded-xl border border-[var(--border)] bg-[var(--card)] shadow-xl">+ <div className="flex items-center justify-between border-b border-[var(--border)] px-4 py-3">+ <h2 className="text-sm font-semibold text-[var(--foreground)]">+ {t("Full Draft AI Edit")}+ </h2>+ <button+ onClick={() => setIsEditModalOpen(false)}+ className="text-xs text-[var(--muted-foreground)] hover:text-[var(--foreground)]"+ >+ {t("Close")}+ </button>+ </div>++ <div className="space-y-3 px-4 py-4">+ <div className="flex gap-1.5">+ {(Object.keys(ACTION_LABELS) as EditAction[]).map((a) => (+ <button+ key={a}+ onClick={() => setAction(a)}+ className={`rounded-md px-3 py-1.5 text-xs transition-colors ${+ action === a+ ? "bg-[var(--primary)] text-white"+ : "border border-[var(--border)] text-[var(--foreground)] hover:bg-[var(--muted)]"+ }`}+ >+ {t(ACTION_LABELS[a])}+ </button>+ ))}+ </div>++ <textarea+ value={instruction}+ onChange={(e) => setInstruction(e.target.value)}+ rows={4}+ className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-sm text-[var(--foreground)] outline-none focus:border-[var(--primary)]"+ placeholder={t("Describe how you want the text edited...")}+ />++ <div className="grid grid-cols-2 gap-3">+ <div>+ <label className="mb-1 block text-[10px] font-medium uppercase tracking-wider text-[var(--muted-foreground)]">+ {t("Source")}+ </label>+ <select+ value={source}+ onChange={(e) =>+ setSource(e.target.value as SourceOption)+ }+ className="w-full rounded-md border border-[var(--border)] bg-[var(--background)] px-2 py-1.5 text-xs text-[var(--foreground)] outline-none focus:border-[var(--primary)]"+ >+ <option value="none">{t("None")}</option>+ <option value="rag">{t("Knowledge Base")}</option>+ <option value="web">{t("Web Search")}</option>+ </select>+ </div>+ <div>+ <label className="mb-1 block text-[10px] font-medium uppercase tracking-wider text-[var(--muted-foreground)]">+ {t("Knowledge Base")}+ </label>+ <select+ value={kbName}+ onChange={(e) => setKbName(e.target.value)}+ disabled={source !== "rag"}+ className="w-full rounded-md border border-[var(--border)] bg-[var(--background)] px-2 py-1.5 text-xs text-[var(--foreground)] outline-none focus:border-[var(--primary)] disabled:cursor-not-allowed disabled:opacity-40"+ >+ <option value="">{t("Select...")}</option>+ {knowledgeBases.map((k) => (+ <option key={k.name} value={k.name}>+ {k.name}+ </option>+ ))}+ </select>+ </div>+ </div>+ </div>++ <div className="flex justify-end gap-2 border-t border-[var(--border)] px-4 py-3">+ <button+ onClick={applyAutoMark}+ disabled={isEditing || isAutoMarking}+ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] px-3 py-1.5 text-xs font-medium text-[var(--foreground)] transition-colors hover:bg-[var(--muted)] disabled:opacity-50"+ >+ {isAutoMarking ? (+ <Loader2 size={13} className="animate-spin" />+ ) : (+ <Highlighter size={13} />+ )}+ {t("Auto Mark")}+ </button>+ <button+ onClick={applyEdit}+ disabled={isEditing || isAutoMarking}+ className="inline-flex items-center gap-1.5 rounded-md bg-[var(--primary)] px-3 py-1.5 text-xs font-medium text-white transition-opacity disabled:opacity-50"+ >+ {isEditing ? (+ <Loader2 size={13} className="animate-spin" />+ ) : (+ <ArrowRight size={13} />+ )}+ {t("Apply")}+ </button>+ </div>+ </div>+ </div>+ )}++ </div>+ );+}++function ToolbarIconBtn({+ title,+ onClick,+ children,+}: {+ title: string;+ onClick: () => void;+ children: React.ReactNode;+}) {+ return (+ <button+ title={title}+ onClick={onClick}+ className="inline-flex h-8 w-8 items-center justify-center rounded-md text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"+ >+ {children}+ </button>+ );+}diff --git a/web/app/(workspace)/co-writer/page.tsx b/web/app/(workspace)/co-writer/page.tsxindex 506402f15..b7e14e20e 100644--- a/web/app/(workspace)/co-writer/page.tsx+++ b/web/app/(workspace)/co-writer/page.tsx@@ -1,1945 +1,266 @@"use client";-import dynamic from "next/dynamic";-import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useCallback, useEffect, useState } from "react";+import { useRouter } from "next/navigation";import { useTranslation } from "react-i18next";import {- ArrowRight,- ArrowUpRight,- Bold,- BookPlus,- Braces,- Check,- ChevronDown,- ChevronLeft,- ChevronRight,- Code2,- Download,- Eraser,FileText,- Heading1,- Heading2,- Heading3,- Heading4,- Heading5,- Heading6,- Highlighter,- Image as ImageIcon,- Italic,- Link as LinkIcon,- List,- ListOrdered,- ListTodo,Loader2,- Minus,- Quote,- Redo2,- Strikethrough,- Table2,- Undo2,- WandSparkles,- Workflow,+ PenLine,+ Plus,+ Trash2,} from "lucide-react";-import { apiUrl } from "@/lib/api";-import { listKnowledgeBases } from "@/lib/knowledge-api";+import {+ createCoWriterDocument,+ deleteCoWriterDocument,+ listCoWriterDocuments,+ type CoWriterDocumentSummary,+} from "@/lib/co-writer-api";+import { notifyCoWriterChanged } from "@/lib/co-writer-events";import { CO_WRITER_SAMPLE_TEMPLATE } from "./sampleTemplate";-const MarkdownRenderer = dynamic(() => import("@/components/common/MarkdownRenderer"), {- ssr: false,-});-const SaveToNotebookModal = dynamic(() => import("@/components/notebook/SaveToNotebookModal"), {- ssr: false,-});--type EditAction = "rewrite" | "shorten" | "expand";-type SelectionMode = EditAction | "none";-type SourceOption = "none" | "rag" | "web";-type ToolName =- | "brainstorm"- | "rag"- | "web_search"- | "code_execution"- | "reason"- | "paper_search";--interface KnowledgeBase {- name: string;- is_default?: boolean;-}--const STORAGE_KEY = "deeptutor.co_writer.draft";-const HISTORY_KEY = "deeptutor.co_writer.history";-const SPLIT_RATIO_KEY = "deeptutor.co_writer.split_ratio";-const SYNC_SCROLL_KEY = "deeptutor.co_writer.sync_scroll";-const MIN_PANEL_RATIO = 0.18;-const MAX_PANEL_RATIO = 0.82;--const ACTION_LABELS: Record<EditAction, string> = {- rewrite: "Rewrite",- shorten: "Shorten",- expand: "Expand",-};--const TOOL_OPTIONS: Array<{ name: ToolName; label: string }> = [- { name: "brainstorm", label: "Brainstorm" },- { name: "rag", label: "RAG" },- { name: "web_search", label: "Web Search" },- { name: "code_execution", label: "Code" },- { name: "reason", label: "Reason" },- { name: "paper_search", label: "Arxiv Search" },-];--const MODE_OPTIONS: Array<{ value: SelectionMode; label: string }> = [- { value: "none", label: "None" },- { value: "shorten", label: "Shorten" },- { value: "expand", label: "Expand" },- { value: "rewrite", label: "Rewrite" },-];--interface ToolbarItem {- id: string;- icon: React.ComponentType<{ size?: number; className?: string }>;- title: string;- snippet?: string;- type?: "separator";- action?: () => void;-}--interface SelectedRange {- start: number;- end: number;- text: string;- snapshot: string;-}--interface SelectionPopoverState {- visible: boolean;- top: number;- left: number;-}--interface SelectionToolTrace {- kind?: "tool_call" | "tool_result";- name: string;- arguments: Record<string, unknown>;- result: string;- success: boolean;- sources: Array<Record<string, unknown>>;- metadata: Record<string, unknown>;-}--interface SelectionTraceData {- thinking: string;- toolTraces: SelectionToolTrace[];- response: string;-}--interface StreamTraceEvent {- type: string;- stage?: string;- content?: string;- metadata?: Record<string, unknown>;+function relativeTime(seconds: number): string {+ if (!seconds || Number.isNaN(seconds)) return "";+ const diff = Date.now() / 1000 - seconds;+ if (diff < 60) return "just now";+ const mins = Math.floor(diff / 60);+ if (mins < 60) return `${mins}m`;+ const hrs = Math.floor(mins / 60);+ if (hrs < 24) return `${hrs}h`;+ const days = Math.floor(hrs / 24);+ if (days < 30) return `${days}d`;+ const months = Math.floor(days / 30);+ if (months < 12) return `${months}mo`;+ return `${Math.floor(months / 12)}y`;}-interface StreamEditResult {- edited_text?: string;-}--export default function CoWriterPage() {+export default function CoWriterHomePage() {+ const router = useRouter();const { t } = useTranslation();- const textareaRef = useRef<HTMLTextAreaElement>(null);- const previewScrollRef = useRef<HTMLDivElement>(null);- const splitContainerRef = useRef<HTMLDivElement>(null);- const scrollSyncSourceRef = useRef<"editor" | "preview" | null>(null);- const scrollSyncResetTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);- const selectionPopoverRef = useRef<HTMLDivElement>(null);- const preserveSelectionTraceRef = useRef(false);- const selectionRequestAbortRef = useRef<AbortController | null>(null);- const selectionDragStateRef = useRef<{ offsetX: number; offsetY: number } | null>(- null,- );- const [markdown, setMarkdown] = useState("");- const [instruction, setInstruction] = useState("");- const [action, setAction] = useState<EditAction>("rewrite");- const [source, setSource] = useState<SourceOption>("none");- const [knowledgeBases, setKnowledgeBases] = useState<KnowledgeBase[]>([]);- const [kbName, setKbName] = useState("");- const [isEditing, setIsEditing] = useState(false);- const [isAutoMarking, setIsAutoMarking] = useState(false);+ const [documents, setDocuments] = useState<CoWriterDocumentSummary[]>([]);+ const [loading, setLoading] = useState(true);+ const [creating, setCreating] = useState(false);+ const [pendingDeleteId, setPendingDeleteId] = useState<string | null>(null);+ const [deletingId, setDeletingId] = useState<string | null>(null);const [error, setError] = useState("");- const [status, setStatus] = useState("");- const [isEditModalOpen, setIsEditModalOpen] = useState(false);- const [selectedRange, setSelectedRange] = useState<SelectedRange | null>(null);- const [selectionPopover, setSelectionPopover] = useState<SelectionPopoverState>({- visible: false,- top: 0,- left: 0,- });- const [selectionInstruction, setSelectionInstruction] = useState("");- const [selectionMode, setSelectionMode] = useState<SelectionMode>("rewrite");- const [selectionTools, setSelectionTools] = useState<ToolName[]>([]);- const [isToolMenuOpen, setIsToolMenuOpen] = useState(false);- const [isModeMenuOpen, setIsModeMenuOpen] = useState(false);- const [selectionTrace, setSelectionTrace] = useState<SelectionTraceData | null>(- null,- );- const [isTraceExpanded, setIsTraceExpanded] = useState(true);- const [selectionPopoverPinned, setSelectionPopoverPinned] = useState(false);- const [isDraggingSelectionPopover, setIsDraggingSelectionPopover] =- useState(false);-- const [editorCollapsed, setEditorCollapsed] = useState(false);- const [previewCollapsed, setPreviewCollapsed] = useState(false);- const [editorRatio, setEditorRatio] = useState(0.5);- const [isResizingSplit, setIsResizingSplit] = useState(false);- const [syncScrollEnabled, setSyncScrollEnabled] = useState(true);- const showEditor = !editorCollapsed;- const showPreview = !previewCollapsed;-- const [showSaveModal, setShowSaveModal] = useState(false);-- const [undoStack, setUndoStack] = useState<string[]>([]);- const [redoStack, setRedoStack] = useState<string[]>([]);- const undoTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);- const [hasLoadedDraft, setHasLoadedDraft] = useState(false);-- useEffect(() => {- const saved = window.localStorage.getItem(STORAGE_KEY);- setMarkdown(saved === null ? CO_WRITER_SAMPLE_TEMPLATE : saved);- setHasLoadedDraft(true);-- const savedRatio = window.localStorage.getItem(SPLIT_RATIO_KEY);- if (savedRatio) {- const parsed = Number.parseFloat(savedRatio);- if (Number.isFinite(parsed)) {- setEditorRatio(- Math.min(MAX_PANEL_RATIO, Math.max(MIN_PANEL_RATIO, parsed)),- );- }- }-- const savedSync = window.localStorage.getItem(SYNC_SCROLL_KEY);- if (savedSync !== null) {- setSyncScrollEnabled(savedSync !== "0");- }- }, []);-- useEffect(() => {- if (!hasLoadedDraft) return;- window.localStorage.setItem(STORAGE_KEY, markdown);- }, [hasLoadedDraft, markdown]);-- useEffect(() => {- window.localStorage.setItem(SPLIT_RATIO_KEY, String(editorRatio));- }, [editorRatio]);-- useEffect(() => {- window.localStorage.setItem(SYNC_SCROLL_KEY, syncScrollEnabled ? "1" : "0");- }, [syncScrollEnabled]);-- useEffect(() => {- // Drop the cached editor line positions when the viewport changes width;- // wrapping behavior depends on it.- const handleResize = () => {- editorYCacheRef.current = null;- };- window.addEventListener("resize", handleResize);- return () => window.removeEventListener("resize", handleResize);- }, []);-- // Editor inner width can change without a window resize (collapsing the- // preview pane, dragging the splitter, etc). Invalidate the y cache so the- // mirror remeasures with the new wrap width.- useEffect(() => {- editorYCacheRef.current = null;- }, [editorRatio, editorCollapsed, previewCollapsed]);-- useEffect(() => {- (async () => {- try {- const list = await listKnowledgeBases();- setKnowledgeBases(list);- const defaultKb =- list.find((k: KnowledgeBase) => k.is_default)?.name ||- list[0]?.name ||- "";- setKbName((prev) => prev || defaultKb);- } catch {- setKnowledgeBases([]);- }- })();- }, []);-- const pushUndo = useCallback(- (prev: string) => {- setUndoStack((s) => [...s.slice(-50), prev]);- setRedoStack([]);- },- [],- );-- const handleMarkdownChange = useCallback(- (value: string) => {- if (undoTimerRef.current) clearTimeout(undoTimerRef.current);- const prev = markdown;- undoTimerRef.current = setTimeout(() => pushUndo(prev), 400);- setMarkdown(value);- },- [markdown, pushUndo],- );-- const handleUndo = useCallback(() => {- if (undoStack.length === 0) return;- const prev = undoStack[undoStack.length - 1];- setRedoStack((s) => [...s, markdown]);- setUndoStack((s) => s.slice(0, -1));- setMarkdown(prev);- }, [undoStack, markdown]);-- const handleRedo = useCallback(() => {- if (redoStack.length === 0) return;- const next = redoStack[redoStack.length - 1];- setUndoStack((s) => [...s, markdown]);- setRedoStack((s) => s.slice(0, -1));- setMarkdown(next);- }, [redoStack, markdown]);-- const wordCount = useMemo(() => {- const trimmed = markdown.trim();- if (!trimmed) return 0;- return trimmed.split(/\s+/).length;- }, [markdown]);-- const charCount = markdown.length;- const notebookSavePayload = useMemo(() => {- const title =- markdown- .split("\n")- .find((line) => line.startsWith("#"))- ?.replace(/^#+\s*/, "")- .trim() || t("Co-Writer Draft");- return {- recordType: "co_writer" as const,- title,- userQuery: "",- output: markdown,- metadata: { source: "co_writer", char_count: markdown.length },- };- }, [markdown]);-- const hideSelectionPopover = useCallback(() => {- selectionRequestAbortRef.current?.abort();- selectionRequestAbortRef.current = null;- selectionDragStateRef.current = null;- setSelectionPopoverPinned(false);- setIsDraggingSelectionPopover(false);- setSelectionPopover((prev) => ({ ...prev, visible: false }));- setSelectedRange(null);- setSelectionInstruction("");- setIsToolMenuOpen(false);- setIsModeMenuOpen(false);- setSelectionTrace(null);- setIsTraceExpanded(true);- }, []);-- const measureSelectionAnchor = useCallback(- (textarea: HTMLTextAreaElement, index: number) => {- const rect = textarea.getBoundingClientRect();- const computed = window.getComputedStyle(textarea);- const mirror = document.createElement("div");- const properties = [- "box-sizing",- "width",- "height",- "overflow-x",- "overflow-y",- "border-top-width",- "border-right-width",- "border-bottom-width",- "border-left-width",- "padding-top",- "padding-right",- "padding-bottom",- "padding-left",- "font-style",- "font-variant",- "font-weight",- "font-stretch",- "font-size",- "font-size-adjust",- "line-height",- "font-family",- "letter-spacing",- "text-align",- "text-transform",- "text-indent",- "text-decoration",- "tab-size",- ];-- properties.forEach((property) => {- mirror.style.setProperty(property, computed.getPropertyValue(property));- });-- mirror.style.position = "fixed";- mirror.style.top = `${rect.top}px`;- mirror.style.left = `${rect.left}px`;- mirror.style.whiteSpace = "pre-wrap";- mirror.style.overflowWrap = "break-word";- mirror.style.visibility = "hidden";- mirror.style.pointerEvents = "none";-- mirror.textContent = textarea.value.slice(0, index);-- const marker = document.createElement("span");- marker.textContent = textarea.value.slice(index) || ".";- mirror.appendChild(marker);-- document.body.appendChild(mirror);-- const top = rect.top + marker.offsetTop - textarea.scrollTop;- const left = rect.left + marker.offsetLeft - textarea.scrollLeft;-- document.body.removeChild(mirror);- return { top, left };- },- [],- );-- const updateSelectionPopover = useCallback(() => {- const textarea = textareaRef.current;- if (!textarea) {- hideSelectionPopover();- return;- }-- const start = textarea.selectionStart;- const end = textarea.selectionEnd;- if (start === end) {- hideSelectionPopover();- return;- }- const text = textarea.value.slice(start, end);- if (!text.trim()) {- hideSelectionPopover();- return;- }-- const anchor = measureSelectionAnchor(textarea, end);- const width = 360;- const left = Math.min(- Math.max(anchor.left - width / 2, 12),- window.innerWidth - width - 12,- );- const top = Math.max(anchor.top - 98, 12);-- setSelectedRange((prev) => {- const changed =- !prev ||- prev.start !== start ||- prev.end !== end ||- prev.text !== text ||- prev.snapshot !== markdown;- if (changed) {- setSelectionPopoverPinned(false);- if (preserveSelectionTraceRef.current) {- preserveSelectionTraceRef.current = false;- } else {- setSelectionTrace(null);- }- setIsTraceExpanded(true);- }- return { start, end, text, snapshot: markdown };- });- setSelectionPopover((prev) => ({- visible: true,- top: selectionPopoverPinned ? prev.top : top,- left: selectionPopoverPinned ? prev.left : left,- }));- }, [- hideSelectionPopover,- markdown,- measureSelectionAnchor,- selectionPopoverPinned,- ]);-- const insertSnippet = useCallback(- (snippet: string) => {- pushUndo(markdown);- const textarea = textareaRef.current;- if (!textarea) {- setMarkdown((prev) => `${prev}\n${snippet}`);- return;- }- const start = textarea.selectionStart;- const end = textarea.selectionEnd;- const next = `${markdown.slice(0, start)}${snippet}${markdown.slice(end)}`;- setMarkdown(next);- requestAnimationFrame(() => {- textarea.focus();- const cursor = start + snippet.length;- textarea.setSelectionRange(cursor, cursor);- });- },- [markdown, pushUndo],- );-- const clearDocument = () => {- pushUndo(markdown);- setMarkdown("");- setStatus("");+ const refresh = useCallback(async () => {+ setLoading(true);setError("");- };-- const loadExampleTemplate = useCallback(() => {- if (markdown === CO_WRITER_SAMPLE_TEMPLATE) {- setStatus(t("Example template is already loaded."));- setError("");- return;+ try {+ const docs = await listCoWriterDocuments();+ setDocuments(docs);+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ } finally {+ setLoading(false);}-- pushUndo(markdown);- setMarkdown(CO_WRITER_SAMPLE_TEMPLATE);- setStatus(t("Loaded example template."));- setError("");- }, [markdown, pushUndo]);-- const handleDownload = () => {- const blob = new Blob([markdown], { type: "text/markdown;charset=utf-8" });- const url = URL.createObjectURL(blob);- const anchor = document.createElement("a");- anchor.href = url;- anchor.download = "co-writer.md";- anchor.click();- URL.revokeObjectURL(url);- };-- const replaceSelectedText = useCallback(- (range: SelectedRange, replacement: string) => {- pushUndo(range.snapshot);- const next = `${range.snapshot.slice(0, range.start)}${replacement}${range.snapshot.slice(range.end)}`;- preserveSelectionTraceRef.current = true;- setMarkdown(next);- setSelectedRange({- start: range.start,- end: range.start + replacement.length,- text: replacement,- snapshot: next,- });-- requestAnimationFrame(() => {- const textarea = textareaRef.current;- if (!textarea) return;- textarea.focus();- textarea.setSelectionRange(range.start, range.start + replacement.length);- updateSelectionPopover();- });- },- [pushUndo, updateSelectionPopover],- );-- const toggleSelectionTool = useCallback((tool: ToolName) => {- setSelectionTools((prev) =>- prev.includes(tool) ? prev.filter((item) => item !== tool) : [...prev, tool],- );}, []);- const handleSelectionPopoverDragStart = useCallback(- (event: React.MouseEvent<HTMLDivElement>) => {- const target = event.target as HTMLElement;- if (- target.closest(- "input, textarea, button, select, option, a, [data-no-drag='true']",- )- ) {- return;- }- event.preventDefault();- selectionDragStateRef.current = {- offsetX: event.clientX - selectionPopover.left,- offsetY: event.clientY - selectionPopover.top,- };- setSelectionPopoverPinned(true);- setIsDraggingSelectionPopover(true);- setIsToolMenuOpen(false);- setIsModeMenuOpen(false);- },- [selectionPopover.left, selectionPopover.top],- );-- const updateSelectionTraceFromEvent = useCallback((event: StreamTraceEvent) => {- setSelectionTrace((prev) => {- const current = prev ?? { thinking: "", toolTraces: [], response: "" };- if (event.type === "thinking") {- return { ...current, thinking: `${current.thinking}${event.content || ""}` };- }- if (event.type === "tool_call") {- return {- ...current,- toolTraces: [- ...current.toolTraces,- {- kind: "tool_call",- name: String(event.content || ""),- arguments:- event.metadata && typeof event.metadata.args === "object"- ? (event.metadata.args as Record<string, unknown>)- : {},- result: "",- success: true,- sources: [],- metadata: event.metadata || {},- },- ],- };- }- if (event.type === "tool_result") {- return {- ...current,- toolTraces: [- ...current.toolTraces,- {- kind: "tool_result",- name: String(event.metadata?.tool || "result"),- arguments: {},- result: String(event.content || ""),- success: true,- sources: [],- metadata: event.metadata || {},- },- ],- };- }- if (event.type === "content" && event.stage === "responding") {- return { ...current, response: `${current.response}${event.content || ""}` };- }- return current;- });- }, []);-- const applyReactSelectionEdit = useCallback(async () => {- if (!selectedRange) {- setError(t("Please select a text passage first."));- return;- }-- if (selectionMode === "none" && !selectionInstruction.trim()) {- setError(t("Please enter an instruction or choose a mode."));- return;- }+ useEffect(() => {+ void refresh();+ }, [refresh]);- setIsEditing(true);+ const handleCreate = useCallback(+ async (withTemplate: boolean) => {+ if (creating) return;+ setCreating(true);setError("");- setStatus("");- setSelectionTrace({ thinking: "", toolTraces: [], response: "" });- setIsTraceExpanded(true);- selectionRequestAbortRef.current?.abort();- const controller = new AbortController();- selectionRequestAbortRef.current = controller;-try {- const response = await fetch(apiUrl("/api/v1/co_writer/edit_react/stream"), {- method: "POST",- headers: { "Content-Type": "application/json" },- signal: controller.signal,- body: JSON.stringify({- selected_text: selectedRange.text,- instruction: selectionInstruction.trim(),- mode: selectionMode,- tools: selectionTools,- kb_name: selectionTools.includes("rag") ? kbName || null : null,- }),+ const document = await createCoWriterDocument({+ content: withTemplate ? CO_WRITER_SAMPLE_TEMPLATE : "",});- if (!response.ok) {- throw new Error((await response.text()) || "Failed to edit selected text.");- }- if (!response.body) {- throw new Error("Streaming response body is missing.");- }-- const reader = response.body.getReader();- const decoder = new TextDecoder();- let buffer = "";- let finalResult: StreamEditResult | undefined;-- const processSseChunk = (chunk: string) => {- const lines = chunk.split(/\r?\n/);- let eventName = "message";- const dataLines: string[] = [];- for (const line of lines) {- if (line.startsWith("event:")) {- eventName = line.slice(6).trim();- } else if (line.startsWith("data:")) {- dataLines.push(line.slice(5).trimStart());- }- }- if (dataLines.length === 0) return;- const payload = JSON.parse(dataLines.join("\n"));- if (eventName === "stream") {- updateSelectionTraceFromEvent(payload as StreamTraceEvent);- return;- }- if (eventName === "result") {- finalResult = payload as StreamEditResult;- return;- }- if (eventName === "error") {- throw new Error(String(payload?.detail || "Failed to edit selected text."));- }- };-- while (true) {- const { value, done } = await reader.read();- if (done) break;- buffer += decoder.decode(value, { stream: true });- while (true) {- const delimiterIndex = buffer.indexOf("\n\n");- if (delimiterIndex === -1) break;- const rawEvent = buffer.slice(0, delimiterIndex);- buffer = buffer.slice(delimiterIndex + 2);- processSseChunk(rawEvent);- }- }- buffer += decoder.decode();- if (buffer.trim()) {- processSseChunk(buffer.trim());- }- if (finalResult === undefined) {- throw new Error("Did not receive a final edit result.");- }- const editedText = finalResult.edited_text ?? "";-- if (markdown !== selectedRange.snapshot) {- throw new Error(- "The draft changed before AI edit finished. Please reselect the text and try again.",- );- }-- replaceSelectedText(selectedRange, editedText);- setStatus(t("Applied AI edit to the selection."));+ notifyCoWriterChanged();+ router.push(`/co-writer/${document.id}`);} catch (err) {- if (err instanceof DOMException && err.name === "AbortError") {- return;- }- setError(- err instanceof Error ? err.message : "Failed to edit selected text.",- );- } finally {- selectionRequestAbortRef.current = null;- setIsEditing(false);+ setError(err instanceof Error ? err.message : String(err));+ setCreating(false);}- }, [- kbName,- markdown,- replaceSelectedText,- selectedRange,- selectionInstruction,- selectionMode,- selectionTools,- updateSelectionTraceFromEvent,- ]);-- const applyEdit = async () => {- if (!instruction.trim()) {- setError(t("Please enter an editing instruction first."));- return;- }- setIsEditing(true);- setError("");- setStatus("");- try {- const response = await fetch(apiUrl("/api/v1/co_writer/edit"), {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- text: markdown,- instruction: instruction.trim(),- action,- source: source === "none" ? null : source,- kb_name: source === "rag" ? kbName || null : null,- }),- });- const data = await response.json();- if (!response.ok)- throw new Error(data?.detail || "Failed to edit document.");- pushUndo(markdown);- setMarkdown(data.edited_text || "");- setStatus(t("Applied {{action}} to the full draft.", { action: t(ACTION_LABELS[action]).toLowerCase() }));- setIsEditModalOpen(false);- } catch (err) {- setError(err instanceof Error ? err.message : "Failed to edit document.");- } finally {- setIsEditing(false);- }- };-- const applyAutoMark = async () => {- setIsAutoMarking(true);- setError("");- setStatus("");- try {- const response = await fetch(apiUrl("/api/v1/co_writer/automark"), {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ text: markdown }),- });- const data = await response.json();- if (!response.ok)- throw new Error(data?.detail || "Failed to auto-mark document.");- pushUndo(markdown);- setMarkdown(data.marked_text || "");- setStatus(t("Applied auto-mark annotations."));- } catch (err) {- setError(- err instanceof Error ? err.message : "Failed to auto-mark document.",- );- } finally {- setIsAutoMarking(false);- }- };-- const TOOLBAR: ToolbarItem[] = useMemo(- () => [- { id: "undo", icon: Undo2, title: "Undo", action: handleUndo },- { id: "redo", icon: Redo2, title: "Redo", action: handleRedo },- { id: "sep-1", icon: Minus, title: "", type: "separator" },- { id: "h1", icon: Heading1, title: "Heading 1", snippet: "\n# " },- { id: "h2", icon: Heading2, title: "Heading 2", snippet: "\n## " },- { id: "h3", icon: Heading3, title: "Heading 3", snippet: "\n### " },- { id: "h4", icon: Heading4, title: "Heading 4", snippet: "\n#### " },- { id: "h5", icon: Heading5, title: "Heading 5", snippet: "\n##### " },- { id: "h6", icon: Heading6, title: "Heading 6", snippet: "\n###### " },- { id: "sep-2", icon: Minus, title: "", type: "separator" },- { id: "bold", icon: Bold, title: "Bold", snippet: "**bold**" },- { id: "italic", icon: Italic, title: "Italic", snippet: "*italic*" },- {- id: "strikethrough",- icon: Strikethrough,- title: "Strikethrough",- snippet: "~~text~~",- },- { id: "code", icon: Braces, title: "Inline Code", snippet: "`code`" },- { id: "sep-3", icon: Minus, title: "", type: "separator" },- { id: "quote", icon: Quote, title: "Blockquote", snippet: "\n> " },- {- id: "ul",- icon: List,- title: "Bullet List",- snippet: "\n- Item\n- Item\n",- },- {- id: "ol",- icon: ListOrdered,- title: "Numbered List",- snippet: "\n1. Item\n2. Item\n",- },- {- id: "task",- icon: ListTodo,- title: "Task List",- snippet: "\n- [ ] Task\n- [x] Done\n",- },- { id: "sep-4", icon: Minus, title: "", type: "separator" },- { id: "hr", icon: Minus, title: "Horizontal Rule", snippet: "\n---\n" },- {- id: "table",- icon: Table2,- title: "Table",- snippet:- "\n| Column | Column |\n| ------ | ------ |\n| Cell | Cell |\n",- },- {- id: "link",- icon: LinkIcon,- title: "Link",- snippet: "[text](https://)",- },- {- id: "image",- icon: ImageIcon,- title: "Image",- snippet: "",- },- { id: "sep-5", icon: Minus, title: "", type: "separator" },- {- id: "codeblock",- icon: Code2,- title: "Code Block",- snippet: '\n```python\nprint("hello")\n```\n',- },- {- id: "mermaid",- icon: Workflow,- title: "Mermaid Diagram",- snippet:- "\n```mermaid\nflowchart TD\n A[Start] --> B[End]\n```\n",- },- {- id: "math",- icon: () => (- <span className="text-[11px] font-semibold leading-none">- Σ- </span>- ),- title: "Math Block",- snippet: "\n$$\na^2 + b^2 = c^2\n$$\n",- },- ],- [handleUndo, handleRedo],+ },+ [creating, router],);- useEffect(() => {- if (!selectionPopover.visible) return;- const handleViewportChange = () => updateSelectionPopover();- window.addEventListener("resize", handleViewportChange);- return () => window.removeEventListener("resize", handleViewportChange);- }, [selectionPopover.visible, updateSelectionPopover]);-- useEffect(() => {- if (!selectionPopover.visible) return;- const handlePointerDown = (event: MouseEvent) => {- const target = event.target as Node;- if (selectionPopoverRef.current?.contains(target)) return;- if (textareaRef.current?.contains(target)) return;- hideSelectionPopover();- };- document.addEventListener("mousedown", handlePointerDown);- return () => document.removeEventListener("mousedown", handlePointerDown);- }, [hideSelectionPopover, selectionPopover.visible]);-- useEffect(() => {- if (!isDraggingSelectionPopover) return;- const handleMouseMove = (event: MouseEvent) => {- const dragState = selectionDragStateRef.current;- const popover = selectionPopoverRef.current;- if (!dragState || !popover) return;- const width = popover.offsetWidth || 360;- const height = popover.offsetHeight || 200;- const nextLeft = Math.min(- Math.max(event.clientX - dragState.offsetX, 12),- window.innerWidth - width - 12,- );- const nextTop = Math.min(- Math.max(event.clientY - dragState.offsetY, 12),- window.innerHeight - height - 12,- );- setSelectionPopover((prev) => ({- ...prev,- visible: true,- top: nextTop,- left: nextLeft,- }));- };- const handleMouseUp = () => {- selectionDragStateRef.current = null;- setIsDraggingSelectionPopover(false);- };- window.addEventListener("mousemove", handleMouseMove);- window.addEventListener("mouseup", handleMouseUp);- return () => {- window.removeEventListener("mousemove", handleMouseMove);- window.removeEventListener("mouseup", handleMouseUp);- };- }, [isDraggingSelectionPopover]);-- useEffect(() => {- return () => {- selectionRequestAbortRef.current?.abort();- if (scrollSyncResetTimerRef.current) {- clearTimeout(scrollSyncResetTimerRef.current);- }- };- }, []);-- const handleSplitterPointerDown = useCallback(- (event: React.PointerEvent<HTMLDivElement>) => {- if (!showEditor || !showPreview) return;- event.preventDefault();- setIsResizingSplit(true);+ const handleDelete = useCallback(+ async (docId: string) => {+ if (deletingId) return;+ setDeletingId(docId);try {- (event.target as HTMLDivElement).setPointerCapture(event.pointerId);- } catch {- /* ignore */+ await deleteCoWriterDocument(docId);+ setDocuments((prev) => prev.filter((doc) => doc.id !== docId));+ setPendingDeleteId(null);+ notifyCoWriterChanged();+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ } finally {+ setDeletingId(null);}},- [showEditor, showPreview],+ [deletingId],);- useEffect(() => {- if (!isResizingSplit) return;- const handleMove = (event: PointerEvent) => {- const container = splitContainerRef.current;- if (!container) return;- const rect = container.getBoundingClientRect();- if (rect.width <= 0) return;- const ratio = (event.clientX - rect.left) / rect.width;- setEditorRatio(- Math.min(MAX_PANEL_RATIO, Math.max(MIN_PANEL_RATIO, ratio)),- );- };- const handleEnd = () => setIsResizingSplit(false);- window.addEventListener("pointermove", handleMove);- window.addEventListener("pointerup", handleEnd);- window.addEventListener("pointercancel", handleEnd);- return () => {- window.removeEventListener("pointermove", handleMove);- window.removeEventListener("pointerup", handleEnd);- window.removeEventListener("pointercancel", handleEnd);- };- }, [isResizingSplit]);-- const releaseScrollSyncSource = useCallback(() => {- if (scrollSyncResetTimerRef.current) {- clearTimeout(scrollSyncResetTimerRef.current);- }- scrollSyncResetTimerRef.current = setTimeout(() => {- scrollSyncSourceRef.current = null;- }, 90);- }, []);-- // ── Line-anchored scroll synchronization ──- //- // Each block element rendered in the preview carries a `data-source-line`- // attribute that points back at its starting line in the markdown source- // (provided by remark's AST position info). For the editor side we cannot- // assume `scrollTop / lineHeight = source line` because long lines wrap- // visually. Instead we build a hidden mirror that mimics the textarea's- // wrapping and read the real pixel y of every source line. With both sides- // expressed as pixel coordinates we can interpolate either direction with- // a single piecewise-linear map.-- // Cache: rebuilding the mirror is moderately expensive, so cache by- // (markdown content, textarea inner width). Both invalidate the cache.- const editorYCacheRef = useRef<{- signature: string;- ys: Map<number, number>;- } | null>(null);-- const measureEditorLineYs = useCallback((): Map<number, number> => {- const editor = textareaRef.current;- if (!editor) return new Map();- const value = editor.value;- const sourceLines = value.split("\n");- if (sourceLines.length === 0) return new Map();-- const computed = window.getComputedStyle(editor);- const rect = editor.getBoundingClientRect();- const mirror = document.createElement("div");-- const properties = [- "box-sizing",- "width",- "border-top-width",- "border-right-width",- "border-bottom-width",- "border-left-width",- "padding-top",- "padding-right",- "padding-bottom",- "padding-left",- "font-style",- "font-variant",- "font-weight",- "font-stretch",- "font-size",- "font-size-adjust",- "line-height",- "font-family",- "letter-spacing",- "text-align",- "text-transform",- "text-indent",- "tab-size",- ];- for (const property of properties) {- mirror.style.setProperty(property, computed.getPropertyValue(property));- }-- mirror.style.position = "fixed";- mirror.style.top = `${rect.top}px`;- mirror.style.left = `${rect.left}px`;- mirror.style.height = "auto";- mirror.style.maxHeight = "none";- mirror.style.minHeight = "0";- mirror.style.whiteSpace = "pre-wrap";- mirror.style.overflowWrap = "break-word";- mirror.style.wordBreak = "normal";- mirror.style.visibility = "hidden";- mirror.style.pointerEvents = "none";- mirror.style.zIndex = "-1";-- const spans: HTMLSpanElement[] = [];- for (let i = 0; i < sourceLines.length; i += 1) {- if (i > 0) mirror.appendChild(document.createTextNode("\n"));- const span = document.createElement("span");- // Empty lines need measurable content for offsetTop to be meaningful.- span.textContent =- sourceLines[i].length > 0 ? sourceLines[i] : "\u200B";- mirror.appendChild(span);- spans.push(span);- }-- document.body.appendChild(mirror);-- const result = new Map<number, number>();- // span.offsetTop is the y-position of the line within the mirror, which- // mirrors the textarea's scroll content. Setting `editor.scrollTop` to- // this value lifts that source line to the top of the visible viewport.- for (let i = 0; i < spans.length; i += 1) {- result.set(i + 1, spans[i].offsetTop);- }-- document.body.removeChild(mirror);- return result;- }, []);-- const getEditorLineYs = useCallback((): Map<number, number> => {- const editor = textareaRef.current;- if (!editor) return new Map();- const signature = `${editor.clientWidth}|${markdown}`;- const cached = editorYCacheRef.current;- if (cached && cached.signature === signature) return cached.ys;- const ys = measureEditorLineYs();- editorYCacheRef.current = { signature, ys };- return ys;- }, [markdown, measureEditorLineYs]);-- const collectPreviewLineYs = useCallback((): Map<number, number> => {- const preview = previewScrollRef.current;- if (!preview) return new Map();- const nodes = preview.querySelectorAll<HTMLElement>("[data-source-line]");- if (nodes.length === 0) return new Map();- const previewRect = preview.getBoundingClientRect();- const baseTop = previewRect.top - preview.scrollTop;- const result = new Map<number, number>();- for (const el of Array.from(nodes)) {- const raw = el.getAttribute("data-source-line");- const line = raw ? Number.parseInt(raw, 10) : NaN;- if (!Number.isFinite(line)) continue;- // Keep the first occurrence; nested wrappers often repeat the same line.- if (result.has(line)) continue;- const rect = el.getBoundingClientRect();- result.set(line, rect.top - baseTop);- }- return result;- }, []);-- const buildJointMarkers = useCallback((): Array<{- line: number;- editorY: number;- previewY: number;- }> => {- const editorYs = getEditorLineYs();- const previewYs = collectPreviewLineYs();- if (editorYs.size === 0 || previewYs.size === 0) return [];-- const lines = Array.from(previewYs.keys())- .filter((line) => editorYs.has(line))- .sort((a, b) => a - b);-- const editor = textareaRef.current;- const preview = previewScrollRef.current;- const markers: Array<{ line: number; editorY: number; previewY: number }> =- [];- for (const line of lines) {- const editorY = editorYs.get(line);- const previewY = previewYs.get(line);- if (typeof editorY !== "number" || typeof previewY !== "number") continue;- markers.push({ line, editorY, previewY });- }-- // Anchor the very top so we don't snap to the first heading when the user- // is still above it.- if (markers.length === 0 || markers[0].editorY > 0 || markers[0].previewY > 0) {- markers.unshift({ line: 0, editorY: 0, previewY: 0 });- }-- // Anchor the bottom so the bottom of the document matches.- if (editor && preview) {- const editorMax = Math.max(0, editor.scrollHeight - editor.clientHeight);- const previewMax = Math.max(0, preview.scrollHeight - preview.clientHeight);- const last = markers[markers.length - 1];- if (- editorMax > last.editorY + 1 ||- previewMax > last.previewY + 1- ) {- markers.push({- line: last.line + 1,- editorY: editorMax,- previewY: previewMax,- });- }- }-- return markers;- }, [collectPreviewLineYs, getEditorLineYs]);-- const interpolate = (- value: number,- fromA: number,- fromB: number,- toA: number,- toB: number,- ): number => {- if (fromA === fromB) return toA;- const ratio = (value - fromA) / (fromB - fromA);- return toA + (toB - toA) * ratio;- };-- const handleEditorScrollSync = useCallback(() => {- updateSelectionPopover();- if (!syncScrollEnabled) return;- if (scrollSyncSourceRef.current === "preview") return;- const editor = textareaRef.current;- const preview = previewScrollRef.current;- if (!editor || !preview) return;- const markers = buildJointMarkers();- if (markers.length === 0) return;-- const editorScroll = editor.scrollTop;- let lower = markers[0];- let upper = markers[markers.length - 1];- for (const marker of markers) {- if (marker.editorY <= editorScroll) lower = marker;- if (marker.editorY >= editorScroll) {- upper = marker;- break;- }- }-- const target = interpolate(- editorScroll,- lower.editorY,- upper.editorY,- lower.previewY,- upper.previewY,- );-- const max = preview.scrollHeight - preview.clientHeight;- const next = Math.max(0, Math.min(max, target));- if (Math.abs(next - preview.scrollTop) < 0.5) return;- scrollSyncSourceRef.current = "editor";- preview.scrollTop = next;- releaseScrollSyncSource();- }, [- buildJointMarkers,- releaseScrollSyncSource,- syncScrollEnabled,- updateSelectionPopover,- ]);-- const handlePreviewScrollSync = useCallback(() => {- if (!syncScrollEnabled) return;- if (scrollSyncSourceRef.current === "editor") return;- const editor = textareaRef.current;- const preview = previewScrollRef.current;- if (!editor || !preview) return;- const markers = buildJointMarkers();- if (markers.length === 0) return;-- const previewScroll = preview.scrollTop;- let lower = markers[0];- let upper = markers[markers.length - 1];- for (const marker of markers) {- if (marker.previewY <= previewScroll) lower = marker;- if (marker.previewY >= previewScroll) {- upper = marker;- break;- }- }-- const target = interpolate(- previewScroll,- lower.previewY,- upper.previewY,- lower.editorY,- upper.editorY,- );-- const max = editor.scrollHeight - editor.clientHeight;- const next = Math.max(0, Math.min(max, target));- if (Math.abs(next - editor.scrollTop) < 0.5) return;- scrollSyncSourceRef.current = "preview";- editor.scrollTop = next;- releaseScrollSyncSource();- }, [buildJointMarkers, releaseScrollSyncSource, syncScrollEnabled]);-- // Mermaid diagrams, images, and KaTeX render asynchronously, so the preview's- // scrollHeight (and the y position of every marker after them) shifts well- // after the initial render. Without intervention, the user's last alignment- // becomes stale and the next scroll feels "jumpy" because all the markers- // moved underneath them. Whenever the preview's intrinsic height changes we- // re-run the editor→preview sync to put the preview back in lock-step with- // the editor's current scroll position.- const handleEditorScrollSyncRef = useRef(handleEditorScrollSync);- useEffect(() => {- handleEditorScrollSyncRef.current = handleEditorScrollSync;- }, [handleEditorScrollSync]);-- useEffect(() => {- const preview = previewScrollRef.current;- if (!preview) return;- const inner = preview.firstElementChild as HTMLElement | null;- if (!inner) return;-- let raf = 0;- const schedule = () => {- if (raf) cancelAnimationFrame(raf);- raf = requestAnimationFrame(() => {- raf = 0;- // Treat this as an editor-driven update; we want preview to follow- // wherever the editor cursor currently anchors us, not the other way- // around (which would feed back into editor scroll).- if (scrollSyncSourceRef.current) return;- handleEditorScrollSyncRef.current();- });- };-- const observer = new ResizeObserver(schedule);- observer.observe(inner);-- // Images load asynchronously and don't always trigger a ResizeObserver- // update on the parent, so we listen to load events directly too.- const onLoad = (event: Event) => {- const target = event.target as HTMLElement | null;- if (!target) return;- if (target.tagName === "IMG" || target.tagName === "IFRAME") schedule();- };- inner.addEventListener("load", onLoad, true);-- return () => {- if (raf) cancelAnimationFrame(raf);- observer.disconnect();- inner.removeEventListener("load", onLoad, true);- };- }, [showPreview]);+ const renderEmpty = () => (+ <div className="flex flex-col items-center justify-center gap-4 rounded-xl border border-dashed border-[var(--border)] bg-[var(--secondary)]/30 px-8 py-16 text-center">+ <PenLine size={28} className="text-[var(--muted-foreground)]/50" />+ <div>+ <p className="text-base font-medium text-[var(--foreground)]">+ {t("No drafts yet")}+ </p>+ <p className="mt-1 text-sm text-[var(--muted-foreground)]">+ {t("Start a new markdown draft to begin writing.")}+ </p>+ </div>+ <div className="flex items-center gap-2">+ <button+ type="button"+ onClick={() => handleCreate(false)}+ disabled={creating}+ className="inline-flex items-center gap-1.5 rounded-md bg-[var(--primary)] px-3 py-1.5 text-sm font-medium text-white transition-opacity hover:opacity-90 disabled:opacity-60"+ >+ {creating ? <Loader2 size={14} className="animate-spin" /> : <Plus size={14} />}+ {t("New draft")}+ </button>+ <button+ type="button"+ onClick={() => handleCreate(true)}+ disabled={creating}+ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] px-3 py-1.5 text-sm font-medium text-[var(--foreground)] transition-colors hover:bg-[var(--muted)] disabled:opacity-60"+ >+ <FileText size={14} />+ {t("Start from template")}+ </button>+ </div>+ </div>+ );return (<div className="flex h-full min-h-full flex-col overflow-hidden bg-[var(--background)]">- {/* ── Top bar ── */}- <header className="flex shrink-0 items-center justify-between border-b border-[var(--border)] px-4 py-1.5">- <div className="flex items-center gap-3 text-sm text-[var(--muted-foreground)]">- <span className="font-medium text-[var(--foreground)]">- {t("Co-Writer")}- </span>- <span className="hidden text-xs sm:inline">- {wordCount} {t("words")} · {charCount} {t("chars")}- </span>+ <header className="flex shrink-0 items-center justify-between border-b border-[var(--border)] px-6 py-3">+ <div className="flex items-center gap-3">+ <PenLine size={18} className="text-[var(--muted-foreground)]" />+ <div>+ <div className="text-sm font-semibold text-[var(--foreground)]">+ {t("Co-Writer")}+ </div>+ <div className="text-xs text-[var(--muted-foreground)]">+ {t("Manage your markdown drafts and projects.")}+ </div>+ </div></div><div className="flex items-center gap-2">- <ToolbarIconBtn- title={t("Clear")}- onClick={clearDocument}- >- <Eraser size={17} strokeWidth={1.7} />- </ToolbarIconBtn>- <ToolbarIconBtn- title={t("Export Markdown")}- onClick={handleDownload}- >- <Download size={17} strokeWidth={1.7} />- </ToolbarIconBtn>- <ToolbarIconBtn- title={t("Load Example Template")}- onClick={loadExampleTemplate}- >- <FileText size={17} strokeWidth={1.7} />- </ToolbarIconBtn>- <div className="relative">- <ToolbarIconBtn- title={t("Add to Notebook")}- onClick={() => setShowSaveModal(true)}- >- <BookPlus size={17} strokeWidth={1.7} />- </ToolbarIconBtn>- </div>- <a- href="https://litewrite.ai/"- target="_blank"- rel="noreferrer"- className="inline-flex items-center gap-1 rounded-full border border-[var(--border)] px-2.5 py-1 text-[11px] font-medium text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"- >- <span>{t("Pro Vide Writing")}</span>- <ArrowUpRight size={12} strokeWidth={1.8} aria-hidden="true" />- </a>- <div className="mx-1 h-5 w-px bg-[var(--border)]" /><button- onClick={() => setIsEditModalOpen(true)}- className="inline-flex items-center gap-1.5 rounded-md bg-[var(--primary)] px-3 py-1 text-xs font-medium text-white transition-opacity hover:opacity-90"+ type="button"+ onClick={() => handleCreate(true)}+ disabled={creating}+ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] px-3 py-1.5 text-xs font-medium text-[var(--foreground)] transition-colors hover:bg-[var(--muted)] disabled:opacity-60">- <WandSparkles size={13} />- {t("Full Draft")}+ <FileText size={13} />+ {t("From template")}</button>- </div>- </header>-- {/* ── Toolbar ── */}- <div className="flex shrink-0 items-center gap-0.5 overflow-x-auto border-b border-[var(--border)] px-3 py-1">- {TOOLBAR.map((item) => {- if (item.type === "separator") {- return (- <div- key={item.id}- className="mx-1 h-4 w-px shrink-0 bg-[var(--border)]"- />- );- }- const Icon = item.icon;- return (- <button- key={item.id}- title={t(item.title)}- onClick={() =>- item.action ? item.action() : insertSnippet(item.snippet || "")- }- className="shrink-0 rounded p-1.5 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"- >- <Icon size={16} />- </button>- );- })}-- <div className="ml-auto flex shrink-0 items-center gap-1.5 pl-3 text-[10px] text-[var(--muted-foreground)]"><buttontype="button"- onClick={() => setSyncScrollEnabled((prev) => !prev)}- disabled={!showEditor || !showPreview}- title={- syncScrollEnabled- ? t("Scroll sync is on. Click to disable.")- : t("Scroll sync is off. Click to enable.")- }- className={`inline-flex items-center gap-1 rounded border px-1.5 py-0.5 text-[10px] font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-40 ${- syncScrollEnabled- ? "border-[var(--primary)]/40 bg-[var(--primary)]/10 text-[var(--primary)]"- : "border-[var(--border)] bg-transparent text-[var(--muted-foreground)] hover:bg-[var(--muted)]"- }`}+ onClick={() => handleCreate(false)}+ disabled={creating}+ className="inline-flex items-center gap-1.5 rounded-md bg-[var(--primary)] px-3 py-1.5 text-xs font-medium text-white transition-opacity hover:opacity-90 disabled:opacity-60">- <span- aria-hidden="true"- className={`inline-block h-1.5 w-1.5 rounded-full ${- syncScrollEnabled ? "bg-[var(--primary)]" : "bg-[var(--muted-foreground)]/60"- }`}- />- {t("Sync Scroll")}+ {creating ? (+ <Loader2 size={13} className="animate-spin" />+ ) : (+ <Plus size={13} />+ )}+ {t("New draft")}</button>- <span className="mx-0.5 h-3 w-px bg-[var(--border)]" aria-hidden="true" />- <span className="rounded bg-[var(--muted)] px-1.5 py-0.5">GFM</span>- <span className="rounded bg-[var(--muted)] px-1.5 py-0.5">- KaTeX- </span>- <span className="rounded bg-[var(--muted)] px-1.5 py-0.5">- Mermaid- </span></div>- </div>-- {/* ── Editor + Preview ── */}- <div- ref={splitContainerRef}- className={`relative flex min-h-0 flex-1 ${- isResizingSplit ? "select-none" : ""- }`}- >- {/* Editor panel */}- {showEditor && (- <div- className="flex min-h-0 flex-col"- style={{- width: showPreview ? `${editorRatio * 100}%` : "100%",- }}- >- <div className="flex shrink-0 items-center justify-between border-b border-[var(--border)] px-3 py-1">- <span className="text-xs font-medium text-[var(--muted-foreground)]">- {t("Editor")}- </span>- <button- title={t("Collapse editor")}- onClick={() => setEditorCollapsed(true)}- className="rounded p-0.5 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"- >- <ChevronLeft size={14} />- </button>- </div>- <textarea- ref={textareaRef}- value={markdown}- onChange={(e) => handleMarkdownChange(e.target.value)}- onSelect={updateSelectionPopover}- onKeyUp={updateSelectionPopover}- onMouseUp={updateSelectionPopover}- onScroll={handleEditorScrollSync}- spellCheck={false}- className="min-h-0 flex-1 resize-none bg-transparent p-4 font-mono text-[13px] leading-relaxed text-[var(--foreground)] outline-none placeholder:text-[var(--muted-foreground)]"- placeholder={t("Start writing in Markdown...")}- />- </div>- )}-- {/* Draggable splitter (only when both panes are visible) */}- {showEditor && showPreview && (- <div- role="separator"- aria-orientation="vertical"- aria-label={t("Resize editor and preview")}- onPointerDown={handleSplitterPointerDown}- onDoubleClick={() => setEditorRatio(0.5)}- className={`group relative z-10 flex w-1 shrink-0 cursor-col-resize items-stretch border-x border-[var(--border)] transition-colors ${- isResizingSplit- ? "bg-[var(--primary)]/40"- : "bg-transparent hover:bg-[var(--primary)]/30"- }`}- title={t("Drag to resize, double-click to reset")}- >- {/* Wider invisible hit-area so the handle is easy to grab */}- <div className="absolute inset-y-0 -left-1.5 -right-1.5" />- <div- className={`pointer-events-none absolute left-1/2 top-1/2 h-10 w-[3px] -translate-x-1/2 -translate-y-1/2 rounded-full transition-opacity ${- isResizingSplit- ? "bg-[var(--primary)] opacity-100"- : "bg-[var(--muted-foreground)]/40 opacity-0 group-hover:opacity-100"- }`}- />- </div>- )}-- {/* Collapse gutter / expand buttons */}- {editorCollapsed && (- <button- onClick={() => setEditorCollapsed(false)}- title={t("Expand editor")}- className="flex w-7 shrink-0 items-center justify-center border-r border-[var(--border)] text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"- >- <ChevronRight size={14} />- </button>- )}-- {previewCollapsed && (- <button- onClick={() => setPreviewCollapsed(false)}- title={t("Expand preview")}- className="flex w-7 shrink-0 items-center justify-center border-l border-[var(--border)] text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"- >- <ChevronLeft size={14} />- </button>- )}-- {/* Preview panel */}- {showPreview && (- <div- className="flex min-h-0 flex-col"- style={{- width: showEditor ? `${(1 - editorRatio) * 100}%` : "100%",- }}- >- <div className="flex shrink-0 items-center justify-between border-b border-[var(--border)] px-3 py-1">- <span className="text-xs font-medium text-[var(--muted-foreground)]">- {t("Preview")}- </span>- <button- title={t("Collapse preview")}- onClick={() => setPreviewCollapsed(true)}- className="rounded p-0.5 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"- >- <ChevronRight size={14} />- </button>- </div>- <div- ref={previewScrollRef}- onScroll={handlePreviewScrollSync}- className="min-h-0 flex-1 overflow-y-auto p-5"- >- <MarkdownRenderer- content={markdown || `_${t("Nothing to preview yet.")}_`}- variant="prose"- trackSourceLines- />- </div>- </div>- )}- </div>+ </header>- {selectionPopover.visible && selectedRange && (- <div- ref={selectionPopoverRef}- onMouseDown={handleSelectionPopoverDragStart}- className={`fixed z-50 rounded-2xl border border-[var(--border)] bg-[var(--card)] p-2.5 shadow-2xl ${- isDraggingSelectionPopover ? "cursor-grabbing" : "cursor-grab"- }`}- style={{- top: selectionPopover.top,- left: selectionPopover.left,- width: 360,- }}- >- <div className="mb-2 flex justify-center" aria-hidden="true">- <div className="h-1 w-10 rounded-full bg-[var(--border)]/80" />+ <main className="flex-1 overflow-y-auto px-6 py-6">+ {error ? (+ <div className="mb-4 rounded-md border border-rose-300/30 bg-rose-50/40 px-3 py-2 text-xs text-rose-700 dark:bg-rose-950/30 dark:text-rose-300">+ {error}</div>+ ) : null}- <div className="relative">- <input- value={selectionInstruction}- onChange={(e) => setSelectionInstruction(e.target.value)}- onKeyDown={(e) => {- if (e.key === "Enter") {- e.preventDefault();- void applyReactSelectionEdit();- }- }}- className="h-10 w-full rounded-xl bg-transparent pl-3 pr-10 text-[13px] text-[var(--foreground)] outline-none placeholder:text-[var(--muted-foreground)]"- placeholder={t("Tell AI what to do with the selection...")}- />- <button- onClick={() => void applyReactSelectionEdit()}- disabled={isEditing || isAutoMarking}- className="absolute right-1.5 top-1.5 inline-flex h-7 w-7 items-center justify-center rounded-full bg-[var(--primary)] text-white transition-opacity disabled:opacity-45"- title={t("Apply AI edit")}- >- {isEditing ? (- <Loader2 size={13} className="animate-spin" />- ) : (- <ArrowRight size={13} />- )}- </button>+ {loading ? (+ <div className="flex items-center justify-center gap-2 py-20 text-sm text-[var(--muted-foreground)]">+ <Loader2 size={16} className="animate-spin" />+ {t("Loading drafts…")}</div>-- <div className="mt-2 grid grid-cols-2 gap-2">- <div className="relative">- <button- onClick={() => {- setIsToolMenuOpen((prev) => !prev);- setIsModeMenuOpen(false);- }}- className="flex h-9 w-full items-center justify-between rounded-xl border border-[var(--border)] px-3 text-[12px] text-[var(--foreground)] transition-colors hover:bg-[var(--muted)]"- >- <span className="truncate">- {selectionTools.length === 0- ? t("Tools")- : selectionTools.length === 1- ? t(TOOL_OPTIONS.find((item) => item.name === selectionTools[0])- ?.label || "Tools")- : t("{{count}} tools", { count: selectionTools.length })}- </span>- <ChevronDown- size={13}- className={`shrink-0 transition-transform ${isToolMenuOpen ? "rotate-180" : ""}`}- />- </button>- {isToolMenuOpen && (- <div className="absolute left-0 top-full z-20 mt-1 w-full rounded-xl border border-[var(--border)] bg-[var(--card)] p-1 shadow-xl">- {TOOL_OPTIONS.map((tool) => {- const active = selectionTools.includes(tool.name);- return (- <button- key={tool.name}- onClick={() => toggleSelectionTool(tool.name)}- className="flex w-full items-center justify-between rounded-lg px-2.5 py-2 text-left text-[12px] text-[var(--foreground)] transition-colors hover:bg-[var(--muted)]"- >- <span>{t(tool.label)}</span>- {active ? <Check size={12} /> : <span className="w-3" />}- </button>- );- })}- </div>- )}- </div>-- <div className="relative">- <button- onClick={() => {- setIsModeMenuOpen((prev) => !prev);- setIsToolMenuOpen(false);- }}- className="flex h-9 w-full items-center justify-between rounded-xl border border-[var(--border)] px-3 text-[12px] text-[var(--foreground)] transition-colors hover:bg-[var(--muted)]"- >- <span>- {t(MODE_OPTIONS.find((item) => item.value === selectionMode)?.label ||- "Mode")}- </span>- <ChevronDown- size={13}- className={`shrink-0 transition-transform ${isModeMenuOpen ? "rotate-180" : ""}`}- />- </button>- {isModeMenuOpen && (- <div className="absolute left-0 top-full z-20 mt-1 w-full rounded-xl border border-[var(--border)] bg-[var(--card)] p-1 shadow-xl">- {MODE_OPTIONS.map((mode) => (+ ) : documents.length === 0 ? (+ renderEmpty()+ ) : (+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-3">+ {documents.map((doc) => {+ const isPendingDelete = pendingDeleteId === doc.id;+ const isDeleting = deletingId === doc.id;+ return (+ <div+ key={doc.id}+ role="button"+ tabIndex={0}+ onClick={() => router.push(`/co-writer/${doc.id}`)}+ onKeyDown={(event) => {+ if (event.key === "Enter" || event.key === " ") {+ event.preventDefault();+ router.push(`/co-writer/${doc.id}`);+ }+ }}+ className="group relative flex h-44 cursor-pointer flex-col rounded-xl border border-[var(--border)] bg-[var(--secondary)]/40 p-4 transition-all hover:border-[var(--primary)]/40 hover:bg-[var(--secondary)]/70 hover:shadow-sm"+ >+ <div className="flex items-start justify-between gap-2">+ <div className="flex min-w-0 items-start gap-2">+ <FileText+ size={14}+ className="mt-0.5 shrink-0 text-[var(--muted-foreground)]"+ />+ <div className="min-w-0">+ <div+ className="truncate text-sm font-medium text-[var(--foreground)]"+ title={doc.title || t("Untitled draft")}+ >+ {doc.title || t("Untitled draft")}+ </div>+ <div className="text-[10px] text-[var(--muted-foreground)]/70">+ {t("Updated")} {relativeTime(doc.updated_at)} {t("ago")}+ </div>+ </div>+ </div><button- key={mode.value}- onClick={() => {- setSelectionMode(mode.value);- setIsModeMenuOpen(false);+ type="button"+ onClick={(event) => {+ event.stopPropagation();+ if (isPendingDelete) {+ void handleDelete(doc.id);+ } else {+ setPendingDeleteId(doc.id);+ }}}- className="flex w-full items-center justify-between rounded-lg px-2.5 py-2 text-left text-[12px] text-[var(--foreground)] transition-colors hover:bg-[var(--muted)]"+ disabled={isDeleting}+ title={+ isPendingDelete+ ? t("Click again to confirm")+ : t("Delete draft")+ }+ className={`shrink-0 rounded-md p-1 transition-colors disabled:opacity-50 ${+ isPendingDelete+ ? "bg-rose-500/15 text-rose-600 dark:text-rose-400"+ : "text-[var(--muted-foreground)]/60 opacity-0 hover:bg-rose-500/10 hover:text-rose-600 group-hover:opacity-100 dark:hover:text-rose-400"+ }`}>- <span>{t(mode.label)}</span>- {selectionMode === mode.value ? (- <Check size={12} />+ {isDeleting ? (+ <Loader2 size={13} className="animate-spin" />) : (- <span className="w-3" />+ <Trash2 size={13} />)}</button>- ))}+ </div>+ <p className="mt-3 line-clamp-4 flex-1 text-xs leading-relaxed text-[var(--muted-foreground)]">+ {doc.preview || t("Empty draft")}+ </p></div>- )}- </div>+ );+ })}</div>-- {(isEditing || selectionTrace) && (- <div className="mt-2 rounded-xl border border-[var(--border)]/70 bg-[var(--muted)]/18">- <button- onClick={() => setIsTraceExpanded((prev) => !prev)}- className="flex w-full items-center gap-2 px-3 py-2 text-left text-[12px] text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"- >- <ChevronDown- size={12}- className={`shrink-0 transition-transform ${isTraceExpanded ? "rotate-180" : ""}`}- />- <span className="font-medium text-[var(--foreground)]">- {t("Trace")}- </span>- {isEditing ? (- <Loader2 size={12} className="ml-auto animate-spin" />- ) : null}- </button>-- {isTraceExpanded && (- <div- data-no-drag="true"- className="max-h-[280px] overflow-y-auto border-t border-[var(--border)]/60 px-3 py-2 text-[12px] leading-[1.7] text-[var(--muted-foreground)]"- >- {selectionTrace?.thinking ? (- <div className="space-y-1.5">- <div className="text-[11px] font-medium uppercase tracking-[0.08em] text-[var(--muted-foreground)]/60">- {t("Thought")}- </div>- <MarkdownRenderer- content={selectionTrace.thinking}- variant="trace"- />- </div>- ) : isEditing ? (- <div className="opacity-70">{t("Thinking...")}</div>- ) : null}-- {selectionTrace && selectionTrace.toolTraces.length > 0 && (- <div className="mt-3 space-y-1.5">- <div className="text-[11px] font-medium uppercase tracking-[0.08em] text-[var(--muted-foreground)]/60">- {t("Tool")}- </div>- <div className="space-y-2">- {selectionTrace.toolTraces.map((trace, index) => (- <div key={`${trace.name}-${index}`} className="space-y-1">- <div>- <span className="opacity-50">- {trace.kind === "tool_result" ? "✓ " : "→ "}- </span>- <span className="text-[var(--foreground)]">- {trace.name}- </span>- </div>- {trace.arguments &&- Object.keys(trace.arguments).length > 0 ? (- <pre className="ml-3 whitespace-pre-wrap break-words rounded-md bg-[var(--muted)]/45 px-2 py-1 font-mono text-[11px] leading-[1.55] text-[var(--muted-foreground)]/78">- {JSON.stringify(trace.arguments, null, 2)}- </pre>- ) : null}- {trace.result ? (- <div className="ml-3">- <MarkdownRenderer- content={trace.result}- variant="trace"- />- </div>- ) : null}- </div>- ))}- </div>- </div>- )}-- {selectionTrace?.response ? (- <div className="mt-3 space-y-1.5">- <div className="text-[11px] font-medium uppercase tracking-[0.08em] text-[var(--muted-foreground)]/60">- {t("Response")}- </div>- <MarkdownRenderer- content={selectionTrace.response}- variant="trace"- />- </div>- ) : null}-- {isEditing &&- selectionTrace &&- !selectionTrace.thinking &&- selectionTrace.toolTraces.length === 0 &&- !selectionTrace.response ? (- <div className="mt-2 opacity-70">- {t("Running tools and preparing the final edit...")}- </div>- ) : null}- </div>- )}- </div>- )}- </div>- )}-- {/* ── Status bar ── */}- {(error || status) && (- <div- className={`shrink-0 border-t px-4 py-1.5 text-xs ${- error- ? "border-red-200 bg-red-50 text-red-600 dark:border-red-900 dark:bg-red-950/30 dark:text-red-400"- : "border-emerald-200 bg-emerald-50 text-emerald-600 dark:border-emerald-900 dark:bg-emerald-950/30 dark:text-emerald-400"- }`}- >- {error || status}- </div>- )}-- {/* ── AI Edit modal ── */}- {isEditModalOpen && (- <div- className="fixed inset-0 z-50 flex items-center justify-center bg-black/30 backdrop-blur-sm"- onClick={(e) => {- if (e.target === e.currentTarget) setIsEditModalOpen(false);- }}- >- <div className="w-full max-w-md rounded-xl border border-[var(--border)] bg-[var(--card)] shadow-xl">- <div className="flex items-center justify-between border-b border-[var(--border)] px-4 py-3">- <h2 className="text-sm font-semibold text-[var(--foreground)]">- {t("Full Draft AI Edit")}- </h2>- <button- onClick={() => setIsEditModalOpen(false)}- className="text-xs text-[var(--muted-foreground)] hover:text-[var(--foreground)]"- >- {t("Close")}- </button>- </div>-- <div className="space-y-3 px-4 py-4">- <div className="flex gap-1.5">- {(Object.keys(ACTION_LABELS) as EditAction[]).map((a) => (- <button- key={a}- onClick={() => setAction(a)}- className={`rounded-md px-3 py-1.5 text-xs transition-colors ${- action === a- ? "bg-[var(--primary)] text-white"- : "border border-[var(--border)] text-[var(--foreground)] hover:bg-[var(--muted)]"- }`}- >- {t(ACTION_LABELS[a])}- </button>- ))}- </div>-- <textarea- value={instruction}- onChange={(e) => setInstruction(e.target.value)}- rows={4}- className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-sm text-[var(--foreground)] outline-none focus:border-[var(--primary)]"- placeholder={t("Describe how you want the text edited...")}- />-- <div className="grid grid-cols-2 gap-3">- <div>- <label className="mb-1 block text-[10px] font-medium uppercase tracking-wider text-[var(--muted-foreground)]">- {t("Source")}- </label>- <select- value={source}- onChange={(e) =>- setSource(e.target.value as SourceOption)- }- className="w-full rounded-md border border-[var(--border)] bg-[var(--background)] px-2 py-1.5 text-xs text-[var(--foreground)] outline-none focus:border-[var(--primary)]"- >- <option value="none">{t("None")}</option>- <option value="rag">{t("Knowledge Base")}</option>- <option value="web">{t("Web Search")}</option>- </select>- </div>- <div>- <label className="mb-1 block text-[10px] font-medium uppercase tracking-wider text-[var(--muted-foreground)]">- {t("Knowledge Base")}- </label>- <select- value={kbName}- onChange={(e) => setKbName(e.target.value)}- disabled={source !== "rag"}- className="w-full rounded-md border border-[var(--border)] bg-[var(--background)] px-2 py-1.5 text-xs text-[var(--foreground)] outline-none focus:border-[var(--primary)] disabled:cursor-not-allowed disabled:opacity-40"- >- <option value="">{t("Select...")}</option>- {knowledgeBases.map((k) => (- <option key={k.name} value={k.name}>- {k.name}- </option>- ))}- </select>- </div>- </div>- </div>-- <div className="flex justify-end gap-2 border-t border-[var(--border)] px-4 py-3">- <button- onClick={applyAutoMark}- disabled={isEditing || isAutoMarking}- className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] px-3 py-1.5 text-xs font-medium text-[var(--foreground)] transition-colors hover:bg-[var(--muted)] disabled:opacity-50"- >- {isAutoMarking ? (- <Loader2 size={13} className="animate-spin" />- ) : (- <Highlighter size={13} />- )}- {t("Auto Mark")}- </button>- <button- onClick={applyEdit}- disabled={isEditing || isAutoMarking}- className="inline-flex items-center gap-1.5 rounded-md bg-[var(--primary)] px-3 py-1.5 text-xs font-medium text-white transition-opacity disabled:opacity-50"- >- {isEditing ? (- <Loader2 size={13} className="animate-spin" />- ) : (- <ArrowRight size={13} />- )}- {t("Apply")}- </button>- </div>- </div>- </div>- )}-- <SaveToNotebookModal- open={showSaveModal}- payload={notebookSavePayload}- onClose={() => setShowSaveModal(false)}- onSaved={() => setStatus(t("Added to notebook."))}- />+ )}+ </main></div>);}--function ToolbarIconBtn({- title,- onClick,- children,-}: {- title: string;- onClick: () => void;- children: React.ReactNode;-}) {- return (- <button- title={title}- onClick={onClick}- className="inline-flex h-8 w-8 items-center justify-center rounded-md text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"- >- {children}- </button>- );-}diff --git a/web/app/(workspace)/co-writer/sampleTemplate.ts b/web/app/(workspace)/co-writer/sampleTemplate.tsindex 4f08e267b..b19472765 100644--- a/web/app/(workspace)/co-writer/sampleTemplate.ts+++ b/web/app/(workspace)/co-writer/sampleTemplate.ts@@ -107,8 +107,7 @@ ${FENCE}json"default_capability": "chat","enabled_tools": ["rag", "web_search", "code_execution", "reason"],"ui": {- "co_writer_template": true,- "notebook_export": true+ "co_writer_template": true}}${FENCE}@@ -136,14 +135,14 @@ ${FENCE}1. Draft a concept note2. Ask AI to refine it-3. Save it to a notebook+3. Export the polished markdown### TablesFeature | Description------------- | -------------Co-Writer | Draft and refine Markdown content-Notebook | Save and organize outputs+Chat | Ask questions and iterate ideasResearch | Build structured multi-step reports| Capability | Primary Use Case |@@ -191,7 +190,7 @@ ${FENCE}${FENCE}seqStudent->DeepTutor: Ask for help-DeepTutor->Notebook: Load context+DeepTutor->KnowledgeBase: Load contextNote right of DeepTutor: Collect memory\nand relevant knowledgeDeepTutor-->Student: Return guided responseStudent->>DeepTutor: Request rewrite in co-writerdiff --git a/web/app/layout.tsx b/web/app/layout.tsxindex 6b5614cc1..59cc160bf 100644--- a/web/app/layout.tsx+++ b/web/app/layout.tsx@@ -20,6 +20,13 @@ const fontSerif = Lora({export const metadata: Metadata = {title: "DeepTutor",description: "Agent-native intelligent learning companion",+ icons: {+ icon: [+ { url: "/favicon-16x16.png", sizes: "16x16", type: "image/png" },+ { url: "/favicon-32x32.png", sizes: "32x32", type: "image/png" },+ ],+ apple: "/apple-touch-icon.png",+ },};export default function RootLayout({diff --git a/web/components/notebook/SaveToNotebookModal.tsx b/web/components/notebook/SaveToNotebookModal.tsxindex 3ce82dd37..b245e21fd 100644--- a/web/components/notebook/SaveToNotebookModal.tsx+++ b/web/components/notebook/SaveToNotebookModal.tsx@@ -13,7 +13,6 @@ type RecordType =| "solve"| "question"| "research"- | "co_writer"| "chat";export interface NotebookSavePayload {diff --git a/web/components/sidebar/BookRecent.tsx b/web/components/sidebar/BookRecent.tsxindex 45f174278..7fef5838e 100644--- a/web/components/sidebar/BookRecent.tsx+++ b/web/components/sidebar/BookRecent.tsx@@ -2,7 +2,6 @@import Link from "next/link";import { useEffect, useState } from "react";-import { Library } from "lucide-react";import { apiUrl } from "@/lib/api";interface RecentBook {@@ -68,28 +67,7 @@ export function BookRecent({ collapsed = false, limit = 4 }: BookRecentProps) {if (books.length === 0) return null;- if (collapsed) {- return (- <div className="flex flex-col items-center gap-0.5 pb-0.5 pt-px">- {books.map((book) => {- const dot = STATUS_DOT[book.status] || "bg-[var(--muted-foreground)]/30";- return (- <Link- key={book.id}- href={`/book?book=${encodeURIComponent(book.id)}`}- title={book.title || "Untitled book"}- className="relative rounded-md p-1.5 text-[var(--muted-foreground)]/70 transition-colors hover:bg-[var(--background)]/50 hover:text-[var(--foreground)]"- >- <Library size={12} strokeWidth={1.5} />- <span- className={`absolute right-0.5 top-0.5 h-1.5 w-1.5 rounded-full ${dot} ring-1 ring-[var(--secondary)]`}- />- </Link>- );- })}- </div>- );- }+ if (collapsed) return null;return (<div className="ml-5 border-l border-[var(--border)]/30 py-1">diff --git a/web/components/sidebar/CoWriterRecent.tsx b/web/components/sidebar/CoWriterRecent.tsxnew file mode 100644index 000000000..65eb343a4--- /dev/null+++ b/web/components/sidebar/CoWriterRecent.tsx@@ -0,0 +1,74 @@+"use client";++import Link from "next/link";+import { usePathname } from "next/navigation";+import { useCallback, useEffect, useRef, useState } from "react";+import { listCoWriterDocuments, type CoWriterDocumentSummary } from "@/lib/co-writer-api";+import { subscribeCoWriterChanges } from "@/lib/co-writer-events";++function relativeTime(seconds: number): string {+ if (!seconds || Number.isNaN(seconds)) return "";+ const diff = Date.now() / 1000 - seconds;+ if (diff < 60) return "now";+ const mins = Math.floor(diff / 60);+ if (mins < 60) return `${mins}m`;+ const hrs = Math.floor(mins / 60);+ if (hrs < 24) return `${hrs}h`;+ const days = Math.floor(hrs / 24);+ return `${days}d`;+}++interface CoWriterRecentProps {+ collapsed?: boolean;+ limit?: number;+}++export function CoWriterRecent({ collapsed = false, limit = 4 }: CoWriterRecentProps) {+ const [docs, setDocs] = useState<CoWriterDocumentSummary[]>([]);+ const pathname = usePathname();+ const limitRef = useRef(limit);+ limitRef.current = limit;++ const refresh = useCallback(async () => {+ try {+ const items = await listCoWriterDocuments();+ setDocs(items.slice(0, limitRef.current));+ } catch {+ /* ignore */+ }+ }, []);++ useEffect(() => {+ void refresh();+ }, [refresh, pathname]);++ useEffect(() => {+ return subscribeCoWriterChanges(() => {+ void refresh();+ });+ }, [refresh]);++ if (docs.length === 0) return null;++ if (collapsed) return null;++ return (+ <div className="ml-5 border-l border-[var(--border)]/30 py-1">+ {docs.map((doc) => (+ <Link+ key={doc.id}+ href={`/co-writer/${encodeURIComponent(doc.id)}`}+ className="group flex items-center gap-2 rounded-r-lg py-1 pl-3 pr-2 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--background)]/40 hover:text-[var(--foreground)]"+ >+ <span className="block h-1.5 w-1.5 shrink-0 rounded-full bg-[var(--muted-foreground)]/30" />+ <span className="min-w-0 flex-1 truncate text-[13px]">+ {doc.title || "Untitled draft"}+ </span>+ <span className="shrink-0 text-[10px] tabular-nums text-[var(--muted-foreground)]/40">+ {relativeTime(Number(doc.updated_at) || 0)}+ </span>+ </Link>+ ))}+ </div>+ );+}diff --git a/web/components/sidebar/SidebarShell.tsx b/web/components/sidebar/SidebarShell.tsxindex 172e64a29..2b7e3a4b2 100644--- a/web/components/sidebar/SidebarShell.tsx+++ b/web/components/sidebar/SidebarShell.tsx@@ -3,7 +3,8 @@import Image from "next/image";import Link from "next/link";import { usePathname, useRouter } from "next/navigation";-import { useState, type ReactNode } from "react";+import { type ReactNode } from "react";+import { useAppShell } from "@/context/AppShellContext";import {BookOpen,Bot,@@ -21,6 +22,7 @@ import { useTranslation } from "react-i18next";import SessionList from "@/components/SessionList";import { TutorBotRecent } from "@/components/sidebar/TutorBotRecent";import { BookRecent } from "@/components/sidebar/BookRecent";+import { CoWriterRecent } from "@/components/sidebar/CoWriterRecent";import type { SessionSummary } from "@/lib/session-api";interface NavEntry {@@ -69,7 +71,7 @@ export function SidebarShell({const pathname = usePathname();const router = useRouter();const { t } = useTranslation();- const [collapsed, setCollapsed] = useState(false);+ const { sidebarCollapsed: collapsed, setSidebarCollapsed: setCollapsed } = useAppShell();const handleNewChat = () => {if (onNewChat) {@@ -82,62 +84,90 @@ export function SidebarShell({/* ---- Collapsed state ---- */if (collapsed) {return (- <aside className="flex w-[56px] h-screen shrink-0 flex-col items-center bg-[var(--secondary)] py-3 transition-all duration-200">- <button- onClick={() => setCollapsed(false)}- className="mb-4 rounded-md p-1.5 text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"- aria-label={t("Expand sidebar")}- >- <PanelLeftOpen size={15} />- </button>+ <aside className="group/sb relative flex h-screen w-[60px] shrink-0 flex-col items-center bg-[var(--secondary)] py-3 transition-all duration-200">+ {/* Header: logo + collapse toggle (toggle replaces logo on hover) */}+ <div className="relative mb-2 flex h-9 w-9 items-center justify-center">+ <Link+ href="/"+ aria-label="DeepTutor"+ className="flex items-center justify-center transition-opacity duration-150 group-hover/sb:opacity-0"+ >+ <Image+ src="/logo-ver2.png"+ alt="DeepTutor"+ width={22}+ height={22}+ className="rounded-md"+ />+ </Link>+ <button+ onClick={() => setCollapsed(false)}+ className="absolute inset-0 flex items-center justify-center rounded-lg text-[var(--muted-foreground)] opacity-0 transition-all duration-150 hover:bg-[var(--background)]/60 hover:text-[var(--foreground)] group-hover/sb:opacity-100"+ aria-label={t("Expand sidebar")}+ >+ <PanelLeftOpen size={16} />+ </button>+ </div>+ {/* New chat — visually distinct circular button */}<buttononClick={handleNewChat}- className="mb-3 rounded-lg p-2 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--background)]/60 hover:text-[var(--foreground)]"+ title={t("New Chat") as string}+ className="mb-2 flex h-9 w-9 items-center justify-center rounded-xl border border-[var(--border)]/50 bg-[var(--background)]/40 text-[var(--foreground)] shadow-sm transition-all duration-150 hover:border-[var(--border)] hover:bg-[var(--background)]/80"aria-label={t("New Chat")}>- <Plus size={16} strokeWidth={2} />+ <Plus size={16} strokeWidth={2.2} /></button>- <nav className="flex flex-col items-center gap-px pt-1">+ {/* Subtle divider */}+ <div className="my-1.5 h-px w-7 bg-[var(--border)]/40" />++ {/* Primary nav */}+ <nav className="flex w-full flex-col items-center gap-1 px-1.5">{PRIMARY_NAV.map((item) => {const active = pathname.startsWith(item.href);return (- <div key={item.href} className="flex flex-col items-center">- <Link- href={item.href}- className={`rounded-lg p-2 transition-colors ${- active- ? "bg-[var(--background)]/70 text-[var(--foreground)]"- : "text-[var(--muted-foreground)] hover:bg-[var(--background)]/50 hover:text-[var(--foreground)]"- }`}- >- <item.icon size={16} strokeWidth={active ? 1.9 : 1.5} />- </Link>- {item.href === "/agents" && <TutorBotRecent collapsed />}- {item.href === "/book" && <BookRecent collapsed />}-- </div>+ <Link+ key={item.href}+ href={item.href}+ title={t(item.label) as string}+ className={`relative flex h-9 w-9 items-center justify-center rounded-xl transition-all duration-150 ${+ active+ ? "bg-[var(--background)]/80 text-[var(--foreground)] shadow-sm"+ : "text-[var(--muted-foreground)] hover:bg-[var(--background)]/50 hover:text-[var(--foreground)]"+ }`}+ >+ {active && (+ <span className="absolute -left-1.5 top-1/2 h-5 w-[3px] -translate-y-1/2 rounded-full bg-[var(--foreground)]/80" />+ )}+ <item.icon size={18} strokeWidth={active ? 2 : 1.6} />+ </Link>);})}</nav><div className="flex-1" />- <div className="flex flex-col items-center gap-px pb-1">+ {/* Secondary nav + footer */}+ <div className="flex w-full flex-col items-center gap-1 px-1.5">+ <div className="my-1 h-px w-7 bg-[var(--border)]/40" />{SECONDARY_NAV.map((item) => {const active = pathname.startsWith(item.href);return (<Linkkey={item.href}href={item.href}- className={`rounded-lg p-2 transition-colors ${+ title={t(item.label) as string}+ className={`relative flex h-9 w-9 items-center justify-center rounded-xl transition-all duration-150 ${active- ? "bg-[var(--background)]/70 text-[var(--foreground)]"+ ? "bg-[var(--background)]/80 text-[var(--foreground)] shadow-sm": "text-[var(--muted-foreground)] hover:bg-[var(--background)]/50 hover:text-[var(--foreground)]"}`}>- <item.icon size={16} strokeWidth={active ? 1.9 : 1.5} />+ {active && (+ <span className="absolute -left-1.5 top-1/2 h-5 w-[3px] -translate-y-1/2 rounded-full bg-[var(--foreground)]/80" />+ )}+ <item.icon size={18} strokeWidth={active ? 2 : 1.6} /></Link>);})}@@ -190,6 +220,7 @@ export function SidebarShell({const hasSessionsBelow = item.href === "/chat" && showSessions && onSelectSession && onRenameSession && onDeleteSession;const hasBots = item.href === "/agents";const hasBooks = item.href === "/book";+ const hasCoWriterDocs = item.href === "/co-writer";return (<div key={item.href}><Link@@ -217,6 +248,7 @@ export function SidebarShell({</div>)}{hasBots && <TutorBotRecent />}+ {hasCoWriterDocs && <CoWriterRecent />}{hasBooks && <BookRecent />}</div>);diff --git a/web/components/sidebar/TutorBotRecent.tsx b/web/components/sidebar/TutorBotRecent.tsxindex 5db00c20c..1266763d1 100644--- a/web/components/sidebar/TutorBotRecent.tsx+++ b/web/components/sidebar/TutorBotRecent.tsx@@ -2,7 +2,6 @@import Link from "next/link";import { useEffect, useState } from "react";-import { Bot } from "lucide-react";import { apiUrl } from "@/lib/api";interface RecentBot {@@ -44,25 +43,7 @@ export function TutorBotRecent({ collapsed = false }: { collapsed?: boolean }) {if (bots.length === 0) return null;- if (collapsed) {- return (- <div className="flex flex-col items-center gap-0.5 pb-0.5 pt-px">- {bots.map((bot) => (- <Link- key={bot.bot_id}- href={`/agents/${bot.bot_id}/chat`}- title={bot.name}- className="relative rounded-md p-1.5 text-[var(--muted-foreground)]/70 transition-colors hover:bg-[var(--background)]/50 hover:text-[var(--foreground)]"- >- <Bot size={12} strokeWidth={1.5} />- {bot.running && (- <span className="absolute right-0.5 top-0.5 h-1.5 w-1.5 rounded-full bg-emerald-400 ring-1 ring-[var(--secondary)]" />- )}- </Link>- ))}- </div>- );- }+ if (collapsed) return null;return (<div className="ml-5 border-l border-[var(--border)]/30 py-1">diff --git a/web/context/AppShellContext.tsx b/web/context/AppShellContext.tsxindex f40fcd635..c72a2bf32 100644--- a/web/context/AppShellContext.tsx+++ b/web/context/AppShellContext.tsx@@ -20,9 +20,11 @@ export type AppLanguage = "en" | "zh";export const ACTIVE_SESSION_STORAGE_KEY = "deeptutor.activeSessionId.tab";export const LANGUAGE_STORAGE_KEY = "deeptutor-language";+export const SIDEBAR_COLLAPSED_STORAGE_KEY = "deeptutor.sidebarCollapsed";const ACTIVE_SESSION_EVENT = "deeptutor:active-session";const LANGUAGE_EVENT = "deeptutor:language";+const SIDEBAR_COLLAPSED_EVENT = "deeptutor:sidebar-collapsed";function normalizeLanguage(value: string | null | undefined): AppLanguage {return value === "zh" ? "zh" : "en";@@ -60,6 +62,29 @@ export function readStoredActiveSessionId(): string | null {}}+export function readStoredSidebarCollapsed(): boolean {+ if (typeof window === "undefined") return false;+ try {+ return window.localStorage.getItem(SIDEBAR_COLLAPSED_STORAGE_KEY) === "1";+ } catch {+ return false;+ }+}++export function writeStoredSidebarCollapsed(collapsed: boolean): void {+ if (typeof window === "undefined") return;+ try {+ window.localStorage.setItem(SIDEBAR_COLLAPSED_STORAGE_KEY, collapsed ? "1" : "0");+ window.dispatchEvent(+ new CustomEvent(SIDEBAR_COLLAPSED_EVENT, {+ detail: { collapsed },+ }),+ );+ } catch {+ // localStorage may be unavailable+ }+}+export function writeStoredActiveSessionId(sessionId: string | null): void {if (typeof window === "undefined") return;try {@@ -85,6 +110,8 @@ interface AppShellContextValue {setLanguage: (language: AppLanguage) => void;activeSessionId: string | null;setActiveSessionId: (sessionId: string | null) => void;+ sidebarCollapsed: boolean;+ setSidebarCollapsed: (collapsed: boolean) => void;}const AppShellContext = createContext<AppShellContextValue | null>(null);@@ -102,9 +129,12 @@ export function AppShellProvider({const [activeSessionId, setActiveSessionIdState] = useState<string | null>(() =>readStoredActiveSessionId(),);+ // Always start expanded to match SSR; hydrate from localStorage after mount+ const [sidebarCollapsed, setSidebarCollapsedState] = useState<boolean>(false);useEffect(() => {setLanguageState(readStoredLanguage());+ setSidebarCollapsedState(readStoredSidebarCollapsed());}, []);useEffect(() => {@@ -123,6 +153,9 @@ export function AppShellProvider({if (event.key === ACTIVE_SESSION_STORAGE_KEY) {setActiveSessionIdState(event.newValue);}+ if (event.key === SIDEBAR_COLLAPSED_STORAGE_KEY) {+ setSidebarCollapsedState(event.newValue === "1");+ }};const onLanguage = (event: Event) => {@@ -135,14 +168,21 @@ export function AppShellProvider({setActiveSessionIdState(detail?.sessionId ?? null);};+ const onSidebarCollapsed = (event: Event) => {+ const detail = (event as CustomEvent<{ collapsed?: boolean }>).detail;+ setSidebarCollapsedState(Boolean(detail?.collapsed));+ };+window.addEventListener("storage", onStorage);window.addEventListener(LANGUAGE_EVENT, onLanguage);window.addEventListener(ACTIVE_SESSION_EVENT, onActiveSession);+ window.addEventListener(SIDEBAR_COLLAPSED_EVENT, onSidebarCollapsed);return () => {window.removeEventListener("storage", onStorage);window.removeEventListener(LANGUAGE_EVENT, onLanguage);window.removeEventListener(ACTIVE_SESSION_EVENT, onActiveSession);+ window.removeEventListener(SIDEBAR_COLLAPSED_EVENT, onSidebarCollapsed);};}, []);@@ -161,6 +201,11 @@ export function AppShellProvider({setActiveSessionIdState(sessionId);}, []);+ const setSidebarCollapsed = useCallback((collapsed: boolean) => {+ writeStoredSidebarCollapsed(collapsed);+ setSidebarCollapsedState(collapsed);+ }, []);+const value = useMemo<AppShellContextValue>(() => ({theme,@@ -169,8 +214,19 @@ export function AppShellProvider({setLanguage,activeSessionId,setActiveSessionId,+ sidebarCollapsed,+ setSidebarCollapsed,}),- [activeSessionId, language, setActiveSessionId, setLanguage, setTheme, theme],+ [+ activeSessionId,+ language,+ setActiveSessionId,+ setLanguage,+ setSidebarCollapsed,+ setTheme,+ sidebarCollapsed,+ theme,+ ],);return (diff --git a/web/lib/co-writer-api.ts b/web/lib/co-writer-api.tsnew file mode 100644index 000000000..5c946b597--- /dev/null+++ b/web/lib/co-writer-api.ts@@ -0,0 +1,78 @@+import { apiUrl } from "@/lib/api";++const BASE = "/api/v1/co_writer";++export interface CoWriterDocumentSummary {+ id: string;+ title: string;+ created_at: number;+ updated_at: number;+ preview: string;+}++export interface CoWriterDocument {+ id: string;+ title: string;+ content: string;+ created_at: number;+ updated_at: number;+}++async function jsonOrThrow<T>(res: Response): Promise<T> {+ if (!res.ok) {+ const text = await res.text().catch(() => "");+ throw new Error(`Request failed (${res.status}): ${text || res.statusText}`);+ }+ return res.json() as Promise<T>;+}++export async function listCoWriterDocuments(): Promise<CoWriterDocumentSummary[]> {+ const res = await fetch(apiUrl(`${BASE}/documents`), { cache: "no-store" });+ const data = await jsonOrThrow<{ documents: CoWriterDocumentSummary[] }>(res);+ return Array.isArray(data?.documents) ? data.documents : [];+}++export async function createCoWriterDocument(payload?: {+ title?: string;+ content?: string;+}): Promise<CoWriterDocument> {+ const res = await fetch(apiUrl(`${BASE}/documents`), {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ title: payload?.title ?? null,+ content: payload?.content ?? "",+ }),+ });+ return jsonOrThrow<CoWriterDocument>(res);+}++export async function getCoWriterDocument(docId: string): Promise<CoWriterDocument> {+ const res = await fetch(apiUrl(`${BASE}/documents/${encodeURIComponent(docId)}`), {+ cache: "no-store",+ });+ return jsonOrThrow<CoWriterDocument>(res);+}++export async function updateCoWriterDocument(+ docId: string,+ payload: { title?: string | null; content?: string | null },+): Promise<CoWriterDocument> {+ const res = await fetch(apiUrl(`${BASE}/documents/${encodeURIComponent(docId)}`), {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ title: payload.title ?? null,+ content: payload.content ?? null,+ }),+ });+ return jsonOrThrow<CoWriterDocument>(res);+}++export async function deleteCoWriterDocument(docId: string): Promise<boolean> {+ const res = await fetch(apiUrl(`${BASE}/documents/${encodeURIComponent(docId)}`), {+ method: "DELETE",+ });+ const data = await jsonOrThrow<{ deleted: boolean }>(res);+ return Boolean(data?.deleted);+}diff --git a/web/lib/co-writer-events.ts b/web/lib/co-writer-events.tsnew file mode 100644index 000000000..a26fe7a6e--- /dev/null+++ b/web/lib/co-writer-events.ts@@ -0,0 +1,28 @@+// Lightweight client-side event bus for Co-Writer document mutations.+//+// `CoWriterRecent` (sidebar) and the home page list need to refresh whenever a+// document is created, updated (autosave), or deleted from anywhere in the+// app. We avoid a full Context provider here because the sidebar lives at the+// workspace shell level and mutations happen in disparate routes.++const EVENT_NAME = "co-writer:changed";++type Listener = () => void;++function getTarget(): EventTarget | null {+ if (typeof window === "undefined") return null;+ return window;+}++export function notifyCoWriterChanged(): void {+ const target = getTarget();+ if (!target) return;+ target.dispatchEvent(new Event(EVENT_NAME));+}++export function subscribeCoWriterChanges(listener: Listener): () => void {+ const target = getTarget();+ if (!target) return () => {};+ target.addEventListener(EVENT_NAME, listener);+ return () => target.removeEventListener(EVENT_NAME, listener);+}diff --git a/web/lib/notebook-api.ts b/web/lib/notebook-api.tsindex cfa297aa5..a6805ad5b 100644--- a/web/lib/notebook-api.ts+++ b/web/lib/notebook-api.ts@@ -11,7 +11,6 @@ export type NotebookRecordType =| "solve"| "question"| "research"- | "co_writer"| "chat";export interface NotebookSummary {diff --git a/web/lib/notebook-selection-types.ts b/web/lib/notebook-selection-types.tsindex 084fea73c..012cde27f 100644--- a/web/lib/notebook-selection-types.ts+++ b/web/lib/notebook-selection-types.ts@@ -30,8 +30,6 @@ export function getTypeColor(type: string): string {return "bg-purple-100 text-purple-700 border-purple-200";case "research":return "bg-emerald-100 text-emerald-700 border-emerald-200";- case "co_writer":- return "bg-amber-100 text-amber-700 border-amber-200";case "chat":return "bg-cyan-100 text-cyan-700 border-cyan-200";default:diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex c1555c467..dd303dd28 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -331,7 +331,6 @@"Close": "Close","messages": "messages","Failed to load session": "Failed to load session",- "Add to Notebook": "Add to Notebook","Added Successfully!": "Added Successfully!","Record Preview": "Record Preview","Select Notebooks": "Select Notebooks",@@ -710,7 +709,6 @@"Applied AI edit to the selection.": "Applied AI edit to the selection.","Applied {{action}} to the full draft.": "Applied {{action}} to the full draft.","Applied auto-mark annotations.": "Applied auto-mark annotations.",- "Added to notebook.": "Added to notebook.","Please select a text passage first.": "Please select a text passage first.","Please enter an instruction or choose a mode.": "Please enter an instruction or choose a mode.","Please enter an editing instruction first.": "Please enter an editing instruction first.",diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex 1ae4195d1..37489e6de 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -331,7 +331,6 @@"Close": "关闭","messages": "条消息","Failed to load session": "加载会话失败",- "Add to Notebook": "保存到笔记本","Added Successfully!": "保存成功!","Record Preview": "记录预览","Select Notebooks": "选择笔记本",@@ -754,7 +753,6 @@"Applied AI edit to the selection.": "已将 AI 编辑应用到所选内容。","Applied {{action}} to the full draft.": "已对全文草稿执行{{action}}。","Applied auto-mark annotations.": "已应用自动批注。",- "Added to notebook.": "已添加到笔记本。","Please select a text passage first.": "请先选择一段文本。","Please enter an instruction or choose a mode.": "请输入指令或选择一种模式。","Please enter an editing instruction first.": "请先输入编辑指令。",diff --git a/web/public/apple-touch-icon.png b/web/public/apple-touch-icon.pngnew file mode 100644index 000000000..c5ce0928aBinary files /dev/null and b/web/public/apple-touch-icon.png differdiff --git a/web/public/favicon-16x16.png b/web/public/favicon-16x16.pngnew file mode 100644index 000000000..1d4027bf5Binary files /dev/null and b/web/public/favicon-16x16.png differdiff --git a/web/public/favicon-32x32.png b/web/public/favicon-32x32.pngnew file mode 100644index 000000000..d1dccdb04Binary files /dev/null and b/web/public/favicon-32x32.png differdiff --git a/web/scripts/route_budgets.mjs b/web/scripts/route_budgets.mjsindex 7e7c41e6d..5df2beb63 100644--- a/web/scripts/route_budgets.mjs+++ b/web/scripts/route_budgets.mjs@@ -8,7 +8,8 @@ const APP_OUTPUT_DIR = path.resolve(".next");const ROUTE_BUDGETS_KB = {"/": 700,"/playground": 700,- "/co-writer": 700,+ "/co-writer": 200,+ "/co-writer/[docId]": 700,"/knowledge": 450,"/memory": 450,"/settings": 180,