DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
chore: prepare v1.2.5 release
Bingxi Zhao (Frank)64284580492a
diff --git a/.env.example b/.env.exampleindex 8f3231b7f..8b1b6a664 100644--- a/.env.example+++ b/.env.example@@ -73,3 +73,16 @@ NEXT_PUBLIC_API_BASE=# --------------------------------------------# Keep this false in production.DISABLE_SSL_VERIFY=false++# --------------------------------------------+# Chat Attachments (Optional)+# --------------------------------------------+# Where the chat turn runtime persists user-uploaded files (PDF, DOCX,+# images, …) so the preview drawer can re-fetch the originals after the+# in-memory base64 is dropped.+#+# Defaults to <project>/data/user/workspace/chat/attachments, which is+# already mounted as a volume in docker-compose.yml — leave unset for the+# default Docker / Linux deployment. Override only when running multiple+# backend instances against shared storage (e.g. NFS).+CHAT_ATTACHMENT_DIR=diff --git a/README.md b/README.mdindex 00ae57e38..b52b95ab6 100644--- a/README.md+++ b/README.md@@ -28,6 +28,8 @@### 📦 Releases+> **[2026.4.25]** [v1.2.5](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.5) — Persistent chat attachment storage with preview/download URLs, right-side file preview drawer for PDF/images/SVG/Markdown/code/Office text, broader code-file attachment coverage, attachment-aware Deep Solve/Question/Research/Visualize pipelines, TutorBot save-to-notebook and Markdown export, Setup Tour diagnostics, and auto-scroll/upload-picker fixes.+> **[2026.4.25]** [v1.2.4](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.4) — Text/code/SVG chat attachments, one-command Setup Tour with dependency installation, `uv pip` and Windows npm fixes, Markdown chat export, compact Knowledge Base management UI, Polish README, theme/popover polish, and release/update-version hardening.> **[2026.4.24]** [v1.2.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.3) — Document attachments in chat (PDF/DOCX/XLSX/PPTX), reasoning model thinking-block display, tri-state embedding `send_dimensions` toggle, LLM provider core refactor, Soul template editor, Co-Writer save-to-notebook, Knowledge Base drag-and-drop upload & delete resilience, and question generation language fidelity.diff --git a/assets/releases/ver1-2-5.md b/assets/releases/ver1-2-5.mdnew file mode 100644index 000000000..bce2c36bf--- /dev/null+++ b/assets/releases/ver1-2-5.md@@ -0,0 +1,63 @@+# DeepTutor v1.2.5 Release Notes++**Release Date:** 2026.04.25++## Highlights++### Attachment Store and File Preview Drawer+Chat attachments are now persisted as first-class session artifacts instead of living only as inline base64 blobs in message rows. The turn runtime writes every uploaded file to a new attachment store before document extraction, records a stable URL on the message, and drops the bulky base64 payload from persisted chat history.++- **Backend attachment store** — `deeptutor/services/storage/attachment_store.py` introduces a pluggable `AttachmentStore` protocol and a default `LocalDiskAttachmentStore` rooted at `data/user/workspace/chat/attachments`. The path can be overridden with `CHAT_ATTACHMENT_DIR`, documented in `.env.example`.+- **Safe attachment serving** — a new `/api/attachments/{session_id}/{attachment_id}/{filename}` router serves stored files with traversal-safe path resolution, atomic writes on upload, inline `Content-Disposition`, UTF-8 filename handling, and private no-cache headers.+- **Stable attachment metadata** — `Attachment` now carries an `id` plus `extracted_text`; `TurnRuntimeManager` generates missing IDs, persists original bytes, stores the preview URL, and keeps extracted text from Office/text documents so the UI can show exactly what the assistant read.+- **Right-side preview drawer** — `FilePreviewDrawer` adds a Claude-style side panel for chat files. On desktop it squeezes the chat column; on smaller screens it overlays. The shell stays mounted for instant open/close, while heavy preview bodies are deferred until after the slide animation to avoid jank.+- **Preview renderers** — PDFs render in the browser viewer, images and SVGs render with native `<img>`, Markdown reuses the main Markdown renderer, code/text files use `RichCodeBlock` with syntax highlighting, Office files show backend-extracted plain text, and unsupported/legacy files fall back to a download card.+- **Attachment actions** — pending composer chips and sent message cards are clickable, with keyboard focus rings, download, copy-link, Escape-to-close, and graceful "legacy file not stored" messaging for old sessions.++### Broader Code and Text Attachment Coverage+The v1.2.4 text/code attachment support has been widened substantially, keeping the backend RAG router, chat extractor, frontend upload allowlist, icons, and preview highlighter aligned.++- **More accepted formats** — `FileTypeRouter.TEXT_EXTENSIONS` and `TEXT_LIKE_EXTS` now include JSONC/JSON5, MJS/CJS/MTS/CTS, Vue/Svelte, Kotlin scripts, Groovy/Gradle, C#/Zig/Nim, Objective-C, Perl/Lua/Julia/Dart, Haskell/Clojure/Elixir/Erlang/OCaml/F#, Lisp/Scheme/Racket, Solidity, fish/vim, GraphQL/protobuf, CMake/Makefile, Terraform/HCL, nginx config, and Dockerfile-style files.+- **Central syntax mapping** — `web/lib/code-languages.ts` maps extensions and special filenames (`Dockerfile`, `Makefile`, `CMakeLists.txt`, dotfiles, etc.) to Prism language names so preview classification and code highlighting stay in sync.+- **Frontend helpers exported** — `extOf()` is now exported from `web/lib/doc-attachments.ts` for the preview pipeline, and document icons/categories were expanded to match the new extension set.++### Attachment-Aware Deep Capabilities+Uploaded attachments now flow into more agent pipelines, not just the default chat stage.++- **Base agent parity** — non-streaming LLM calls now use the same `prepare_multimodal_messages()` path as streaming calls when attachments are present, including image stripping/logging for non-vision models.+- **Deep Solve** — instead of extracting only the first image URL, `DeepSolveCapability` forwards image attachments through `MainSolver` into planner, solver, and replan calls, so multimodal problems remain visible throughout the Plan-ReAct-Write loop.+- **Deep Question** — topic generation and follow-up answering pass attachments to the underlying agents. Mimic mode can now use `[Attached Documents]` text directly when uploaded PDFs have already been extracted and stripped from base64 storage.+- **Deep Research** — research planning accepts attachments and forwards them into the first planning LLM call, whether that is rephrase or decompose, without duplicating the same image/file context in later planning turns.+- **Visualize** — visualization analysis now receives chat attachments, enabling diagrams or screenshots to influence render-type selection and data extraction.++### TutorBot Export and Notebook Capture+TutorBot chat sessions now have the same capture paths as regular chat:++- The Agent chat page adds **Save to Notebook** and **Download Markdown** actions in the header.+- `SaveToNotebookModal`, `notebook-api`, backend notebook request types, and `RecordType` now recognize a new `tutorbot` record type.+- The Knowledge page displays TutorBot notebook entries with their own violet badge and bot icon.+- Restored TutorBot chat history now re-snaps to the bottom across multiple frames so Markdown/KaTeX growth after first paint does not leave the user above the latest message.++### Setup Tour Diagnostics and Install Robustness+The guided setup tour now explains dependency failures instead of failing silently:++- Bootstrap dependency installation captures stdout/stderr and prints the real pip error plus a manual retry command.+- `uv` resolution checks common install locations (`~/.local/bin`, `~/.cargo/bin`, Homebrew paths) before attempting installation, and reports clear next steps if `uv` installs successfully but is still not on `PATH`.+- `uv` install failures now show localized English/Chinese hints for Python wheel availability, stale shell `PATH`, PyPI mirror issues, and direct installer options.+- Node.js/npm version checks resolve executables through `shutil.which()` before running `--version`, improving Windows `.cmd`/`.bat` compatibility after Python subprocess hardening.++### Chat and Knowledge UX Fixes+- **Auto-scroll reliability** — `useChatAutoScroll` now waits for message content before attaching its mutation observer, fixing missed bottom-scroll behavior when reopening sessions whose message container was initially empty.+- **Preview animation polish** — `globals.css` adds a `chat-preview-shell` transition so the drawer slide and chat-column squeeze move together at the same 220 ms timing.+- **Knowledge upload picker** — KB file inputs no longer rely on the browser/OS `accept` filter, which could hide valid files on some systems; in-app validation still enforces the supported-file policy after selection.+- **Localized preview copy** — English and Chinese strings were added for preview loading, copy link, unavailable previews, legacy files, remove attachment, and Office extracted-text explanation.++### Test Suite Expansion+- **Capability attachment forwarding** — `tests/core/test_capabilities_runtime.py` adds coverage for Deep Solve, Deep Question, Deep Research, and Visualize attachment propagation, including mimic mode with extracted document text.+- **Research planning edge case** — `tests/agents/research/test_research_pipeline_rag.py` verifies that attachments are forwarded to decompose when rephrase is enabled but performs zero iterations, ensuring the first actual planning LLM call still sees the uploaded context.++## Community Contributions++No external community PRs were included in this release window; this release focuses on core-team follow-up work after v1.2.4.++**Full Changelog**: https://github.com/HKUDS/DeepTutor/compare/v1.2.4...v1.2.5diff --git a/deeptutor/agents/base_agent.py b/deeptutor/agents/base_agent.pyindex 1ff9ee357..0e84bea34 100644--- a/deeptutor/agents/base_agent.py+++ b/deeptutor/agents/base_agent.py@@ -416,12 +416,25 @@ class BaseAgent(ABC):else:self.logger.debug(f"response_format not supported for {binding}/{model}, skipping")- if messages:- if attachments:- mm_result = prepare_multimodal_messages(- messages, attachments, binding=self.binding, model=model+ # Keep non-streaming calls aligned with stream_llm/chat: when images+ # are attached, convert the final user message to multimodal content.+ if attachments:+ if not messages:+ messages = [+ {"role": "system", "content": system_prompt},+ {"role": "user", "content": user_prompt},+ ]+ mm_result = prepare_multimodal_messages(+ messages, attachments, binding=self.binding, model=model+ )+ messages = mm_result.messages+ if mm_result.images_stripped:+ self.logger.info(+ "Images stripped for %s/%s – model does not support vision",+ self.binding,+ model,)- messages = mm_result.messages+ if messages:kwargs["messages"] = messages# Log inputdiff --git a/deeptutor/agents/question/agents/followup_agent.py b/deeptutor/agents/question/agents/followup_agent.pyindex b6c50665a..b5501bb2f 100644--- a/deeptutor/agents/question/agents/followup_agent.py+++ b/deeptutor/agents/question/agents/followup_agent.py@@ -29,6 +29,7 @@ class FollowupAgent(BaseAgent):user_message: str,question_context: dict[str, Any],history_context: str = "",+ attachments: list[Any] | None = None,) -> str:system_prompt = append_language_directive(self.get_prompt("system", ""),@@ -53,6 +54,7 @@ class FollowupAgent(BaseAgent):user_prompt=user_prompt,system_prompt=system_prompt,stage="followup_answer",+ attachments=attachments,trace_meta=build_trace_metadata(call_id=new_call_id(f"quiz-followup-{question_context.get('question_id', 'question')}"diff --git a/deeptutor/agents/question/agents/idea_agent.py b/deeptutor/agents/question/agents/idea_agent.pyindex df9e680d3..76e52b625 100644--- a/deeptutor/agents/question/agents/idea_agent.py+++ b/deeptutor/agents/question/agents/idea_agent.py@@ -48,6 +48,7 @@ class IdeaAgent(BaseAgent):target_question_type: str = "",existing_concentrations: list[str] | None = None,batch_number: int | None = None,+ attachments: list[Any] | None = None,) -> dict[str, Any]:"""Build grounded question templates in a single pass.@@ -78,6 +79,7 @@ class IdeaAgent(BaseAgent):],trace_id=trace_id,batch_number=batch_number,+ attachments=attachments,)return {"templates": templates,@@ -177,6 +179,7 @@ class IdeaAgent(BaseAgent):retrieval_queries: list[str] | None = None,trace_id: str = "ideation",batch_number: int | None = None,+ attachments: list[Any] | None = None,) -> list[QuestionTemplate]:system_prompt = append_language_directive(self.get_prompt("system", ""),@@ -218,6 +221,7 @@ class IdeaAgent(BaseAgent):system_prompt=system_prompt,response_format={"type": "json_object"},stage="idea_generate_templates",+ attachments=attachments,trace_meta=build_trace_metadata(call_id=new_call_id("quiz-ideation"),phase="ideation",diff --git a/deeptutor/agents/question/coordinator.py b/deeptutor/agents/question/coordinator.pyindex 231db4918..51447e51c 100644--- a/deeptutor/agents/question/coordinator.py+++ b/deeptutor/agents/question/coordinator.py@@ -111,6 +111,7 @@ class AgentCoordinator:difficulty: str = "",question_type: str = "",history_context: str = "",+ attachments: list[Any] | None = None,) -> dict[str, Any]:self._current_batch_dir = self._create_batch_dir("custom")requested = max(1, int(num_questions or 1))@@ -156,6 +157,7 @@ class AgentCoordinator:target_question_type=target_question_type,existing_concentrations=existing_concentrations,batch_number=batch_number,+ attachments=attachments,)batch_templates = idea_result.get("templates", [])if not isinstance(batch_templates, list):diff --git a/deeptutor/agents/research/agents/decompose_agent.py b/deeptutor/agents/research/agents/decompose_agent.pyindex 2b7380a75..364cc8560 100644--- a/deeptutor/agents/research/agents/decompose_agent.py+++ b/deeptutor/agents/research/agents/decompose_agent.py@@ -104,7 +104,11 @@ class DecomposeAgent(BaseAgent):).strip()async def process(- self, topic: str, num_subtopics: int = 5, mode: str = "manual"+ self,+ topic: str,+ num_subtopics: int = 5,+ mode: str = "manual",+ attachments: list[Any] | None = None,) -> dict[str, Any]:"""Decompose topic into subtopics and generate overview for each subtopic@@ -143,7 +147,7 @@ class DecomposeAgent(BaseAgent):# If RAG is disabled, use direct LLM generation without RAG contextif not self.enable_rag:print("⚠️ RAG is disabled, generating subtopics directly from LLM...")- return await self._process_without_rag(topic, num_subtopics, mode)+ return await self._process_without_rag(topic, num_subtopics, mode, attachments)print("\n🔍 Step 1: Executing RAG retrieval to get background knowledge...")rag_context, source_query = await self._retrieve_background_knowledge(topic)@@ -151,11 +155,17 @@ class DecomposeAgent(BaseAgent):print("\n🎯 Step 2: Generating subtopics...")if mode == "auto":sub_topics = await self._generate_sub_topics_auto(- topic=topic, rag_context=rag_context, max_subtopics=num_subtopics+ topic=topic,+ rag_context=rag_context,+ max_subtopics=num_subtopics,+ attachments=attachments,)else:sub_topics = await self._generate_sub_topics(- topic=topic, rag_context=rag_context, num_subtopics=num_subtopics+ topic=topic,+ rag_context=rag_context,+ num_subtopics=num_subtopics,+ attachments=attachments,)print(f"✓ Generated {len(sub_topics)} subtopics")@@ -213,7 +223,11 @@ class DecomposeAgent(BaseAgent):return "", source_queryasync def _process_without_rag(- self, topic: str, num_subtopics: int, mode: str = "manual"+ self,+ topic: str,+ num_subtopics: int,+ mode: str = "manual",+ attachments: list[Any] | None = None,) -> dict[str, Any]:"""Process without RAG: directly generate subtopics from LLM based on topic.@@ -268,6 +282,7 @@ Generate exactly {num_subtopics} subtopics. Please ensure exactly {num_subtopicsuser_prompt=user_prompt,system_prompt=system_prompt,stage="decompose_no_rag",+ attachments=attachments,trace_meta=self._build_trace_meta(mode),):_chunks.append(_c)@@ -307,7 +322,11 @@ Generate exactly {num_subtopics} subtopics. Please ensure exactly {num_subtopics}async def _generate_sub_topics_auto(- self, topic: str, rag_context: str, max_subtopics: int+ self,+ topic: str,+ rag_context: str,+ max_subtopics: int,+ attachments: list[Any] | None = None,) -> list[dict[str, str]]:"""Auto mode: Autonomously generate subtopics based on RAG background@@ -354,6 +373,7 @@ Dynamically generate no more than {max_subtopics} subtopics. Please carefully anuser_prompt=user_prompt,system_prompt=system_prompt,stage="decompose",+ attachments=attachments,trace_meta=self._build_trace_meta("auto"),):_chunks.append(_c)@@ -382,7 +402,11 @@ Dynamically generate no more than {max_subtopics} subtopics. Please carefully anreturn []async def _generate_sub_topics(- self, topic: str, rag_context: str, num_subtopics: int+ self,+ topic: str,+ rag_context: str,+ num_subtopics: int,+ attachments: list[Any] | None = None,) -> list[dict[str, str]]:"""Generate subtopics based on RAG background@@ -426,6 +450,7 @@ Explicitly generate {num_subtopics} subtopics. Please ensure exactly {num_subtopuser_prompt=user_prompt,system_prompt=system_prompt,stage="decompose",+ attachments=attachments,trace_meta=self._build_trace_meta("manual"),):_chunks.append(_c)diff --git a/deeptutor/agents/research/agents/rephrase_agent.py b/deeptutor/agents/research/agents/rephrase_agent.pyindex 28abe74be..e90814701 100644--- a/deeptutor/agents/research/agents/rephrase_agent.py+++ b/deeptutor/agents/research/agents/rephrase_agent.py@@ -89,7 +89,11 @@ class RephraseAgent(BaseAgent):return "\n\n".join(history_parts)async def process(- self, user_input: str, iteration: int = 0, previous_result: dict[str, Any] = None+ self,+ user_input: str,+ iteration: int = 0,+ previous_result: dict[str, Any] = None,+ attachments: list[Any] | None = None,) -> dict[str, Any]:"""Rephrase and optimize user input using the accumulated planning context.@@ -98,6 +102,7 @@ class RephraseAgent(BaseAgent):user_input: Research topic or the latest rephrased topiciteration: Iteration count (for tracking rephrasing rounds)previous_result: Previous rephrasing result+ attachments: Optional chat attachments for multimodal topic analysisReturns:Dictionary containing rephrasing results@@ -172,6 +177,7 @@ class RephraseAgent(BaseAgent):user_prompt=user_prompt,system_prompt=system_prompt,stage="rephrase",+ attachments=attachments,trace_meta=self._build_trace_meta(iteration),):_chunks.append(_c)diff --git a/deeptutor/agents/research/research_pipeline.py b/deeptutor/agents/research/research_pipeline.pyindex b4973da38..d8232057e 100644--- a/deeptutor/agents/research/research_pipeline.py+++ b/deeptutor/agents/research/research_pipeline.py@@ -42,6 +42,7 @@ class ResearchPipeline:progress_callback: Callable | None = None,trace_callback: Callable[[dict[str, Any]], Any] | None = None,pre_confirmed_outline: list[dict[str, str]] | None = None,+ attachments: list[Any] | None = None,):"""Initialize research workflow@@ -55,11 +56,13 @@ class ResearchPipeline:kb_name: Knowledge base name (optional, if provided overrides config file setting)progress_callback: Progress callback function (optional), signature: callback(event: Dict[str, Any])pre_confirmed_outline: Pre-confirmed sub-topics from outline preview (skips decompose)+ attachments: Optional chat attachments for the planning LLMs."""self.config = configself.progress_callback = progress_callbackself.trace_callback = trace_callbackself.pre_confirmed_outline = pre_confirmed_outline+ self.attachments = list(attachments or [])# If kb_name is provided, override configif kb_name is not None:@@ -626,13 +629,18 @@ class ResearchPipeline:rephrase_result = {"topic": topic}current_topic = topiciteration = 0+ planning_attachments_used = Falsewhile iteration < max_iterations:+ first_rephrase_turn = iteration == 0rephrase_result = await self.agents["rephrase"].process(current_topic,iteration=iteration,previous_result=rephrase_result,+ attachments=self.attachments if first_rephrase_turn else None,)+ if first_rephrase_turn:+ planning_attachments_used = Trueiteration += 1next_topic = str(rephrase_result.get("topic", "") or "").strip()if not next_topic:@@ -652,6 +660,7 @@ class ResearchPipeline:else:self.logger.info("\n【Step 1】Topic Rephrasing (disabled, skipping)...")optimized_topic = topic+ planning_attachments_used = Falseself._log_progress("planning","rephrase_skipped",@@ -682,7 +691,10 @@ class ResearchPipeline:self.agents["decompose"].set_citation_manager(self.citation_manager)decompose_result = await self.agents["decompose"].process(- topic=optimized_topic, num_subtopics=num_subtopics, mode=mode+ topic=optimized_topic,+ num_subtopics=num_subtopics,+ mode=mode,+ attachments=self.attachments if not planning_attachments_used else None,)self._log_progress("planning",diff --git a/deeptutor/agents/solve/agents/planner_agent.py b/deeptutor/agents/solve/agents/planner_agent.pyindex bcd4b63a1..9a35418ab 100644--- a/deeptutor/agents/solve/agents/planner_agent.py+++ b/deeptutor/agents/solve/agents/planner_agent.py@@ -65,6 +65,7 @@ class PlannerAgent(BaseAgent):replan: bool = False,memory_context: str = "",image_url: str | None = None,+ attachments: list[Any] | None = None,) -> Plan:"""Generate or revise the solving plan.@@ -75,6 +76,7 @@ class PlannerAgent(BaseAgent):replan: If True, this is a replan request — include progress so far.memory_context: Historical memory context string.image_url: Optional image URL for multimodal questions.+ attachments: Optional chat attachments for multimodal input.Returns:A Plan object with ordered steps.@@ -113,8 +115,11 @@ class PlannerAgent(BaseAgent):),}+ llm_attachments = list(attachments or [])if image_url:- llm_kwargs["attachments"] = [Attachment(type="image", url=image_url)]+ llm_attachments.append(Attachment(type="image", url=image_url))+ if llm_attachments:+ llm_kwargs["attachments"] = llm_attachmentschunks: list[str] = []async for chunk in self.stream_llm(**llm_kwargs):diff --git a/deeptutor/agents/solve/agents/solver_agent.py b/deeptutor/agents/solve/agents/solver_agent.pyindex dc9e6d50f..dc754bee4 100644--- a/deeptutor/agents/solve/agents/solver_agent.py+++ b/deeptutor/agents/solve/agents/solver_agent.py@@ -56,6 +56,7 @@ class SolverAgent(BaseAgent):scratchpad: Scratchpad,memory_context: str = "",image_url: str | None = None,+ attachments: list[Any] | None = None,round_index: int | None = None,) -> dict[str, str]:"""Run one ReAct iteration for the given plan step.@@ -66,6 +67,7 @@ class SolverAgent(BaseAgent):scratchpad: Current scratchpad state.memory_context: Historical memory context string.image_url: Optional image URL for multimodal questions.+ attachments: Optional chat attachments for multimodal input.Returns:dict with keys: thought, action, action_input, self_note@@ -105,8 +107,11 @@ class SolverAgent(BaseAgent):"trace_meta": trace_meta,}+ llm_attachments = list(attachments or [])if image_url:- llm_kwargs["attachments"] = [Attachment(type="image", url=image_url)]+ llm_attachments.append(Attachment(type="image", url=image_url))+ if llm_attachments:+ llm_kwargs["attachments"] = llm_attachmentschunks: list[str] = []async for chunk in self.stream_llm(**llm_kwargs):diff --git a/deeptutor/agents/solve/main_solver.py b/deeptutor/agents/solve/main_solver.pyindex eb464e407..9e00dd5d7 100644--- a/deeptutor/agents/solve/main_solver.py+++ b/deeptutor/agents/solve/main_solver.py@@ -268,6 +268,7 @@ class MainSolver:self,question: str,image_url: str | None = None,+ attachments: list[Any] | None = None,verbose: bool = True,detailed: bool | None = None,conversation_context: str = "",@@ -277,6 +278,7 @@ class MainSolver:Args:question: The user question to solve.image_url: Optional image URL for multimodal questions.+ attachments: Optional multimodal attachments from the chat composer.verbose: Enable verbose logging.detailed: If True, use iterative detailed writing. If None, read from config.@@ -305,7 +307,12 @@ class MainSolver:self.logger.info(f"Output: {output_dir}")try:- result = await self._run_pipeline(question, output_dir, image_url=image_url)+ result = await self._run_pipeline(+ question,+ output_dir,+ image_url=image_url,+ attachments=attachments,+ )result["metadata"] = {**result.get("metadata", {}),"mode": "plan_react_write",@@ -349,6 +356,7 @@ class MainSolver:question: str,output_dir: str,image_url: str | None = None,+ attachments: list[Any] | None = None,) -> dict[str, Any]:solve_cfg = self.config.get("solve", {})max_react = solve_cfg.get("max_react_iterations", 5)@@ -375,6 +383,7 @@ class MainSolver:kb_name=self.kb_name,memory_context=memory_ctx,image_url=image_url,+ attachments=attachments,)scratchpad.set_plan(plan)scratchpad.save(output_dir)@@ -441,6 +450,7 @@ class MainSolver:scratchpad=scratchpad,memory_context=step_memory_context,image_url=image_url,+ attachments=attachments,round_index=round_num + 1,)@@ -514,6 +524,7 @@ class MainSolver:replan=True,memory_context=replan_memory,image_url=image_url,+ attachments=attachments,)scratchpad.update_plan(new_plan)scratchpad.save(output_dir)diff --git a/deeptutor/agents/visualize/agents/analysis_agent.py b/deeptutor/agents/visualize/agents/analysis_agent.pyindex f25b2f174..a49384124 100644--- a/deeptutor/agents/visualize/agents/analysis_agent.py+++ b/deeptutor/agents/visualize/agents/analysis_agent.py@@ -3,6 +3,7 @@from __future__ import annotationsfrom deeptutor.agents.base_agent import BaseAgent+from deeptutor.core.context import Attachmentfrom deeptutor.core.trace import build_trace_metadata, new_call_idfrom ..models import VisualizationAnalysis@@ -32,6 +33,7 @@ class AnalysisAgent(BaseAgent):user_input: str,history_context: str,render_mode: str = "auto",+ attachments: list[Attachment] | None = None,) -> VisualizationAnalysis:if render_mode in ("svg", "chartjs", "mermaid", "html"):system_prompt = self.get_prompt("system_fixed")@@ -62,6 +64,7 @@ class AnalysisAgent(BaseAgent):system_prompt=system_prompt,response_format={"type": "json_object"},stage="analyzing",+ attachments=attachments,trace_meta=build_trace_metadata(call_id=new_call_id("viz-analysis"),phase="analyzing",diff --git a/deeptutor/agents/visualize/pipeline.py b/deeptutor/agents/visualize/pipeline.pyindex 4724e041b..2a1fdaa41 100644--- a/deeptutor/agents/visualize/pipeline.py+++ b/deeptutor/agents/visualize/pipeline.py@@ -4,6 +4,8 @@ from __future__ import annotationsfrom typing import Any, Callable+from deeptutor.core.context import Attachment+from .agents import AnalysisAgent, CodeGeneratorAgent, ReviewAgentfrom .models import ReviewResult, VisualizationAnalysis@@ -48,11 +50,13 @@ class VisualizePipeline:user_input: str,history_context: str,render_mode: str = "auto",+ attachments: list[Attachment] | None = None,) -> VisualizationAnalysis:return await self.analysis_agent.process(user_input=user_input,history_context=history_context,render_mode=render_mode,+ attachments=attachments,)async def run_code_generation(diff --git a/deeptutor/api/main.py b/deeptutor/api/main.pyindex 3ecd42503..a47fc201f 100644--- a/deeptutor/api/main.py+++ b/deeptutor/api/main.py@@ -199,6 +199,7 @@ app.mount(# Some router modules load YAML settings at import time.from deeptutor.api.routers import (agent_config,+ attachments,book,chat,co_writer,@@ -240,6 +241,7 @@ app.include_router(plugins_api.router, prefix="/api/v1/plugins", tags=["plugins"app.include_router(agent_config.router, prefix="/api/v1/agent-config", tags=["agent-config"])app.include_router(vision_solver.router, prefix="/api/v1", tags=["vision-solver"])app.include_router(tutorbot.router, prefix="/api/v1/tutorbot", tags=["tutorbot"])+app.include_router(attachments.router, prefix="/api/attachments", tags=["attachments"])# Unified WebSocket endpointapp.include_router(unified_ws.router, prefix="/api/v1", tags=["unified-ws"])diff --git a/deeptutor/api/routers/attachments.py b/deeptutor/api/routers/attachments.pynew file mode 100644index 000000000..130cf7689--- /dev/null+++ b/deeptutor/api/routers/attachments.py@@ -0,0 +1,93 @@+"""HTTP endpoint for chat attachment downloads / previews.++The chat turn runtime persists every uploaded attachment to the+:class:`~deeptutor.services.storage.AttachmentStore` and records the public+URL on the message. The frontend preview drawer loads files via this+router, which only serves paths the store hands back — every component is+sanitised to defend against directory traversal.++URL shape::++ GET /api/attachments/{session_id}/{attachment_id}/{filename}++The session id functions as the ACL boundary, mirroring how the rest of+the app treats sessions today (single-tenant, session ownership is local+trust). Once multi-user auth lands we should swap this for signed URLs.+"""++from __future__ import annotations++import logging+import mimetypes+from urllib.parse import quote++from fastapi import APIRouter, HTTPException+from fastapi.responses import FileResponse++from deeptutor.services.storage import (+ LocalDiskAttachmentStore,+ get_attachment_store,+)++logger = logging.getLogger(__name__)++router = APIRouter()+++def _content_disposition(filename: str, *, disposition: str = "inline") -> str:+ """Build a Content-Disposition header that survives non-ASCII filenames.++ HTTP/1.1 headers are latin-1, so dropping a Chinese / accented filename+ straight into ``filename="..."`` blows up with UnicodeEncodeError. RFC+ 6266 / RFC 5987 cover this: emit ``filename*=UTF-8''<percent-encoded>``+ plus an ASCII fallback on ``filename=`` for legacy clients.+ """+ ascii_fallback = filename.encode("ascii", errors="replace").decode("ascii")+ # Quotes / backslashes break the simple-quoted-string form; collapse them.+ ascii_fallback = ascii_fallback.replace('"', "_").replace("\\", "_")+ encoded = quote(filename, safe="")+ return (+ f'{disposition}; filename="{ascii_fallback}"; filename*=UTF-8\'\'{encoded}'+ )++[email protected]("/{session_id}/{attachment_id}/{filename:path}")+async def get_attachment(+ session_id: str,+ attachment_id: str,+ filename: str,+):+ """Serve a previously uploaded chat attachment.++ Responds with ``Content-Disposition: inline`` so browsers preview PDFs+ and images directly in an ``<iframe>`` / ``<img>``. For unknown types+ the browser still falls back to download, which is fine for the+ drawer's "Download" button path.+ """+ store = get_attachment_store()+ if not isinstance(store, LocalDiskAttachmentStore):+ # Future remote backends should issue a redirect to the signed URL+ # here. Local-disk is the only backend today, so this branch just+ # guards against an unexpected configuration.+ raise HTTPException(status_code=501, detail="Attachment backend not servable")++ target = store.resolve_path(+ session_id=session_id,+ attachment_id=attachment_id,+ filename=filename,+ )+ if target is None:+ raise HTTPException(status_code=404, detail="Attachment not found")++ media_type, _ = mimetypes.guess_type(target.name)+ if not media_type:+ media_type = "application/octet-stream"++ # ``inline`` lets the browser preview the file when possible while still+ # honouring the suggested filename for the drawer's download action.+ headers = {+ "Content-Disposition": _content_disposition(target.name),+ # User-uploaded data; do not let intermediaries cache it.+ "Cache-Control": "private, max-age=0, must-revalidate",+ }+ return FileResponse(path=str(target), media_type=media_type, headers=headers)diff --git a/deeptutor/api/routers/notebook.py b/deeptutor/api/routers/notebook.pyindex 91e842d9d..1ec00ca0b 100644--- a/deeptutor/api/routers/notebook.py+++ b/deeptutor/api/routers/notebook.py@@ -41,7 +41,9 @@ class AddRecordRequest(BaseModel):"""Add record request"""notebook_ids: list[str]- record_type: Literal["solve", "question", "research", "chat", "co_writer"]+ record_type: Literal[+ "solve", "question", "research", "chat", "co_writer", "tutorbot"+ ]title: strsummary: str = ""user_query: strdiff --git a/deeptutor/capabilities/deep_question.py b/deeptutor/capabilities/deep_question.pyindex c982200b6..739708ba2 100644--- a/deeptutor/capabilities/deep_question.py+++ b/deeptutor/capabilities/deep_question.py@@ -67,6 +67,7 @@ class DeepQuestionCapability(BaseCapability):history_context=str(context.metadata.get("conversation_context_text", "") or "").strip(),+ attachments=context.attachments,)if answer:await stream.content(answer, source=self.name, stage="generation")@@ -174,6 +175,7 @@ class DeepQuestionCapability(BaseCapability):difficulty=difficulty,question_type=question_type,history_context=history_context,+ attachments=context.attachments,)content = self._render_summary_markdown(result)@@ -412,6 +414,26 @@ class DeepQuestionCapability(BaseCapability):).strip(),)+ if "[Attached Documents]" in context.user_message:+ async with stream.stage("ideation", source=self.name):+ await stream.thinking(+ "Using extracted attachment text as the quiz source...",+ source=self.name,+ stage="ideation",+ )+ return await coordinator.generate_from_topic(+ user_topic=context.user_message,+ preference=(+ "Mimic the attached source document as closely as possible: "+ "style, difficulty, structure, and assessed concepts."+ ),+ num_questions=max_questions,+ history_context=str(+ context.metadata.get("conversation_context_text", "") or ""+ ).strip(),+ attachments=context.attachments,+ )+await stream.error("Mimic mode requires either an uploaded PDF or a parsed exam directory.",source=self.name,diff --git a/deeptutor/capabilities/deep_research.py b/deeptutor/capabilities/deep_research.pyindex c114d8f37..4b0468195 100644--- a/deeptutor/capabilities/deep_research.py+++ b/deeptutor/capabilities/deep_research.py@@ -326,6 +326,7 @@ class DeepResearchCapability(BaseCapability):progress_callback=_progress_cb,trace_callback=_trace_cb,conversation_history=conversation_history,+ attachments=context.attachments,)sub_topics_data = []for item in outline_items:@@ -373,6 +374,7 @@ class DeepResearchCapability(BaseCapability):progress_callback=_progress_cb,trace_callback=_trace_cb,pre_confirmed_outline=pre_outline,+ attachments=context.attachments,)async with stream.stage("researching", source=self.name):@@ -480,6 +482,7 @@ class DeepResearchCapability(BaseCapability):progress_callback: Any,trace_callback: Any,conversation_history: list[dict[str, Any]] | None = None,+ attachments: list[Any] | None = None,) -> list[dict[str, str]]:"""Run only the planning phase (rephrase + decompose) and return sub-topics."""from deeptutor.agents.research.research_pipeline import ResearchPipeline@@ -495,6 +498,7 @@ class DeepResearchCapability(BaseCapability):kb_name=kb_name,progress_callback=progress_callback,trace_callback=trace_callback,+ attachments=attachments,)async with stream.stage("decomposing", source=self.name):diff --git a/deeptutor/capabilities/deep_solve.py b/deeptutor/capabilities/deep_solve.pyindex e1935fc74..891838250 100644--- a/deeptutor/capabilities/deep_solve.py+++ b/deeptutor/capabilities/deep_solve.py@@ -18,18 +18,9 @@ from deeptutor.core.stream_bus import StreamBusfrom deeptutor.core.trace import derive_trace_metadata, merge_trace_metadata-def _first_image_url(attachments: list[Any]) -> str | None:- """Extract a data-URI or URL from the first image attachment, if any."""- for att in attachments or []:- if getattr(att, "type", "") != "image":- continue- if getattr(att, "url", ""):- return att.url- b64 = getattr(att, "base64", "")- if b64:- mime = getattr(att, "mime_type", "") or "image/png"- return f"data:{mime};base64,{b64}"- return None+def _image_attachments(attachments: list[Any]) -> list[Any]:+ """Return the image attachments to forward into multimodal LLM calls."""+ return [att for att in attachments or [] if getattr(att, "type", "") == "image"]class DeepSolveCapability(BaseCapability):@@ -274,11 +265,9 @@ class DeepSolveCapability(BaseCapability):setattr(solver, "_content_callback", _content_sink)- image_url = _first_image_url(context.attachments)-result = await solver.solve(question=context.user_message,- image_url=image_url,+ attachments=_image_attachments(context.attachments),verbose=False,detailed=detailed,conversation_context=str(diff --git a/deeptutor/capabilities/visualize.py b/deeptutor/capabilities/visualize.pyindex 498a28985..845b56f52 100644--- a/deeptutor/capabilities/visualize.py+++ b/deeptutor/capabilities/visualize.py@@ -66,6 +66,7 @@ class VisualizeCapability(BaseCapability):user_input=context.user_message,history_context=history_context,render_mode=render_mode,+ attachments=context.attachments,)await stream.progress(message=f"Render type: {analysis.render_type} — {analysis.description}",diff --git a/deeptutor/core/context.py b/deeptutor/core/context.pyindex 752e76646..28ea105e7 100644--- a/deeptutor/core/context.py+++ b/deeptutor/core/context.py@@ -21,6 +21,13 @@ class Attachment:base64: str = ""filename: str = ""mime_type: str = ""+ # Stable per-attachment identifier; doubles as the directory segment+ # under which the original bytes live in the AttachmentStore.+ id: str = ""+ # Plain-text rendering of binary documents (PDF/DOCX/XLSX/PPTX).+ # Populated by ``extract_documents_from_records`` so the frontend can+ # show "what the LLM saw" when previewing office files.+ extracted_text: str = ""@dataclassdiff --git a/deeptutor/services/notebook/service.py b/deeptutor/services/notebook/service.pyindex 1e747abb2..36e0f9009 100644--- a/deeptutor/services/notebook/service.py+++ b/deeptutor/services/notebook/service.py@@ -26,6 +26,7 @@ class RecordType(str, Enum):RESEARCH = "research"CHAT = "chat"CO_WRITER = "co_writer"+ TUTORBOT = "tutorbot"class NotebookRecord(BaseModel):diff --git a/deeptutor/services/rag/file_routing.py b/deeptutor/services/rag/file_routing.pyindex 3cd68af68..927f23511 100644--- a/deeptutor/services/rag/file_routing.py+++ b/deeptutor/services/rag/file_routing.py@@ -48,6 +48,7 @@ class FileTypeRouter:PARSER_EXTENSIONS = {".pdf"}TEXT_EXTENSIONS = {+ # Plain text & docs".txt",".text",".log",@@ -55,38 +56,89 @@ class FileTypeRouter:".markdown",".rst",".asciidoc",+ # Data / config".json",+ ".jsonc",+ ".json5",".yaml",".yml",".toml",".csv",".tsv",+ ".ini",+ ".cfg",+ ".conf",+ ".env",+ ".properties",+ # Typesetting".tex",".latex",".bib",- ".py",+ # JavaScript / TypeScript family".js",+ ".mjs",+ ".cjs",".ts",+ ".mts",+ ".cts",".jsx",".tsx",+ # Web frameworks+ ".vue",+ ".svelte",+ # Python+ ".py",+ # JVM languages".java",+ ".kt",+ ".kts",+ ".scala",+ ".groovy",+ ".gradle",+ # Systems languages".c",- ".cpp",".h",+ ".cpp",+ ".cc",+ ".cxx",".hpp",+ ".hh",+ ".hxx",+ ".cs",".go",".rs",+ ".zig",+ ".nim",+ # Apple platforms+ ".swift",+ ".m",+ ".mm",+ # Scripting".rb",".php",- ".swift",- ".kt",- ".scala",+ ".pl",+ ".pm",+ ".lua",".r",- ".sql",- ".sh",- ".bash",- ".zsh",- ".ps1",+ ".jl",+ ".dart",+ # Functional+ ".hs",+ ".clj",+ ".cljs",+ ".cljc",+ ".ex",+ ".exs",+ ".erl",+ ".ml",+ ".mli",+ ".fs",+ ".fsx",+ ".lisp",+ ".lsp",+ ".scm",+ ".rkt",+ # Web markup / styles".html",".htm",".xml",@@ -95,11 +147,27 @@ class FileTypeRouter:".scss",".sass",".less",- ".ini",- ".cfg",- ".conf",- ".env",- ".properties",+ # Smart contracts+ ".sol",+ # Shells / editors+ ".sh",+ ".bash",+ ".zsh",+ ".fish",+ ".ps1",+ ".vim",+ # Query / IDL+ ".sql",+ ".graphql",+ ".gql",+ ".proto",+ # Build / infra+ ".cmake",+ ".mk",+ ".tf",+ ".hcl",+ ".nginxconf",+ ".dockerfile",}DOCX_EXTENSIONS = {".docx", ".doc"}diff --git a/deeptutor/services/session/turn_runtime.py b/deeptutor/services/session/turn_runtime.pyindex c3b9f1118..1e3980d89 100644--- a/deeptutor/services/session/turn_runtime.py+++ b/deeptutor/services/session/turn_runtime.py@@ -546,6 +546,11 @@ class TurnRuntimeManager:history_context = ""question_bank_context = ""+ import base64 as _b64+ import uuid as _uuid++ from deeptutor.services.storage import get_attachment_store+for item in payload.get("attachments", []):record = {"type": item.get("type", "file"),@@ -553,9 +558,46 @@ class TurnRuntimeManager:"base64": item.get("base64", ""),"filename": item.get("filename", ""),"mime_type": item.get("mime_type", ""),+ "id": item.get("id", "") or _uuid.uuid4().hex[:12],}attachment_records.append(record)+ # Persist original bytes to the attachment store before extraction+ # so the frontend preview drawer can fetch the file later. The+ # extractor will clear base64 on documents to keep DB rows lean,+ # but the URL we record here outlives that pruning. Upload errors+ # are non-fatal — extraction still runs from the in-memory base64.+ attachment_store = get_attachment_store()+ for record in attachment_records:+ if record.get("url"):+ continue # already hosted (e.g. legacy URL)+ b64 = record.get("base64") or ""+ if not b64:+ continue+ try:+ raw_bytes = _b64.b64decode(b64, validate=False)+ except Exception as exc:+ logger.warning(+ "skipping attachment upload for %r: invalid base64 (%s)",+ record.get("filename"),+ exc,+ )+ continue+ try:+ record["url"] = await attachment_store.put(+ session_id=session_id,+ attachment_id=record["id"],+ filename=record.get("filename", "") or "file",+ data=raw_bytes,+ mime_type=record.get("mime_type", "") or "",+ )+ except Exception as exc:+ logger.warning(+ "attachment store rejected %r: %s",+ record.get("filename"),+ exc,+ )+from deeptutor.utils.document_extractor import extract_documents_from_recordsdocument_texts, attachment_records = extract_documents_from_records(@@ -568,9 +610,22 @@ class TurnRuntimeManager:base64=r.get("base64", ""),filename=r.get("filename", ""),mime_type=r.get("mime_type", ""),+ id=r.get("id", ""),+ extracted_text=r.get("extracted_text", ""),)for r in attachment_records]+ # DB persistence copy: drop base64 unconditionally now that the+ # original bytes live in the attachment store. Image attachments+ # used to keep base64 here (which bloated message rows); the URL+ # is now the stable source for previews.+ persisted_attachment_records = [+ {+ **{k: v for k, v in r.items() if k != "base64"},+ "base64": "",+ }+ for r in attachment_records+ ]if followup_question_context:existing_messages = await self.store.get_messages_for_context(session_id)@@ -727,7 +782,7 @@ class TurnRuntimeManager:role="user",content=raw_user_content,capability=capability_name,- attachments=attachment_records,+ attachments=persisted_attachment_records,)context = UnifiedContext(diff --git a/deeptutor/services/storage/__init__.py b/deeptutor/services/storage/__init__.pynew file mode 100644index 000000000..17baaa7e0--- /dev/null+++ b/deeptutor/services/storage/__init__.py@@ -0,0 +1,18 @@+"""Pluggable storage backends for chat-session artifacts.++Currently exposes only :mod:`attachment_store`, which persists user-uploaded+chat attachments to disk so the frontend can preview them after the original+base64 payload is dropped from the message record.+"""++from deeptutor.services.storage.attachment_store import (+ AttachmentStore,+ LocalDiskAttachmentStore,+ get_attachment_store,+)++__all__ = [+ "AttachmentStore",+ "LocalDiskAttachmentStore",+ "get_attachment_store",+]diff --git a/deeptutor/services/storage/attachment_store.py b/deeptutor/services/storage/attachment_store.pynew file mode 100644index 000000000..e718a37cd--- /dev/null+++ b/deeptutor/services/storage/attachment_store.py@@ -0,0 +1,236 @@+"""Persistent storage for chat attachments.++The chat turn runtime writes the bytes of every uploaded attachment here+*before* the document extractor runs. Once persisted, the URL is recorded on+the message and the in-memory base64 is dropped (extractor still clears it+for office docs to save DB space). The frontend later fetches the original+file via the :mod:`deeptutor.api.routers.attachments` endpoint to render a+preview.++Design goals+------------++* **Local disk by default**: works in single-container Docker setups (the+ ``data/user`` volume is already mounted) and on plain Linux servers without+ any extra infrastructure.+* **Pluggable**: a thin :class:`AttachmentStore` protocol leaves room for an+ S3 / MinIO / GCS backend without touching call-sites.+* **Path-safe**: filenames coming over the WS are sanitised; resolved paths+ must remain inside the configured root.++The on-disk layout is::++ {root}/{session_id}/{attachment_id}_{filename}++The ``attachment_id`` prefix prevents collisions when the same filename is+uploaded twice in the same session.+"""++from __future__ import annotations++import asyncio+import logging+import os+from pathlib import Path+from typing import Protocol, runtime_checkable+from urllib.parse import quote++from deeptutor.services.path_service import get_path_service+from deeptutor.tutorbot.utils.helpers import safe_filename++logger = logging.getLogger(__name__)+++_ATTACHMENT_DIR_ENV = "CHAT_ATTACHMENT_DIR"+_DEFAULT_SUBPATH = ("workspace", "chat", "attachments")+# Public route prefix served by deeptutor.api.routers.attachments+_PUBLIC_URL_PREFIX = "/api/attachments"+++def _coerce_filename(filename: str) -> str:+ """Reduce *filename* to a safe basename.++ * Strips any directory components (defends against ``../`` traversal).+ * Replaces filesystem-unsafe characters via the existing ``safe_filename``+ helper (already used by the matrix tutorbot uploads).+ * Falls back to ``"file"`` if the result is empty.+ """+ base = os.path.basename(filename or "")+ cleaned = safe_filename(base)+ return cleaned or "file"+++@runtime_checkable+class AttachmentStore(Protocol):+ """Storage backend for chat attachments.++ Implementations must be safe to call from an asyncio context. The default+ :class:`LocalDiskAttachmentStore` uses ``run_in_executor`` to keep blocking+ disk I/O off the event loop.+ """++ async def put(+ self,+ *,+ session_id: str,+ attachment_id: str,+ filename: str,+ data: bytes,+ mime_type: str = "",+ ) -> str:+ """Persist *data* and return a public URL the frontend can fetch.++ The returned URL is relative to the API origin (e.g.+ ``"/api/attachments/<sid>/<aid>/<name>"``). Raising on failure is+ fine — callers log the error and proceed without ``url``.+ """++ async def delete_session(self, session_id: str) -> None:+ """Best-effort cleanup of all attachments for *session_id*."""++ def resolve_path(+ self, *, session_id: str, attachment_id: str, filename: str+ ) -> Path | None:+ """Return the absolute path on disk for an attachment, or ``None``+ if it does not exist or escapes the storage root.++ Used by the static router to serve files; remote-storage backends can+ return ``None`` and the router will then fall back to a redirect.+ """+++class LocalDiskAttachmentStore:+ """Default :class:`AttachmentStore` backend writing to local disk.++ The root directory defaults to ``data/user/workspace/chat/attachments``+ under the project root (matching :class:`PathService`'s public outputs).+ Override via ``$CHAT_ATTACHMENT_DIR`` (absolute path).+ """++ def __init__(self, root: Path | None = None) -> None:+ if root is None:+ override = os.environ.get(_ATTACHMENT_DIR_ENV, "").strip()+ if override:+ root = Path(override).expanduser().resolve()+ else:+ root = (+ get_path_service().get_user_root().joinpath(*_DEFAULT_SUBPATH)+ ).resolve()+ self._root = root++ @property+ def root(self) -> Path:+ return self._root++ def _stored_filename(self, attachment_id: str, filename: str) -> str:+ return f"{attachment_id}_{_coerce_filename(filename)}"++ def _session_dir(self, session_id: str) -> Path:+ sid = _coerce_filename(session_id)+ return (self._root / sid).resolve()++ def _safe_join(self, session_id: str, name: str) -> Path | None:+ """Join *name* under the session dir and confirm the result stays+ inside ``self._root``. Returns ``None`` if traversal is detected.+ """+ session_dir = self._session_dir(session_id)+ # Resolve the candidate even if it doesn't exist yet — prevents a+ # symlink-based attack that would point outside the root once created.+ candidate = (session_dir / name).resolve()+ try:+ candidate.relative_to(self._root.resolve())+ except ValueError:+ return None+ return candidate++ async def put(+ self,+ *,+ session_id: str,+ attachment_id: str,+ filename: str,+ data: bytes,+ mime_type: str = "",+ ) -> str:+ del mime_type # not needed for local disk+ stored = self._stored_filename(attachment_id, filename)+ target = self._safe_join(session_id, stored)+ if target is None:+ raise ValueError(+ f"refusing to write attachment outside storage root: {stored!r}"+ )++ loop = asyncio.get_running_loop()+ await loop.run_in_executor(None, self._write_sync, target, data)++ # The router uses the same _coerce_filename rules to look up the file,+ # so the public URL must use the sanitised pieces. Each path segment+ # is percent-encoded so spaces/Unicode/punctuation in filenames flow+ # through fetch / <iframe> consistently across browsers.+ sid = quote(_coerce_filename(session_id), safe="")+ aid = quote(attachment_id, safe="")+ name = quote(_coerce_filename(filename), safe="")+ return f"{_PUBLIC_URL_PREFIX}/{sid}/{aid}/{name}"++ @staticmethod+ def _write_sync(target: Path, data: bytes) -> None:+ target.parent.mkdir(parents=True, exist_ok=True)+ # Atomic-ish write: write to .tmp then rename. Avoids exposing a+ # half-written file via the static handler.+ tmp = target.with_suffix(target.suffix + ".tmp")+ try:+ with tmp.open("wb") as fh:+ fh.write(data)+ os.replace(tmp, target)+ finally:+ if tmp.exists():+ try:+ tmp.unlink()+ except OSError:+ pass++ async def delete_session(self, session_id: str) -> None:+ session_dir = self._session_dir(session_id)+ if not session_dir.exists():+ return+ loop = asyncio.get_running_loop()+ await loop.run_in_executor(None, self._rmtree_sync, session_dir)++ @staticmethod+ def _rmtree_sync(path: Path) -> None:+ import shutil++ try:+ shutil.rmtree(path)+ except OSError as exc:+ logger.warning("failed to clean up attachment dir %s: %s", path, exc)++ def resolve_path(+ self, *, session_id: str, attachment_id: str, filename: str+ ) -> Path | None:+ stored = self._stored_filename(attachment_id, filename)+ target = self._safe_join(session_id, stored)+ if target is None or not target.is_file():+ return None+ return target+++_singleton: AttachmentStore | None = None+++def get_attachment_store() -> AttachmentStore:+ """Return the process-wide :class:`AttachmentStore`.++ Today this is always a :class:`LocalDiskAttachmentStore`; future S3/MinIO+ backends can be selected here based on an env var.+ """+ global _singleton+ if _singleton is None:+ _singleton = LocalDiskAttachmentStore()+ return _singleton+++def reset_attachment_store() -> None:+ """Reset the singleton — only meant for tests."""+ global _singleton+ _singleton = Nonediff --git a/deeptutor/utils/document_extractor.py b/deeptutor/utils/document_extractor.pyindex 2e80ebc90..bb0209cc9 100644--- a/deeptutor/utils/document_extractor.py+++ b/deeptutor/utils/document_extractor.py@@ -323,9 +323,11 @@ def extract_documents_from_records(``doc_texts`` is a list of strings formatted as``"[File: <name>]\\n<text>"`` (one per processed or skipped doc).``updated_records`` is the input list with the ``base64`` field- cleared on successfully-extracted docs (to save DB space) and an- ``extracted_chars`` field added. Image / non-document records are- returned unchanged.+ cleared on successfully-extracted docs (to save DB space), an+ ``extracted_chars`` field added, and the extracted plain text+ stored under ``extracted_text`` so the chat UI can preview office+ documents without re-running the parser. Image / non-document+ records are returned unchanged."""doc_texts: list[str] = []updated: list[dict] = []@@ -405,6 +407,7 @@ def extract_documents_from_records(doc_texts.append(f"[File: {filename}]\n{text}")record["base64"] = ""record["extracted_chars"] = len(text)+ record["extracted_text"] = textupdated.append(record)return doc_texts, updateddiff --git a/scripts/start_tour.py b/scripts/start_tour.pyindex 75f326668..637706cbb 100644--- a/scripts/start_tour.py+++ b/scripts/start_tour.py@@ -80,11 +80,21 @@ def _bootstrap() -> None:if not missing:returnprint(f" Installing bootstrap dependencies: {', '.join(missing)} ...")- subprocess.check_call(- [*_PIP_CMD, "install", *missing, *_PIP_PYTHON_ARGS, "-q"],- stdout=subprocess.DEVNULL,- stderr=subprocess.DEVNULL,- )+ cmd = [*_PIP_CMD, "install", *missing, *_PIP_PYTHON_ARGS, "-q"]+ result = subprocess.run(cmd, capture_output=True, text=True, errors="replace")+ if result.returncode != 0:+ # Surface the real pip error instead of silently exiting — without+ # this, users see only an opaque CalledProcessError traceback.+ if result.stdout:+ sys.stderr.write(result.stdout)+ if result.stderr:+ sys.stderr.write(result.stderr)+ sys.stderr.write(+ f"\n Failed to install bootstrap dependencies: {', '.join(missing)}\n"+ f" Try running it manually to inspect the full error:\n"+ f" {' '.join(cmd[:-1])}\n"+ )+ raise SystemExit(1)_bootstrap()@@ -235,6 +245,19 @@ MESSAGES: dict[str, dict[str, str]] = {"install_step": "Install dependencies","install_desc": "We will install Python (via uv) and Node.js dependencies for you.","install_checking": "Checking environment ...",+ "install_uv_via_pip": "uv not found — installing via pip ...",+ "install_uv_pip_failed": "Failed to install uv via pip. The underlying error was:",+ "install_uv_hint": (+ "Possible fixes:\n"+ " - Python 3.14+ may not yet have a prebuilt uv wheel; try Python 3.12 or 3.13.\n"+ " - If you already installed uv manually, open a NEW terminal so PATH is refreshed.\n"+ " - Slow / blocked PyPI? Try a mirror, e.g.\n"+ " pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple\n"+ " - Or install uv directly: https://docs.astral.sh/uv/getting-started/installation/"+ ),+ "install_uv_not_on_path": (+ "uv was installed but is not on PATH. Open a new terminal and re-run this script."+ ),"install_uv_ok": "uv: {version}","install_python_ok": "Python: {version}","install_node_ok": "Node.js: {version}",@@ -324,6 +347,19 @@ MESSAGES: dict[str, dict[str, str]] = {"install_step": "安装依赖","install_desc": "我们将通过 uv 安装 Python 依赖,并安装 Node.js 依赖。","install_checking": "正在检测环境 ...",+ "install_uv_via_pip": "未检测到 uv,正在通过 pip 安装 ...",+ "install_uv_pip_failed": "通过 pip 安装 uv 失败,下方是 pip 输出的真实错误:",+ "install_uv_hint": (+ "可能的解决办法:\n"+ " - Python 3.14+ 可能还没有预编译的 uv wheel,建议改用 Python 3.12 或 3.13。\n"+ " - 如果你已经手动安装了 uv,请关闭并重新打开终端以刷新 PATH 后重试。\n"+ " - PyPI 下载缓慢或被拦截?可以切换镜像源,例如:\n"+ " pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple\n"+ " - 也可参考官方安装方式:https://docs.astral.sh/uv/getting-started/installation/"+ ),+ "install_uv_not_on_path": (+ "uv 已安装但没有出现在 PATH 中,请新开一个终端窗口后重新运行本脚本。"+ ),"install_uv_ok": "uv: {version}","install_python_ok": "Python: {version}","install_node_ok": "Node.js: {version}",@@ -744,6 +780,7 @@ def _get_version(cmd: list[str]) -> str | None:capture_output=True,text=True,timeout=10,+ errors="replace",)if result.returncode == 0:return result.stdout.strip()@@ -752,6 +789,49 @@ def _get_version(cmd: list[str]) -> str | None:return None+def _detect_command_version(name: str) -> str | None:+ """Resolve ``name`` via ``shutil.which`` then probe ``--version``.++ Why: on Windows, ``node`` resolves to ``node.exe`` and ``npm`` to+ ``npm.cmd``. ``subprocess.run`` with a bare name (no ``shell=True``)+ handles the former unevenly across Python versions and outright rejects+ ``.cmd``/``.bat`` files since the CVE-2024-4030 hardening in 3.12. Using+ the absolute path returned by ``shutil.which`` (which already respects+ ``PATHEXT``) sidesteps both pitfalls and matches how ``_node_strategy``+ detects the same tools.+ """+ exe = shutil.which(name)+ if not exe:+ return None+ return _get_version([exe, "--version"])+++def _find_uv_in_known_locations() -> str | None:+ """Look for uv in well-known install locations even if not on PATH.++ Helps when the user just ran the standalone installer (or ``pip install+ --user uv``) and hasn't reopened their shell to refresh PATH — without+ this, we'd needlessly try to install uv again.+ """+ home = Path.home()+ if platform.system().lower() == "windows":+ candidates = [+ home / ".local" / "bin" / "uv.exe",+ home / ".cargo" / "bin" / "uv.exe",+ ]+ else:+ candidates = [+ home / ".local" / "bin" / "uv",+ home / ".cargo" / "bin" / "uv",+ Path("/opt/homebrew/bin/uv"),+ Path("/usr/local/bin/uv"),+ ]+ for path in candidates:+ if path.is_file():+ return str(path)+ return None++def _resolve_uv() -> str:"""Return path to uv, installing it via pip if necessary.@@ -759,19 +839,33 @@ def _resolve_uv() -> str:returned None we cannot bootstrap uv with itself, and a pip-less venvwould have already failed in ``_bootstrap()`` above."""- found = shutil.which("uv")+ found = shutil.which("uv") or _find_uv_in_known_locations()if found:return found- log_info(dim("uv not found — installing via pip ..."))- subprocess.check_call(- [_PYTHON, "-m", "pip", "install", "uv", "-q"],- stdout=subprocess.DEVNULL,- stderr=subprocess.DEVNULL,- )- found = shutil.which("uv")+ log_info(dim(_t("install_uv_via_pip")))+ cmd = [_PYTHON, "-m", "pip", "install", "uv", "--disable-pip-version-check"]+ result = subprocess.run(cmd, capture_output=True, text=True, errors="replace")+ if result.returncode != 0:+ log_error(_t("install_uv_pip_failed"))+ # Replay pip's real output so the user can see *why* it failed+ # (no wheel for this Python, network/proxy, SSL, etc.).+ if result.stdout:+ sys.stderr.write(result.stdout)+ if not result.stdout.endswith("\n"):+ sys.stderr.write("\n")+ if result.stderr:+ sys.stderr.write(result.stderr)+ if not result.stderr.endswith("\n"):+ sys.stderr.write("\n")+ log_warn(_t("install_uv_hint"))+ raise SystemExit(1)+ found = shutil.which("uv") or _find_uv_in_known_locations()if found:return found- return f"{_PYTHON} -m uv"+ # pip reported success but uv is nowhere we recognize — its Scripts/bin+ # dir is not on PATH. Reopening the shell almost always fixes this.+ log_error(_t("install_uv_not_on_path"))+ raise SystemExit(1)_UV: str | None = None@@ -827,9 +921,8 @@ def _install_dependencies() -> None:log_success(_t("install_uv_ok", version=uv_version or "unknown"))# --- detect Node.js / npm ---- node_version = _get_version(["node", "--version"])- _npm_cmd = _get_npm_command()- npm_version = _get_version([_npm_cmd, "--version"])+ node_version = _detect_command_version("node")+ npm_version = _detect_command_version("npm")if node_version and npm_version:log_success(_t("install_node_ok", version=node_version))@@ -847,8 +940,8 @@ def _install_dependencies() -> None:input(f" {_t('install_retry_node')}")except EOFError:pass- node_version = _get_version(["node", "--version"])- npm_version = _get_version(["npm", "--version"])+ node_version = _detect_command_version("node")+ npm_version = _detect_command_version("npm")if not (node_version and npm_version):log_error(_t("install_node_abort"))raise SystemExit(1)diff --git a/tests/agents/research/test_research_pipeline_rag.py b/tests/agents/research/test_research_pipeline_rag.pyindex 4acd4c99a..c411cbdb5 100644--- a/tests/agents/research/test_research_pipeline_rag.py+++ b/tests/agents/research/test_research_pipeline_rag.py@@ -15,6 +15,7 @@ These tests pin two contracts:from __future__ import annotationsimport json+from types import SimpleNamespacefrom typing import Anyimport pytest@@ -144,3 +145,50 @@ def test_decompose_agent_no_longer_falls_back_to_ai_textbook() -> None:assert agent.kb_name is None # NOT "ai_textbook"assert agent.enable_rag is False+++async def test_research_planning_forwards_attachments_when_rephrase_has_zero_iterations(+ tmp_path,+) -> None:+ """If rephrase is enabled but performs no LLM call, decompose is the first LLM."""+ config = _minimal_pipeline_config()+ config["planning"]["rephrase"] = {"enabled": True, "max_iterations": 0}+ attachment = object()+ captured: dict[str, Any] = {}++ class FakeDecomposeAgent:+ def set_citation_manager(self, citation_manager: Any) -> None:+ captured["citation_manager"] = citation_manager++ async def process(self, **kwargs: Any) -> dict[str, Any]:+ captured["decompose"] = kwargs+ return {+ "sub_topics": [],+ "sub_queries": [],+ "rag_context": "",+ "total_subtopics": 0,+ }++ pipeline = ResearchPipeline.__new__(ResearchPipeline)+ pipeline.config = config+ pipeline.attachments = [attachment]+ pipeline.pre_confirmed_outline = None+ pipeline.cache_dir = tmp_path+ pipeline.citation_manager = object()+ pipeline.agents = {+ "decompose": FakeDecomposeAgent(),+ "manager": SimpleNamespace(set_primary_topic=lambda _topic: None),+ }+ pipeline.queue = SimpleNamespace(blocks=[], get_statistics=lambda: {"total_blocks": 0})+ pipeline.logger = SimpleNamespace(+ info=lambda *_args, **_kwargs: None,+ success=lambda *_args, **_kwargs: None,+ warning=lambda *_args, **_kwargs: None,+ )+ pipeline._log_progress = lambda *_args, **_kwargs: None++ result = await pipeline._phase1_planning("Research this image")++ assert result == "Research this image"+ assert captured["decompose"]["attachments"] == [attachment]diff --git a/tests/core/test_capabilities_runtime.py b/tests/core/test_capabilities_runtime.pyindex f10b948df..bb28f5382 100644--- a/tests/core/test_capabilities_runtime.py+++ b/tests/core/test_capabilities_runtime.py@@ -10,10 +10,12 @@ from typing import Anyimport pytest+import deeptutor.agents.visualize.pipeline as visualize_pipelinefrom deeptutor.capabilities.chat import ChatCapabilityfrom deeptutor.capabilities.deep_question import DeepQuestionCapabilityfrom deeptutor.capabilities.deep_research import DeepResearchCapabilityfrom deeptutor.capabilities.deep_solve import DeepSolveCapability+from deeptutor.capabilities.visualize import VisualizeCapabilityfrom deeptutor.core.context import Attachment, UnifiedContextfrom deeptutor.core.stream import StreamEvent, StreamEventTypefrom deeptutor.core.stream_bus import StreamBus@@ -163,6 +165,7 @@ async def test_deep_solve_capability_bridges_solver_output(enabled_tools=enabled_tools,knowledge_bases=knowledge_bases,language="en",+ attachments=[Attachment(type="image", base64="ZmFrZQ==", filename="graph.png")],)capability = DeepSolveCapability()events = await _collect_events(lambda bus: capability.run(context, bus))@@ -170,6 +173,7 @@ async def test_deep_solve_capability_bridges_solver_output(assert captured["solver_init"]["enabled_tools"] == expected_toolsassert captured["solver_init"]["kb_name"] == expected_kbassert captured["solver_init"]["disable_planner_retrieve"] is expected_disable+ assert captured["solve"]["attachments"][0].filename == "graph.png"assert any(event.type == StreamEventType.PROGRESS and event.content == "solver-progress"for event in events@@ -304,11 +308,13 @@ async def test_deep_question_capability_uses_user_message_as_topic(user_message="linear algebra fundamentals",config_overrides={},language="en",+ attachments=[Attachment(type="image", base64="ZmFrZQ==", filename="topic.png")],)capability = DeepQuestionCapability()events = await _collect_events(lambda bus: capability.run(context, bus))assert captured["topic_call"]["user_topic"] == "linear algebra fundamentals"+ assert captured["topic_call"]["attachments"][0].filename == "topic.png"assert any(event.type == StreamEventType.PROGRESS and event.stage == "ideation" for event in events)@@ -316,6 +322,71 @@ async def test_deep_question_capability_uses_user_message_as_topic(assert "Question 1" in result_event.metadata["response"]+async def test_deep_question_mimic_uses_extracted_attachment_text_when_pdf_was_stripped(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ captured: dict[str, Any] = {}++ class FakeCoordinator:+ def __init__(self, **_kwargs: Any) -> None:+ self._callback = None++ def set_ws_callback(self, callback) -> None:+ self._callback = callback++ async def generate_from_exam(self, **_kwargs: Any) -> dict[str, Any]:+ raise AssertionError("raw PDF path should not be required after document extraction")++ async def generate_from_topic(self, **kwargs: Any) -> dict[str, Any]:+ captured["topic_call"] = kwargs+ return {+ "results": [+ {+ "qa_pair": {+ "question": "Question from attached paper?",+ "correct_answer": "Yes",+ "explanation": "The extracted document text was used.",+ }+ }+ ]+ }++ _install_module(+ monkeypatch,+ "deeptutor.agents.question.coordinator",+ AgentCoordinator=FakeCoordinator,+ )+ _install_module(+ monkeypatch,+ "deeptutor.services.llm.config",+ get_llm_config=lambda: SimpleNamespace(api_key="k", base_url="u", api_version="v1"),+ )++ context = UnifiedContext(+ user_message="[Attached Documents]\n[File: paper.pdf]\nExam text\n\n[User Question]\n",+ config_overrides={"mode": "mimic", "max_questions": 4},+ language="en",+ attachments=[+ Attachment(+ type="pdf",+ filename="paper.pdf",+ base64="",+ mime_type="application/pdf",+ )+ ],+ )++ capability = DeepQuestionCapability()+ events = await _collect_events(lambda bus: capability.run(context, bus))++ assert "Exam text" in captured["topic_call"]["user_topic"]+ assert captured["topic_call"]["num_questions"] == 4+ assert captured["topic_call"]["attachments"][0].filename == "paper.pdf"+ result_event = next(event for event in events if event.type == StreamEventType.RESULT)+ assert "Question 1" in result_event.metadata["response"]++@pytest.mark.asyncioasync def test_deep_question_capability_uses_single_call_followup_agent(monkeypatch: pytest.MonkeyPatch,@@ -504,6 +575,7 @@ async def test_deep_research_capability_requires_explicit_config_and_streams_trauser_message="agent-native tutoring",enabled_tools=["rag", "web_search", "paper_search"],knowledge_bases=["research-kb"],+ attachments=[Attachment(type="image", base64="ZmFrZQ==", filename="brief.png")],config_overrides={"mode": "report","depth": "standard",@@ -521,6 +593,7 @@ async def test_deep_research_capability_requires_explicit_config_and_streams_traevents = await _collect_events(lambda bus: capability.run(context, bus))config = captured["pipeline_init"]["config"]+ assert captured["pipeline_init"]["attachments"][0].filename == "brief.png"assert config["planning"]["decompose"]["mode"] == "auto"assert config["planning"]["decompose"]["auto_max_subtopics"] == 4assert config["researching"]["max_iterations"] == 3@@ -542,3 +615,76 @@ async def test_deep_research_capability_requires_explicit_config_and_streams_traassert tool_call_event.metadata["research_stage_card"] == "evidence"result_event = next(event for event in events if event.type == StreamEventType.RESULT)assert result_event.metadata["response"] == "Report about agent-native tutoring"+++async def test_visualize_capability_passes_attachments_to_analysis_agent(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ captured: dict[str, Any] = {}++ class FakeAnalysis:+ render_type = "svg"+ description = "A diagram"+ data_description = "diagram data"++ def model_dump(self) -> dict[str, Any]:+ return {+ "render_type": self.render_type,+ "description": self.description,+ "data_description": self.data_description,+ }++ class FakeReview:+ optimized_code = "<svg></svg>"+ changed = False+ review_notes = "ok"++ def model_dump(self) -> dict[str, Any]:+ return {+ "optimized_code": self.optimized_code,+ "changed": self.changed,+ "review_notes": self.review_notes,+ }++ class FakeVisualizePipeline:+ def __init__(self, **kwargs: Any) -> None:+ captured["init"] = kwargs++ async def run_analysis(self, **kwargs: Any) -> FakeAnalysis:+ captured["analysis"] = kwargs+ return FakeAnalysis()++ async def run_code_generation(self, **kwargs: Any) -> str:+ captured["code_generation"] = kwargs+ return "<svg></svg>"++ async def run_review(self, **kwargs: Any) -> FakeReview:+ captured["review"] = kwargs+ return FakeReview()++ monkeypatch.setattr(+ visualize_pipeline,+ "VisualizePipeline",+ FakeVisualizePipeline,+ )+ _install_module(+ monkeypatch,+ "deeptutor.services.llm.config",+ get_llm_config=lambda: SimpleNamespace(api_key="k", base_url="u", api_version="v1"),+ )++ context = UnifiedContext(+ user_message="make a figure",+ active_capability="visualize",+ config_overrides={"render_mode": "svg"},+ language="en",+ attachments=[Attachment(type="image", base64="ZmFrZQ==", filename="figure.png")],+ )++ capability = VisualizeCapability()+ events = await _collect_events(lambda bus: capability.run(context, bus))++ assert captured["analysis"]["attachments"][0].filename == "figure.png"+ result_event = next(event for event in events if event.type == StreamEventType.RESULT)+ assert result_event.metadata["render_type"] == "svg"diff --git a/web/app/(utility)/knowledge/page.tsx b/web/app/(utility)/knowledge/page.tsxindex 4fe699397..368328f60 100644--- a/web/app/(utility)/knowledge/page.tsx+++ b/web/app/(utility)/knowledge/page.tsx@@ -18,6 +18,7 @@ import {ArrowRight,Bookmark,BookOpen,+ Bot,CheckCircle2,ChevronDown,ChevronRight,@@ -1304,6 +1305,13 @@ function KnowledgePageContent() {color: "bg-sky-100 text-sky-700 dark:bg-sky-900/40 dark:text-sky-300",icon: MessageSquare,};+ case "tutorbot":+ return {+ label: t("Tutorbot"),+ color:+ "bg-violet-100 text-violet-700 dark:bg-violet-900/40 dark:text-violet-300",+ icon: Bot,+ };case "research":return {label: t("Research"),@@ -1646,13 +1654,9 @@ function KnowledgePageContent() {multipleclassName="hidden"onChange={(event) => {- setNewKbFiles((prev) =>- mergeSelectedFiles(- prev,- Array.from(event.target.files || []),- ),- );+ const picked = Array.from(event.target.files || []);event.target.value = "";+ setNewKbFiles((prev) => mergeSelectedFiles(prev, picked));}}/>@@ -1820,13 +1824,9 @@ function KnowledgePageContent() {multipleclassName="hidden"onChange={(event) => {- setUploadFiles((prev) =>- mergeSelectedFiles(- prev,- Array.from(event.target.files || []),- ),- );+ const picked = Array.from(event.target.files || []);event.target.value = "";+ setUploadFiles((prev) => mergeSelectedFiles(prev, picked));}}/>diff --git a/web/app/(workspace)/agents/[botId]/chat/page.tsx b/web/app/(workspace)/agents/[botId]/chat/page.tsxindex a6ba159d9..977064e07 100644--- a/web/app/(workspace)/agents/[botId]/chat/page.tsx+++ b/web/app/(workspace)/agents/[botId]/chat/page.tsx@@ -1,6 +1,7 @@"use client";-import { useCallback, useEffect, useRef, useState } from "react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import dynamic from "next/dynamic";import { useParams, useRouter } from "next/navigation";import { useTranslation } from "react-i18next";import { ArrowLeft, Bot, Loader2, Send } from "lucide-react";@@ -8,6 +9,17 @@ import { apiUrl, wsUrl } from "@/lib/api";import { firstParam } from "@/lib/route-params";import AssistantResponse from "@/components/common/AssistantResponse";import { SimpleComposerInput } from "@/components/chat/home/SimpleComposerInput";+import { downloadChatMarkdown } from "@/lib/chat-export";+import type { MessageItem } from "@/context/UnifiedChatContext";+import type {+ NotebookSaveMessage,+ NotebookSavePayload,+} from "@/components/notebook/SaveToNotebookModal";++const SaveToNotebookModal = dynamic(+ () => import("@/components/notebook/SaveToNotebookModal"),+ { ssr: false },+);interface BotInfo {bot_id: string;@@ -37,6 +49,59 @@ export default function BotChatPage() {const scrollRef = useRef<HTMLDivElement>(null);const inputRef = useRef<HTMLTextAreaElement>(null);+ const [showSaveModal, setShowSaveModal] = useState(false);++ const exportTitle = useMemo(() => {+ const firstUser = messages+ .find((m) => m.role === "user")+ ?.content.trim()+ .slice(0, 80);+ return firstUser || bot?.name || botId || "Bot Chat";+ }, [bot?.name, botId, messages]);++ const exportMessages = useMemo<MessageItem[]>(+ () =>+ messages.map((m) => ({+ role: m.role,+ content: m.content,+ })),+ [messages],+ );++ const notebookSaveMessages = useMemo<NotebookSaveMessage[]>(+ () =>+ messages.map((m) => ({+ role: m.role,+ content: m.content,+ })),+ [messages],+ );++ const notebookSavePayload = useMemo<NotebookSavePayload | null>(() => {+ if (!messages.length) return null;+ return {+ recordType: "tutorbot",+ title: exportTitle,+ // SaveToNotebookModal rebuilds userQuery / output from the user's+ // selected message subset; we just need a non-null payload here.+ userQuery: "",+ output: "",+ metadata: {+ source: "agent_chat",+ bot_id: botId ?? null,+ bot_name: bot?.name ?? null,+ total_message_count: messages.length,+ },+ };+ }, [bot?.name, botId, exportTitle, messages.length]);++ const handleDownloadMarkdown = useCallback(() => {+ if (!exportMessages.length) return;+ downloadChatMarkdown(exportMessages, { title: exportTitle });+ }, [exportMessages, exportTitle]);++ const handleCloseSaveModal = useCallback(() => setShowSaveModal(false), []);+const scrollToBottom = useCallback((behavior: ScrollBehavior = "smooth") => {requestAnimationFrame(() => {@@ -179,6 +244,23 @@ export default function BotChatPage() {{bot?.running && (<span className="h-2 w-2 rounded-full bg-emerald-500" />)}+ <div className="ml-auto flex items-center gap-2">+ <button+ onClick={() => setShowSaveModal(true)}+ disabled={!notebookSavePayload}+ className="rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)] disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:border-[var(--border)]/50 disabled:hover:text-[var(--muted-foreground)]"+ >+ {t("Save to Notebook")}+ </button>+ <button+ onClick={handleDownloadMarkdown}+ disabled={!messages.length}+ title={t("Download chat history as Markdown")}+ className="rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)] disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:border-[var(--border)]/50 disabled:hover:text-[var(--muted-foreground)]"+ >+ {t("Download Markdown")}+ </button>+ </div></div>{/* Messages */}@@ -280,6 +362,13 @@ export default function BotChatPage() {</button></div></div>++ <SaveToNotebookModal+ open={showSaveModal}+ payload={notebookSavePayload}+ messages={notebookSaveMessages}+ onClose={handleCloseSaveModal}+ /></div>);}diff --git a/web/app/(workspace)/chat/[[...sessionId]]/page.tsx b/web/app/(workspace)/chat/[[...sessionId]]/page.tsxindex 9977414f8..6e448fdb4 100644--- a/web/app/(workspace)/chat/[[...sessionId]]/page.tsx+++ b/web/app/(workspace)/chat/[[...sessionId]]/page.tsx@@ -25,10 +25,16 @@ import type { SelectedHistorySession } from "@/components/chat/HistorySessionPicimport type { SelectedQuestionEntry } from "@/components/chat/QuestionBankPicker";import ChatComposer from "@/components/chat/home/ChatComposer";import { ChatMessageList } from "@/components/chat/home/ChatMessages";+// Imported eagerly so the drawer shell is always mounted off-screen —+// clicking a chip becomes a single CSS class flip, no chunk fetch + double+// render. The heavy renderers inside still load lazily.+import FilePreviewDrawer from "@/components/chat/preview/FilePreviewDrawer";import {useUnifiedChat,+ type MessageAttachment,type MessageRequestSnapshot,} from "@/context/UnifiedChatContext";+import type { FilePreviewSource } from "@/components/chat/preview/previewerFor";import type { StreamEvent } from "@/lib/unified-ws";import {extractBase64FromDataUrl,@@ -255,6 +261,9 @@ export default function ChatPage() {const [attachments, setAttachments] = useState<PendingAttachment[]>([]);const [dragging, setDragging] = useState(false);const [attachmentError, setAttachmentError] = useState<string | null>(null);+ const [previewSource, setPreviewSource] = useState<FilePreviewSource | null>(+ null,+ );const attachmentErrorTimer = useRef<ReturnType<typeof setTimeout> | null>(null);const [capMenuOpen, setCapMenuOpen] = useState(false);const [quizConfig, setQuizConfig] = useState<DeepQuestionFormConfig>({@@ -749,6 +758,40 @@ export default function ChatPage() {setAttachments((prev) => prev.filter((_, i) => i !== index));}, []);+ const handlePreviewPendingAttachment = useCallback(+ (index: number) => {+ const a = attachments[index];+ if (!a) return;+ setPreviewSource({+ filename: a.filename,+ mimeType: a.mimeType,+ type: a.type,+ base64: a.base64,+ size: a.size,+ });+ },+ [attachments],+ );++ const handlePreviewMessageAttachment = useCallback(+ (a: MessageAttachment) => {+ setPreviewSource({+ filename: a.filename || "",+ mimeType: a.mime_type,+ type: a.type,+ url: a.url,+ base64: a.base64,+ extractedText: a.extracted_text,+ id: a.id,+ });+ },+ [],+ );++ const handleClosePreview = useCallback(() => {+ setPreviewSource(null);+ }, []);+const handleDragEnter = useCallback((e: React.DragEvent) => {e.preventDefault();e.stopPropagation();@@ -1015,7 +1058,17 @@ export default function ChatPage() {}, [state.messages]);return (- <div className="flex h-full flex-col overflow-hidden bg-[var(--background)]">+ <div+ // When the preview drawer is open AND the viewport is wide enough,+ // push the chat content to the left by the drawer's width so the two+ // panels live side-by-side (matches Claude desktop). On smaller+ // screens the drawer overlays — squeezing a phone-width chat into+ // the remaining ~30 px would be useless. The actual padding ++ // transition lives in `chat-preview-shell` (globals.css) so we can+ // hand-tune it without fighting Tailwind's arbitrary-value parser.+ data-preview-open={previewSource ? "true" : "false"}+ className="chat-preview-shell flex h-full flex-col overflow-hidden bg-[var(--background)]"+ ><div className="mx-auto flex w-full max-w-[960px] items-center justify-between px-6 pt-3 pb-0"><span className="text-[15px] font-semibold tracking-[-0.01em] text-[var(--foreground)]">{t(activeCap.label)}@@ -1085,6 +1138,7 @@ export default function ChatPage() {onCopyAssistantMessage={copyAssistantMessage}onRegenerateMessage={handleRegenerateMessage}onConfirmOutline={handleConfirmOutline}+ onPreviewAttachment={handlePreviewMessageAttachment}/><div ref={messagesEndRef} className="h-px w-full shrink-0" /></div>@@ -1150,6 +1204,7 @@ export default function ChatPage() {onToggleResearchSource={toggleResearchSource}onSend={handleSend}onRemoveAttachment={removeAttachment}+ onPreviewAttachment={handlePreviewPendingAttachment}onRemoveHistory={handleRemoveHistory}onRemoveNotebook={handleRemoveNotebook}onRemoveQuestion={handleRemoveQuestion}@@ -1190,6 +1245,11 @@ export default function ChatPage() {messages={chatSaveMessages}onClose={handleCloseSaveModal}/>+ <FilePreviewDrawer+ open={previewSource !== null}+ source={previewSource}+ onClose={handleClosePreview}+ /></div>);}diff --git a/web/app/globals.css b/web/app/globals.cssindex 3dda8928b..fb7106244 100644--- a/web/app/globals.css+++ b/web/app/globals.css@@ -552,3 +552,18 @@.session-pulse {animation: session-pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;}++/* ----- Chat shell ↔ file preview drawer ---------------------------------+ Squeezes the chat column when the drawer is open. The transition+ timing here MUST match FilePreviewDrawer's transform transition so the+ slide-in and the squeeze animate as one motion. Stays a no-op below+ the lg breakpoint, where the drawer overlays instead. */+.chat-preview-shell {+ transition: padding-right 220ms ease-out;+ padding-right: 0;+}+@media (min-width: 1024px) {+ .chat-preview-shell[data-preview-open="true"] {+ padding-right: min(560px, 92vw);+ }+}diff --git a/web/components/chat/home/ChatComposer.tsx b/web/components/chat/home/ChatComposer.tsxindex cca51141d..4f62e9218 100644--- a/web/components/chat/home/ChatComposer.tsx+++ b/web/components/chat/home/ChatComposer.tsx@@ -158,6 +158,7 @@ export default memo(function ChatComposer({onToggleResearchSource,onSend,onRemoveAttachment,+ onPreviewAttachment,onRemoveHistory,onRemoveNotebook,onRemoveQuestion,@@ -239,6 +240,7 @@ export default memo(function ChatComposer({onToggleResearchSource: (source: ResearchSource) => void;onSend: (content: string) => void;onRemoveAttachment: (index: number) => void;+ onPreviewAttachment?: (index: number) => void;onRemoveHistory: (sessionId: string) => void;onRemoveNotebook: (notebookId: string) => void;onRemoveQuestion: (entryId: number) => void;@@ -440,13 +442,21 @@ export default memo(function ChatComposer({{!!attachments.length && (<div className="flex flex-wrap gap-2 px-4 pb-2">{attachments.map((a, i) => {+ const previewLabel = t("Preview");+ const removeLabel = t("Remove attachment");if (a.type === "image" && a.previewUrl) {return (<divkey={`${a.filename}-${i}`}className="group relative">- <div className="relative h-16 w-16 overflow-hidden rounded-lg border border-[var(--border)]">+ <button+ type="button"+ onClick={() => onPreviewAttachment?.(i)}+ title={a.filename || previewLabel}+ aria-label={previewLabel}+ className="relative block h-16 w-16 overflow-hidden rounded-lg border border-[var(--border)] transition-shadow hover:shadow-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--primary)]/40"+ ><Imagesrc={a.previewUrl}alt={a.filename || t("Attachment preview")}@@ -454,13 +464,18 @@ export default memo(function ChatComposer({unoptimizedclassName="object-cover"/>- <button- onClick={() => onRemoveAttachment(i)}- className="absolute -right-1.5 -top-1.5 flex h-4 w-4 items-center justify-center rounded-full bg-[var(--foreground)] text-[var(--background)] opacity-0 shadow-sm transition-opacity group-hover:opacity-100"- >- <X size={10} />- </button>- </div>+ </button>+ <button+ type="button"+ onClick={(e) => {+ e.stopPropagation();+ onRemoveAttachment(i);+ }}+ aria-label={removeLabel}+ className="absolute -right-1.5 -top-1.5 flex h-4 w-4 items-center justify-center rounded-full bg-[var(--foreground)] text-[var(--background)] opacity-0 shadow-sm transition-opacity group-hover:opacity-100"+ >+ <X size={10} />+ </button></div>);}@@ -471,7 +486,12 @@ export default memo(function ChatComposer({className="group relative"title={a.filename}>- <div className="relative h-16 w-16 overflow-hidden rounded-lg border border-[var(--border)] bg-[var(--card)]">+ <button+ type="button"+ onClick={() => onPreviewAttachment?.(i)}+ aria-label={previewLabel}+ className="relative block h-16 w-16 overflow-hidden rounded-lg border border-[var(--border)] bg-[var(--card)] transition-shadow hover:shadow-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--primary)]/40"+ >{/* Native <img> is safe for SVG: scripts inside anSVG don't execute under <img> context. Next.js<Image> rejects SVG by default. */}@@ -481,13 +501,18 @@ export default memo(function ChatComposer({alt={a.filename || t("Attachment preview")}className="h-full w-full object-contain p-1"/>- <button- onClick={() => onRemoveAttachment(i)}- className="absolute -right-1.5 -top-1.5 flex h-4 w-4 items-center justify-center rounded-full bg-[var(--foreground)] text-[var(--background)] opacity-0 shadow-sm transition-opacity group-hover:opacity-100"- >- <X size={10} />- </button>- </div>+ </button>+ <button+ type="button"+ onClick={(e) => {+ e.stopPropagation();+ onRemoveAttachment(i);+ }}+ aria-label={removeLabel}+ className="absolute -right-1.5 -top-1.5 flex h-4 w-4 items-center justify-center rounded-full bg-[var(--foreground)] text-[var(--background)] opacity-0 shadow-sm transition-opacity group-hover:opacity-100"+ >+ <X size={10} />+ </button></div>);}@@ -500,7 +525,12 @@ export default memo(function ChatComposer({className="group relative"title={a.filename}>- <div className="flex h-16 w-[160px] items-center gap-2.5 rounded-lg border border-[var(--border)] bg-[var(--card)] px-2.5">+ <button+ type="button"+ onClick={() => onPreviewAttachment?.(i)}+ aria-label={previewLabel}+ className="flex h-16 w-[160px] items-center gap-2.5 rounded-lg border border-[var(--border)] bg-[var(--card)] px-2.5 text-left transition-colors hover:border-[var(--primary)]/40 hover:bg-[var(--muted)]/30 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--primary)]/40"+ ><div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-md bg-[var(--muted)]/60"><Iconsize={22}@@ -516,9 +546,14 @@ export default memo(function ChatComposer({{sizeLabel ? `${spec.label} · ${sizeLabel}` : spec.label}</div></div>- </div>+ </button><button- onClick={() => onRemoveAttachment(i)}+ type="button"+ onClick={(e) => {+ e.stopPropagation();+ onRemoveAttachment(i);+ }}+ aria-label={removeLabel}className="absolute -right-1.5 -top-1.5 flex h-4 w-4 items-center justify-center rounded-full bg-[var(--foreground)] text-[var(--background)] opacity-0 shadow-sm transition-opacity group-hover:opacity-100"><X size={10} />diff --git a/web/components/chat/home/ChatMessages.tsx b/web/components/chat/home/ChatMessages.tsxindex c94ba87a5..e1b8c1287 100644--- a/web/components/chat/home/ChatMessages.tsx+++ b/web/components/chat/home/ChatMessages.tsx@@ -18,7 +18,10 @@ import { useTranslation } from "react-i18next";import type { SelectedHistorySession } from "@/components/chat/HistorySessionPicker";import type { SelectedQuestionEntry } from "@/components/chat/QuestionBankPicker";import AssistantResponse from "@/components/common/AssistantResponse";-import type { MessageRequestSnapshot } from "@/context/UnifiedChatContext";+import type {+ MessageAttachment,+ MessageRequestSnapshot,+} from "@/context/UnifiedChatContext";import { docIconFor } from "@/lib/doc-attachments";import { extractMathAnimatorResult } from "@/lib/math-animator-types";import { extractQuizQuestions } from "@/lib/quiz-types";@@ -48,12 +51,7 @@ interface ChatMessageItem {content: string;capability?: string;events?: StreamEvent[];- attachments?: Array<{- type: string;- filename?: string;- base64?: string;- mime_type?: string;- }>;+ attachments?: MessageAttachment[];requestSnapshot?: MessageRequestSnapshot;}@@ -286,9 +284,11 @@ function RoughActionButton({const UserMessage = memo(function UserMessage({msg,index,+ onPreviewAttachment,}: {msg: ChatMessageItem;index: number;+ onPreviewAttachment?: (attachment: MessageAttachment) => void;}) {const { t } = useTranslation();if (msg.content.startsWith("[Quiz Performance]")) return null;@@ -304,22 +304,30 @@ const UserMessage = memo(function UserMessage({{msg.attachments?.some((a) => a.type === "image") && (<div className="flex flex-wrap justify-end gap-2">{msg.attachments- .filter((a) => a.type === "image" && a.base64)- .map((a, ai) => (- <div- key={`img-${ai}`}- className="overflow-hidden rounded-2xl border border-[var(--border)]"- >- <Image- src={`data:image/png;base64,${a.base64}`}- alt={a.filename || t("image")}- width={280}- height={192}- unoptimized- className="max-h-48 max-w-[280px] rounded-2xl object-contain"- />- </div>- ))}+ .filter((a) => a.type === "image" && (a.base64 || a.url))+ .map((a, ai) => {+ const src = a.url+ ? a.url+ : `data:image/png;base64,${a.base64}`;+ return (+ <button+ key={`img-${ai}`}+ type="button"+ onClick={() => onPreviewAttachment?.(a)}+ title={a.filename || t("image")}+ className="overflow-hidden rounded-2xl border border-[var(--border)] transition-shadow hover:shadow-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--primary)]/40"+ >+ <Image+ src={src}+ alt={a.filename || t("image")}+ width={280}+ height={192}+ unoptimized+ className="max-h-48 max-w-[280px] rounded-2xl object-contain"+ />+ </button>+ );+ })}</div>)}{msg.attachments?.some((a) => a.type !== "image") && (@@ -330,14 +338,16 @@ const UserMessage = memo(function UserMessage({const filename = a.filename || t("Attachment");const spec = docIconFor(filename);const Icon = spec.Icon;- const href =- a.base64 && a.mime_type- ? `data:${a.mime_type};base64,${a.base64}`- : null;const cardClass =- "flex h-14 w-[220px] items-center gap-2.5 rounded-xl border border-[var(--border)] bg-[var(--card)] px-2.5 shadow-sm transition-colors hover:border-[var(--border)]/80";- const inner = (- <>+ "flex h-14 w-[220px] items-center gap-2.5 rounded-xl border border-[var(--border)] bg-[var(--card)] px-2.5 text-left shadow-sm transition-colors hover:border-[var(--primary)]/40 hover:bg-[var(--muted)]/30 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--primary)]/40";+ return (+ <button+ key={`doc-${ai}`}+ type="button"+ onClick={() => onPreviewAttachment?.(a)}+ title={filename}+ className={cardClass}+ ><div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md bg-[var(--muted)]/60"><Iconsize={20}@@ -353,26 +363,7 @@ const UserMessage = memo(function UserMessage({{spec.label}</div></div>- </>- );- return href ? (- <a- key={`doc-${ai}`}- href={href}- download={filename}- title={filename}- className={cardClass}- >- {inner}- </a>- ) : (- <div- key={`doc-${ai}`}- title={filename}- className={cardClass}- >- {inner}- </div>+ </button>);})}</div>@@ -511,6 +502,7 @@ export const ChatMessageList = memo(function ChatMessageList({onCopyAssistantMessage,onRegenerateMessage,onConfirmOutline,+ onPreviewAttachment,}: {messages: ChatMessageItem[];isStreaming: boolean;@@ -527,6 +519,7 @@ export const ChatMessageList = memo(function ChatMessageList({topic: string,researchConfig?: Record<string, unknown> | null,) => void;+ onPreviewAttachment?: (attachment: MessageAttachment) => void;}) {const { t } = useTranslation();const outlineStatusByIndex = useMemo(() => {@@ -597,7 +590,14 @@ export const ChatMessageList = memo(function ChatMessageList({{messageRows.map(({ msg, originalIndex, pairedUserMessage }) => {const i = originalIndex;if (msg.role === "user") {- return <UserMessage key={`${msg.role}-${i}`} msg={msg} index={i} />;+ return (+ <UserMessage+ key={`${msg.role}-${i}`}+ msg={msg}+ index={i}+ onPreviewAttachment={onPreviewAttachment}+ />+ );}const isActiveAssistant = isStreaming && i === messages.length - 1;diff --git a/web/components/chat/preview/FilePreviewDrawer.tsx b/web/components/chat/preview/FilePreviewDrawer.tsxnew file mode 100644index 000000000..eda67acbb--- /dev/null+++ b/web/components/chat/preview/FilePreviewDrawer.tsx@@ -0,0 +1,305 @@+"use client";++import { memo, useCallback, useEffect, useRef, useState } from "react";+import dynamic from "next/dynamic";+import { Check, Copy, Download, X } from "lucide-react";+import { useTranslation } from "react-i18next";+import { docIconFor, formatBytes } from "@/lib/doc-attachments";+import { apiUrl } from "@/lib/api";+import {+ type FilePreviewSource,+ previewKindFor,+ resolveSourceUrl,+} from "./previewerFor";++// Heavy renderers are lazy so opening the drawer with a small image doesn't+// pay the cost of loading the markdown / code-highlight chunks.+const PdfPreview = dynamic(() => import("./previewers/PdfPreview"));+const ImagePreview = dynamic(() => import("./previewers/ImagePreview"));+const SvgPreview = dynamic(() => import("./previewers/SvgPreview"));+const MarkdownPreview = dynamic(() => import("./previewers/MarkdownPreview"));+const TextPreview = dynamic(() => import("./previewers/TextPreview"));+const OfficeTextPreview = dynamic(+ () => import("./previewers/OfficeTextPreview"),+);+const FallbackPreview = dynamic(() => import("./previewers/FallbackPreview"));++const ANIM_MS = 220;++interface FilePreviewDrawerProps {+ open: boolean;+ source: FilePreviewSource | null;+ onClose: () => void;+}++/**+ * Right-side slide-in drawer that previews a chat attachment.+ *+ * Design notes+ * ────────────+ * • No backdrop. The drawer sits alongside the chat so the user can still+ * read messages or send replies — closer to Claude desktop's "side panel"+ * than a modal dialog.+ * • The shell is **always mounted**, parked off-screen at translate-x-full.+ * That way every open is a single class flip and CSS handles the rest —+ * no double-render, no requestAnimationFrame dance, no delay before the+ * slide starts. Only the body content (header + preview) is conditionally+ * rendered, latched during the exit transition so it doesn't tear.+ * • Renderers are lazy so opening a small image doesn't drag in markdown /+ * syntax-highlight chunks.+ */+export default function FilePreviewDrawer({+ open,+ source,+ onClose,+}: FilePreviewDrawerProps) {+ const { t } = useTranslation();++ // Latch the most recently shown source so the body keeps rendering during+ // the slide-out transition.+ const [renderedSource, setRenderedSource] = useState<FilePreviewSource | null>(+ null,+ );+ // The HEAVY preview body (markdown / syntax-highlight) is gated on this+ // flag and only mounts AFTER the slide-in finishes. The chat-page's+ // padding-right transition lives on the main thread, and so does+ // react-markdown's reconciliation — if both run at once, the markdown+ // work eats every frame and the chat squeeze visibly stalls. Deferring+ // the body keeps the main thread free for the slide animations.+ const [bodyMounted, setBodyMounted] = useState(false);+ const closeBtnRef = useRef<HTMLButtonElement>(null);++ // Mirror `source` synchronously DURING render. React commits a single+ // render where both `renderedSource` and the outer slide class flip+ // together — that single paint also fires the chat-page's padding+ // transition, so the drawer slide and the chat squeeze launch in+ // lock-step (no one-frame gap from a useEffect-driven latch).+ //+ // We also reset `bodyMounted` here so a switch to a new source doesn't+ // momentarily render the heavy body before the deferring effect kicks in.+ if (open && source && source !== renderedSource) {+ setRenderedSource(source);+ setBodyMounted(false);+ }++ // After close, defer the body unmount until the slide-out animation has+ // had time to play. The cleanup cancels the pending unmount if the user+ // re-opens before it fires.+ useEffect(() => {+ if (!open && renderedSource) {+ const timer = setTimeout(() => setRenderedSource(null), ANIM_MS);+ return () => clearTimeout(timer);+ }+ }, [open, renderedSource]);++ // After the slide-in completes, mount the heavy body. Done in an effect+ // so the timer is scoped to the open lifecycle (cleanup cancels it if+ // the user closes before it fires).+ useEffect(() => {+ if (open && renderedSource && !bodyMounted) {+ const timer = setTimeout(() => setBodyMounted(true), ANIM_MS);+ return () => clearTimeout(timer);+ }+ }, [open, renderedSource, bodyMounted]);++ // `visible` derives directly from `open`, so it flips in the very same+ // render where the parent's `previewSource` flipped — same instant the+ // chat's padding-right transition starts.+ const visible = open;++ // Focus the close button on open so keyboard users can immediately ESC.+ useEffect(() => {+ if (visible) closeBtnRef.current?.focus();+ }, [visible]);++ // ESC closes (only while visible — listening on document is fine since the+ // drawer is global).+ useEffect(() => {+ if (!visible) return;+ const onKey = (e: KeyboardEvent) => {+ if (e.key === "Escape") {+ e.stopPropagation();+ onClose();+ }+ };+ document.addEventListener("keydown", onKey);+ return () => document.removeEventListener("keydown", onKey);+ }, [visible, onClose]);++ const previewUrl = renderedSource+ ? resolveSourceUrl(renderedSource, apiUrl)+ : null;+ const downloadUrl = previewUrl;+ const previewKind = renderedSource ? previewKindFor(renderedSource) : null;++ const [copied, setCopied] = useState(false);+ const handleCopy = useCallback(async () => {+ if (!downloadUrl) return;+ try {+ await navigator.clipboard.writeText(downloadUrl);+ setCopied(true);+ setTimeout(() => setCopied(false), 1500);+ } catch {+ // Clipboard rejected (insecure context / permission). Silently noop —+ // the user can still right-click the download link.+ }+ }, [downloadUrl]);++ const filename = renderedSource?.filename || t("Attachment");+ const spec = docIconFor(filename);+ const HeaderIcon = spec.Icon;+ const sizeLabel = renderedSource?.size ? formatBytes(renderedSource.size) : "";++ return (+ <div+ role="dialog"+ aria-hidden={!visible}+ aria-label={t("File preview: {{name}}", { name: filename })}+ className={`fixed right-0 top-0 z-[90] flex h-full w-[min(560px,92vw)] flex-col border-l border-[var(--border)] bg-[var(--card)] shadow-2xl transition-transform ease-out ${+ visible ? "translate-x-0" : "translate-x-full"+ }`}+ style={{+ // Hand the transform to the GPU compositor for a buttery slide.+ willChange: "transform",+ transitionDuration: `${ANIM_MS}ms`,+ // While off-screen the drawer must not steal pointer events from+ // the chat behind it.+ pointerEvents: visible ? "auto" : "none",+ }}+ >+ {renderedSource && (+ <>+ {/* Header */}+ <div className="flex items-center gap-2 border-b border-[var(--border)] bg-[var(--card)] px-4 py-3">+ <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md bg-[var(--muted)]/60">+ <HeaderIcon size={18} strokeWidth={1.5} className={spec.tint} />+ </div>+ <div className="min-w-0 flex-1">+ <div className="truncate text-[13px] font-medium text-[var(--foreground)]">+ {filename}+ </div>+ <div className="truncate text-[10px] uppercase tracking-wide text-[var(--muted-foreground)]">+ {sizeLabel ? `${spec.label} · ${sizeLabel}` : spec.label}+ </div>+ </div>++ {downloadUrl && (+ <a+ href={downloadUrl}+ download={filename}+ title={t("Download")}+ aria-label={t("Download")}+ className="flex h-8 w-8 items-center justify-center rounded-lg text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"+ >+ <Download size={14} strokeWidth={1.7} />+ </a>+ )}+ {downloadUrl && (+ <button+ type="button"+ onClick={handleCopy}+ title={t("Copy link")}+ aria-label={t("Copy link")}+ className="flex h-8 w-8 items-center justify-center rounded-lg text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"+ >+ {copied ? (+ <Check+ size={14}+ strokeWidth={1.7}+ className="text-emerald-500"+ />+ ) : (+ <Copy size={14} strokeWidth={1.7} />+ )}+ </button>+ )}+ <button+ ref={closeBtnRef}+ type="button"+ onClick={onClose}+ title={t("Close")}+ aria-label={t("Close")}+ className="flex h-8 w-8 items-center justify-center rounded-lg text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"+ >+ <X size={15} strokeWidth={1.8} />+ </button>+ </div>++ {/* Body — mounted only after the slide-in animation is done so its+ (potentially expensive) markdown / syntax-highlight render can't+ steal main-thread frames from the chat squeeze. */}+ <div className="relative flex-1 overflow-hidden">+ {bodyMounted && (+ <PreviewBody+ source={renderedSource}+ previewUrl={previewUrl}+ kind={previewKind}+ />+ )}+ </div>+ </>+ )}+ </div>+ );+}++// Memoised so the close-time re-render of the outer drawer does NOT reconcile+// the heavy markdown / syntax-highlight tree underneath (which can take+// 10–50 ms with math + code blocks and was the visible "stutter" before the+// slide-out started). With stable source/previewUrl/kind props, memo bails+// the entire body subtree.+const PreviewBody = memo(function PreviewBody({+ source,+ previewUrl,+ kind,+}: {+ source: FilePreviewSource;+ previewUrl: string | null;+ kind: ReturnType<typeof previewKindFor> | null;+}) {+ const filename = source.filename;++ // Office docs lean on extracted_text and degrade gracefully via the+ // OfficeTextPreview, even when previewUrl is missing (legacy messages).+ if (kind === "office-text") {+ return (+ <OfficeTextPreview+ filename={filename}+ extractedText={source.extractedText}+ url={previewUrl}+ />+ );+ }++ // Everything else needs a fetchable URL. Without one we fall back.+ if (!previewUrl) {+ return <FallbackPreview filename={filename} url={null} reason="legacy" />;+ }++ switch (kind) {+ case "pdf":+ return <PdfPreview url={previewUrl} filename={filename} />;+ case "image":+ return <ImagePreview url={previewUrl} filename={filename} />;+ case "svg":+ return <SvgPreview url={previewUrl} filename={filename} />;+ case "markdown":+ return (+ <div className="h-full overflow-y-auto">+ <MarkdownPreview url={previewUrl} />+ </div>+ );+ case "code":+ case "text":+ return (+ <div className="h-full overflow-y-auto">+ <TextPreview url={previewUrl} filename={filename} />+ </div>+ );+ case "fallback":+ default:+ return <FallbackPreview filename={filename} url={previewUrl} />;+ }+});++PreviewBody.displayName = "PreviewBody";diff --git a/web/components/chat/preview/previewerFor.ts b/web/components/chat/preview/previewerFor.tsnew file mode 100644index 000000000..880feb9ed--- /dev/null+++ b/web/components/chat/preview/previewerFor.ts@@ -0,0 +1,114 @@+/**+ * Maps a chat attachment to the preview renderer it should use.+ *+ * The drawer uses the returned ``kind`` to dynamically import the matching+ * renderer (see ``./previewers/*.tsx``). Office binaries (DOCX/XLSX/PPTX)+ * cannot be rendered natively in the browser, so we fall back to the+ * extractor's plain-text output when present, or to a download-only+ * affordance otherwise.+ */++import { langForFilename } from "@/lib/code-languages";+import { extOf } from "@/lib/doc-attachments";++export type PreviewKind =+ | "pdf"+ | "image"+ | "svg"+ | "markdown"+ | "code"+ | "text"+ | "office-text"+ | "fallback";++export interface FilePreviewSource {+ /** Display name; also used to derive the file extension. */+ filename: string;+ /** MIME type when known (image/png, application/pdf, …). */+ mimeType?: string;+ /** Backend classification — "image" or anything else. Useful for+ * attachments where the filename has no extension but the MIME is set. */+ type?: string;+ /** Public URL served by /api/attachments. Preferred over base64. */+ url?: string;+ /** Inline base64 payload — only present for pending (un-sent) attachments+ * or messages that pre-date the storage rollout. */+ base64?: string;+ /** Plain-text rendering of office docs, populated by the backend. */+ extractedText?: string;+ /** Original byte size, used for empty-state copy. */+ size?: number;+ /** Stable id; lets the drawer build a stable React key. */+ id?: string;+}++const OFFICE_BINARY_EXTS = new Set([".docx", ".xlsx", ".pptx"]);+const MARKDOWN_EXTS = new Set([".md", ".markdown", ".rst", ".asciidoc"]);+const PLAIN_TEXT_EXTS = new Set([+ ".txt",+ ".text",+ ".log",+ ".csv",+ ".tsv",+ ".env",+ ".conf",+]);+const RASTER_IMAGE_EXTS = new Set([+ ".png",+ ".jpg",+ ".jpeg",+ ".gif",+ ".webp",+ ".bmp",+ ".tif",+ ".tiff",+ ".avif",+]);++/** Heuristic: does *source* refer to an image we can render via <img>? */+function isImage(source: FilePreviewSource, ext: string): boolean {+ if (RASTER_IMAGE_EXTS.has(ext)) return true;+ if (source.mimeType?.startsWith("image/") && source.mimeType !== "image/svg+xml")+ return true;+ if (source.type === "image") return true;+ return false;+}++export function previewKindFor(source: FilePreviewSource): PreviewKind {+ const ext = extOf(source.filename || "");+ const mime = source.mimeType || "";++ if (ext === ".pdf" || mime === "application/pdf") return "pdf";+ if (ext === ".svg" || mime === "image/svg+xml") return "svg";+ if (isImage(source, ext)) return "image";+ if (MARKDOWN_EXTS.has(ext) || mime === "text/markdown") return "markdown";+ if (OFFICE_BINARY_EXTS.has(ext)) return "office-text";+ // Catches both extension-based mappings (.js, .ts, .go, .vue, .lua, …)+ // and special filenames without extensions (Dockerfile, Makefile, …).+ if (langForFilename(source.filename || "")) return "code";+ if (PLAIN_TEXT_EXTS.has(ext) || mime.startsWith("text/")) return "text";+ return "fallback";+}++/**+ * Build the in-browser-loadable URL for the preview, falling back to a+ * data URL when the original file lives only as base64 in memory (the+ * pending-attachment case in the composer).+ *+ * Returns ``null`` when neither is available; renderers should then show a+ * "preview not available" affordance.+ */+export function resolveSourceUrl(+ source: FilePreviewSource,+ apiUrl: (path: string) => string,+): string | null {+ if (source.url) {+ return source.url.startsWith("http") || source.url.startsWith("blob:")+ ? source.url+ : apiUrl(source.url);+ }+ if (source.base64 && source.mimeType) {+ return `data:${source.mimeType};base64,${source.base64}`;+ }+ return null;+}diff --git a/web/components/chat/preview/previewers/FallbackPreview.tsx b/web/components/chat/preview/previewers/FallbackPreview.tsxnew file mode 100644index 000000000..706f99fb0--- /dev/null+++ b/web/components/chat/preview/previewers/FallbackPreview.tsx@@ -0,0 +1,55 @@+"use client";++import { Download, FileQuestion } from "lucide-react";+import { useTranslation } from "react-i18next";+import { docIconFor } from "@/lib/doc-attachments";++/**+ * Last-resort preview: a centred icon + filename + Download CTA. Used for+ * encrypted PDFs we cannot iframe, exotic binary formats, or attachments+ * predating the storage rollout where the URL is missing.+ */+export default function FallbackPreview({+ filename,+ url,+ reason,+}: {+ filename: string;+ url: string | null;+ reason?: "legacy" | "unsupported";+}) {+ const { t } = useTranslation();+ const spec = docIconFor(filename);+ const Icon = url ? spec.Icon : FileQuestion;+ const tint = url ? spec.tint : "text-[var(--muted-foreground)]";++ return (+ <div className="flex h-full w-full flex-col items-center justify-center gap-4 p-8 text-center">+ <div className="flex h-20 w-20 items-center justify-center rounded-2xl bg-[var(--muted)]/60">+ <Icon size={40} strokeWidth={1.4} className={tint} />+ </div>+ <div className="space-y-1">+ <div className="text-[14px] font-medium text-[var(--foreground)]">+ {filename}+ </div>+ <div className="text-[12px] text-[var(--muted-foreground)]">+ {reason === "legacy"+ ? t(+ "Original file is not stored (sent before preview was supported).",+ )+ : t("Preview is not available for this file type.")}+ </div>+ </div>+ {url && (+ <a+ href={url}+ download={filename}+ className="inline-flex items-center gap-2 rounded-lg border border-[var(--border)] bg-[var(--card)] px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--primary)]/40 hover:text-[var(--primary)]"+ >+ <Download size={13} strokeWidth={1.7} />+ {t("Download")}+ </a>+ )}+ </div>+ );+}diff --git a/web/components/chat/preview/previewers/ImagePreview.tsx b/web/components/chat/preview/previewers/ImagePreview.tsxnew file mode 100644index 000000000..69f6bc5c9--- /dev/null+++ b/web/components/chat/preview/previewers/ImagePreview.tsx@@ -0,0 +1,62 @@+"use client";++import { useState } from "react";+import { useTranslation } from "react-i18next";+import { Loader2 } from "lucide-react";++/**+ * Image preview. Uses a native <img> instead of next/image because:+ * 1. The /api/attachments URL is dynamic per-session and not in the+ * next.config remotePatterns whitelist.+ * 2. We want object-contain centering against a checkered backdrop.+ *+ * Data URLs (the pending-attachment case) work the same way.+ */+export default function ImagePreview({+ url,+ filename,+}: {+ url: string;+ filename: string;+}) {+ const { t } = useTranslation();+ const [state, setState] = useState<"loading" | "ready" | "error">("loading");++ return (+ <div+ className="relative flex h-full w-full items-center justify-center bg-[var(--muted)]/30"+ style={{+ backgroundImage:+ "linear-gradient(45deg, rgba(0,0,0,0.04) 25%, transparent 25%), " ++ "linear-gradient(-45deg, rgba(0,0,0,0.04) 25%, transparent 25%), " ++ "linear-gradient(45deg, transparent 75%, rgba(0,0,0,0.04) 75%), " ++ "linear-gradient(-45deg, transparent 75%, rgba(0,0,0,0.04) 75%)",+ backgroundSize: "16px 16px",+ backgroundPosition: "0 0, 0 8px, 8px -8px, -8px 0px",+ }}+ >+ {state === "loading" && (+ <div className="pointer-events-none absolute inset-0 z-10 flex items-center justify-center">+ <Loader2+ size={16}+ className="animate-spin text-[var(--muted-foreground)]"+ />+ </div>+ )}+ {state === "error" ? (+ <div className="text-[12px] text-[var(--muted-foreground)]">+ {t("Failed to load image.")}+ </div>+ ) : (+ // eslint-disable-next-line @next/next/no-img-element+ <img+ src={url}+ alt={filename}+ className="max-h-full max-w-full object-contain"+ onLoad={() => setState("ready")}+ onError={() => setState("error")}+ />+ )}+ </div>+ );+}diff --git a/web/components/chat/preview/previewers/MarkdownPreview.tsx b/web/components/chat/preview/previewers/MarkdownPreview.tsxnew file mode 100644index 000000000..178b035e9--- /dev/null+++ b/web/components/chat/preview/previewers/MarkdownPreview.tsx@@ -0,0 +1,38 @@+"use client";++import { Loader2 } from "lucide-react";+import { useTranslation } from "react-i18next";+import MarkdownRenderer from "@/components/common/MarkdownRenderer";+import { useTextSource } from "./useTextSource";++/**+ * Markdown preview that reuses the chat's main MarkdownRenderer (math,+ * tables, code highlight, mermaid all auto-detected).+ */+export default function MarkdownPreview({ url }: { url: string }) {+ const { t } = useTranslation();+ const state = useTextSource(url);++ if (state.kind === "loading") {+ return (+ <div className="flex h-full items-center justify-center gap-2 text-[12px] text-[var(--muted-foreground)]">+ <Loader2 size={14} className="animate-spin" />+ <span>{t("Loading preview…")}</span>+ </div>+ );+ }++ if (state.kind === "error") {+ return (+ <div className="flex h-full items-center justify-center px-6 text-center text-[12px] text-[var(--muted-foreground)]">+ {state.message}+ </div>+ );+ }++ return (+ <div className="px-6 py-5">+ <MarkdownRenderer content={state.text} variant="prose" />+ </div>+ );+}diff --git a/web/components/chat/preview/previewers/OfficeTextPreview.tsx b/web/components/chat/preview/previewers/OfficeTextPreview.tsxnew file mode 100644index 000000000..3b034b67b--- /dev/null+++ b/web/components/chat/preview/previewers/OfficeTextPreview.tsx@@ -0,0 +1,45 @@+"use client";++import { Info } from "lucide-react";+import { useTranslation } from "react-i18next";+import FallbackPreview from "./FallbackPreview";++/**+ * DOCX / XLSX / PPTX preview using the backend-extracted plain text. Browsers+ * cannot natively render OOXML and we choose not to ship mammoth.js / sheetjs+ * to keep the bundle slim. Showing the extracted text doubles as "see what+ * the LLM read", which is itself useful in a study tool.+ */+export default function OfficeTextPreview({+ filename,+ extractedText,+ url,+}: {+ filename: string;+ extractedText: string | undefined;+ url: string | null;+}) {+ const { t } = useTranslation();++ if (!extractedText) {+ return <FallbackPreview filename={filename} url={url} />;+ }++ return (+ <div className="flex h-full flex-col">+ <div className="flex items-start gap-2 border-b border-[var(--border)] bg-[var(--muted)]/40 px-5 py-2.5 text-[11px] text-[var(--muted-foreground)]">+ <Info size={13} strokeWidth={1.6} className="mt-px shrink-0" />+ <p>+ {t(+ "Showing extracted text — the same content the assistant reads. Download the original to see full formatting.",+ )}+ </p>+ </div>+ <div className="flex-1 overflow-y-auto px-6 py-5">+ <pre className="whitespace-pre-wrap break-words font-sans text-[13px] leading-relaxed text-[var(--foreground)]">+ {extractedText}+ </pre>+ </div>+ </div>+ );+}diff --git a/web/components/chat/preview/previewers/PdfPreview.tsx b/web/components/chat/preview/previewers/PdfPreview.tsxnew file mode 100644index 000000000..1eeb1ecdb--- /dev/null+++ b/web/components/chat/preview/previewers/PdfPreview.tsx@@ -0,0 +1,44 @@+"use client";++import { useState } from "react";+import { Loader2 } from "lucide-react";+import { useTranslation } from "react-i18next";+import type { FilePreviewSource } from "../previewerFor";++/**+ * PDF preview powered by the browser's built-in viewer (PDF.js in Chrome /+ * Firefox, Preview in Safari). Loads the original file from /api/attachments+ * via an <iframe> — zero extra bundle weight.+ *+ * The "load" event sometimes fires twice in WebKit because of the inline+ * UA toolbar; we only flip the loading flag on the first one.+ */+export default function PdfPreview({+ url,+ filename,+}: {+ url: string;+ filename: FilePreviewSource["filename"];+}) {+ const { t } = useTranslation();+ const [loading, setLoading] = useState(true);++ return (+ <div className="relative h-full w-full bg-[var(--muted)]/30">+ {loading && (+ <div className="pointer-events-none absolute inset-0 z-10 flex items-center justify-center">+ <div className="flex items-center gap-2 text-[12px] text-[var(--muted-foreground)]">+ <Loader2 size={14} className="animate-spin" />+ <span>{t("Loading preview…")}</span>+ </div>+ </div>+ )}+ <iframe+ title={filename}+ src={url}+ className="h-full w-full border-0 bg-[var(--background)]"+ onLoad={() => setLoading(false)}+ />+ </div>+ );+}diff --git a/web/components/chat/preview/previewers/SvgPreview.tsx b/web/components/chat/preview/previewers/SvgPreview.tsxnew file mode 100644index 000000000..e0dc9ed53--- /dev/null+++ b/web/components/chat/preview/previewers/SvgPreview.tsx@@ -0,0 +1,25 @@+"use client";++/**+ * SVG preview rendered with a native <img> (matches ChatComposer's pending+ * SVG chip). Scripts inside an SVG do not execute under the <img> context,+ * so this is safe even though next/image rejects SVG by default.+ */+export default function SvgPreview({+ url,+ filename,+}: {+ url: string;+ filename: string;+}) {+ return (+ <div className="flex h-full w-full items-center justify-center bg-[var(--muted)]/30 p-6">+ {/* eslint-disable-next-line @next/next/no-img-element */}+ <img+ src={url}+ alt={filename}+ className="max-h-full max-w-full object-contain"+ />+ </div>+ );+}diff --git a/web/components/chat/preview/previewers/TextPreview.tsx b/web/components/chat/preview/previewers/TextPreview.tsxnew file mode 100644index 000000000..77db68437--- /dev/null+++ b/web/components/chat/preview/previewers/TextPreview.tsx@@ -0,0 +1,55 @@+"use client";++import dynamic from "next/dynamic";+import { Loader2 } from "lucide-react";+import { useTranslation } from "react-i18next";+import { langForFilename } from "@/lib/code-languages";+import { useTextSource } from "./useTextSource";++const RichCodeBlock = dynamic(+ () => import("@/components/common/RichCodeBlock"),+ { ssr: false },+);++/**+ * Plain text + code preview. Files with a recognised code extension render+ * inside RichCodeBlock with one-dark syntax highlighting; everything else+ * falls back to a tidy monospace block.+ *+ * Language mapping lives in ``@/lib/code-languages`` — adding a new+ * highlight target is a one-line edit there.+ */+export default function TextPreview({+ url,+ filename,+}: {+ url: string;+ filename: string;+}) {+ const { t } = useTranslation();+ const state = useTextSource(url);+ const lang = langForFilename(filename) ?? "text";++ if (state.kind === "loading") {+ return (+ <div className="flex h-full items-center justify-center gap-2 text-[12px] text-[var(--muted-foreground)]">+ <Loader2 size={14} className="animate-spin" />+ <span>{t("Loading preview…")}</span>+ </div>+ );+ }++ if (state.kind === "error") {+ return (+ <div className="flex h-full items-center justify-center px-6 text-center text-[12px] text-[var(--muted-foreground)]">+ {state.message}+ </div>+ );+ }++ return (+ <div className="px-4 py-4">+ <RichCodeBlock raw={state.text} lang={lang} />+ </div>+ );+}diff --git a/web/components/chat/preview/previewers/useTextSource.ts b/web/components/chat/preview/previewers/useTextSource.tsnew file mode 100644index 000000000..3cb40235a--- /dev/null+++ b/web/components/chat/preview/previewers/useTextSource.ts@@ -0,0 +1,79 @@+"use client";++import { useEffect, useRef, useState } from "react";++const MAX_TEXT_BYTES = 8 * 1024 * 1024; // 8 MB — preview, not a download++export type TextSourceState =+ | { kind: "loading" }+ | { kind: "ready"; text: string }+ | { kind: "error"; message: string };++/**+ * Fetch the text content at *url* (HEAD-checked for size to avoid pulling+ * a 50 MB log into memory). Aborts on unmount.+ *+ * If *fallbackText* is provided and the URL is empty/missing, we render+ * that text instead of fetching. This handles the office-doc case where+ * the backend already extracted plain text.+ */+export function useTextSource(+ url: string | null,+ fallbackText?: string,+): TextSourceState {+ const [state, setState] = useState<TextSourceState>(() =>+ !url && fallbackText !== undefined+ ? { kind: "ready", text: fallbackText }+ : { kind: "loading" },+ );+ const reqIdRef = useRef(0);++ useEffect(() => {+ // Inline fallback (no URL): nothing to fetch.+ if (!url) {+ if (fallbackText !== undefined) {+ setState({ kind: "ready", text: fallbackText });+ } else {+ setState({+ kind: "error",+ message: "Preview source is not available.",+ });+ }+ return;+ }++ const reqId = ++reqIdRef.current;+ const controller = new AbortController();+ setState({ kind: "loading" });++ (async () => {+ try {+ const res = await fetch(url, { signal: controller.signal });+ if (!res.ok) {+ throw new Error(`HTTP ${res.status}`);+ }+ const lengthHeader = res.headers.get("content-length");+ if (lengthHeader && Number(lengthHeader) > MAX_TEXT_BYTES) {+ throw new Error(+ "File is too large to preview as text. Use the Download button.",+ );+ }+ const text = await res.text();+ if (reqIdRef.current !== reqId) return; // superseded+ setState({ kind: "ready", text });+ } catch (err) {+ if (controller.signal.aborted) return;+ if (reqIdRef.current !== reqId) return;+ const message =+ err instanceof Error ? err.message : "Failed to load preview";+ setState({ kind: "error", message });+ }+ })();++ return () => {+ controller.abort();+ };+ }, [url, fallbackText]);++ return state;+}diff --git a/web/components/notebook/SaveToNotebookModal.tsx b/web/components/notebook/SaveToNotebookModal.tsxindex 9beb37ec4..0a6e7e773 100644--- a/web/components/notebook/SaveToNotebookModal.tsx+++ b/web/components/notebook/SaveToNotebookModal.tsx@@ -17,7 +17,13 @@ import {type NotebookSummary as RealNotebookSummary,} from "@/lib/notebook-api";-type RecordType = "solve" | "question" | "research" | "chat" | "co_writer";+type RecordType =+ | "solve"+ | "question"+ | "research"+ | "chat"+ | "co_writer"+ | "tutorbot";export interface NotebookSavePayload {recordType: RecordType;diff --git a/web/context/UnifiedChatContext.tsx b/web/context/UnifiedChatContext.tsxindex f34cb87e4..73cf84098 100644--- a/web/context/UnifiedChatContext.tsx+++ b/web/context/UnifiedChatContext.tsx@@ -74,6 +74,11 @@ export interface MessageAttachment {base64?: string;url?: string;mime_type?: string;+ /** Stable per-attachment id; matches the URL segment served by /api/attachments. */+ id?: string;+ /** Plain-text rendering of office docs, populated by the backend extractor.+ * Used by the preview drawer to show "what the LLM saw" for binary docs. */+ extracted_text?: string;}export interface MessageRequestSnapshot {@@ -563,6 +568,8 @@ export function UnifiedChatProvider({base64: item.base64,url: item.url,mime_type: item.mime_type,+ id: item.id,+ extracted_text: item.extracted_text,})): [],}));diff --git a/web/lib/code-languages.ts b/web/lib/code-languages.tsnew file mode 100644index 000000000..c25c7f101--- /dev/null+++ b/web/lib/code-languages.ts@@ -0,0 +1,178 @@+/**+ * Single source of truth for code-file syntax highlighting.+ *+ * Each entry maps an attachment extension (or special filename) to the+ * Prism language name expected by ``react-syntax-highlighter``. Anything+ * listed here:+ *+ * - is recognised as a "code" preview kind by ``previewerFor`` (so the+ * drawer routes to ``TextPreview`` and renders inside ``RichCodeBlock``);+ * - shows the corresponding language label in the drawer header;+ * - assumes the backend has been taught to accept the extension via+ * ``FileTypeRouter.TEXT_EXTENSIONS`` (deeptutor/services/rag/file_routing.py)+ * and the frontend's ``TEXT_LIKE_EXTS`` (web/lib/doc-attachments.ts).+ *+ * Adding a new language is a one-line edit here. Adding a brand-new file+ * extension also requires the two upload-side lists above so the backend+ * doesn't reject the upload.+ */++/** Extension (lowercase, with leading dot) → Prism language name. */+export const CODE_EXT_TO_LANG: Record<string, string> = {+ // Mainstream+ ".py": "python",+ ".js": "javascript",+ ".mjs": "javascript",+ ".cjs": "javascript",+ ".ts": "typescript",+ ".mts": "typescript",+ ".cts": "typescript",+ ".jsx": "jsx",+ ".tsx": "tsx",+ ".java": "java",+ ".kt": "kotlin",+ ".kts": "kotlin",+ ".scala": "scala",+ ".groovy": "groovy",+ ".gradle": "groovy",++ // Systems+ ".c": "c",+ ".h": "c",+ ".cpp": "cpp",+ ".cc": "cpp",+ ".cxx": "cpp",+ ".hpp": "cpp",+ ".hh": "cpp",+ ".hxx": "cpp",+ ".cs": "csharp",+ ".go": "go",+ ".rs": "rust",+ ".zig": "zig",+ ".nim": "nim",++ // Apple platforms+ ".swift": "swift",+ ".m": "objectivec",+ ".mm": "objectivec",++ // Scripting+ ".rb": "ruby",+ ".php": "php",+ ".pl": "perl",+ ".pm": "perl",+ ".lua": "lua",+ ".r": "r",+ ".jl": "julia",+ ".dart": "dart",++ // Functional+ ".hs": "haskell",+ ".clj": "clojure",+ ".cljs": "clojure",+ ".cljc": "clojure",+ ".ex": "elixir",+ ".exs": "elixir",+ ".erl": "erlang",+ ".ml": "ocaml",+ ".mli": "ocaml",+ ".fs": "fsharp",+ ".fsx": "fsharp",+ ".lisp": "lisp",+ ".lsp": "lisp",+ ".scm": "scheme",+ ".rkt": "racket",++ // Web frameworks+ ".vue": "markup", // single-file component; Prism's vue plugin not always bundled — markup as a safe fallback+ ".svelte": "markup",++ // Web markup / styles+ ".html": "markup",+ ".htm": "markup",+ ".xml": "markup",+ ".css": "css",+ ".scss": "scss",+ ".sass": "sass",+ ".less": "less",+ ".sol": "solidity",++ // Shells+ ".sh": "bash",+ ".bash": "bash",+ ".zsh": "bash",+ ".fish": "bash",+ ".ps1": "powershell",+ ".vim": "vim",++ // Data / config+ ".json": "json",+ ".jsonc": "json",+ ".json5": "json",+ ".yaml": "yaml",+ ".yml": "yaml",+ ".toml": "toml",+ ".ini": "ini",+ ".cfg": "ini",+ ".properties": "ini",++ // Build / infra+ ".sql": "sql",+ ".graphql": "graphql",+ ".gql": "graphql",+ ".proto": "protobuf",+ ".cmake": "cmake",+ ".mk": "makefile",+ ".dockerfile": "docker",+ ".tf": "hcl",+ ".hcl": "hcl",+ ".nginxconf": "nginx",++ // Typesetting+ ".tex": "latex",+ ".latex": "latex",+ ".bib": "latex",+};++/**+ * Special filenames (no extension or shebang-only). Lowercase comparison.+ * Mapped before extension lookup in ``langForFilename``.+ */+const NAMED_FILES: Record<string, string> = {+ dockerfile: "docker",+ makefile: "makefile",+ cmakelists: "cmake",+ "cmakelists.txt": "cmake",+ rakefile: "ruby",+ gemfile: "ruby",+ vagrantfile: "ruby",+ "nginx.conf": "nginx",+ ".bashrc": "bash",+ ".zshrc": "bash",+ ".bash_profile": "bash",+ ".profile": "bash",+};++/** Set of all extensions covered by ``CODE_EXT_TO_LANG``. */+export const CODE_EXTS: ReadonlySet<string> = new Set(+ Object.keys(CODE_EXT_TO_LANG),+);++/**+ * Resolve a Prism language for *filename*.+ *+ * Looks at the bare filename (e.g. ``Dockerfile``) before falling back to+ * the extension. Returns ``null`` when the file is not a recognised code+ * language — callers should render it as plain monospace text.+ */+export function langForFilename(filename: string): string | null {+ if (!filename) return null;+ const lastSlash = filename.lastIndexOf("/");+ const base = (lastSlash >= 0 ? filename.slice(lastSlash + 1) : filename).toLowerCase();+ if (NAMED_FILES[base]) return NAMED_FILES[base];++ const dotIdx = base.lastIndexOf(".");+ if (dotIdx < 0) return null;+ const ext = base.slice(dotIdx);+ return CODE_EXT_TO_LANG[ext] ?? null;+}diff --git a/web/lib/doc-attachments.ts b/web/lib/doc-attachments.tsindex 44612eba9..171c78516 100644--- a/web/lib/doc-attachments.ts+++ b/web/lib/doc-attachments.ts@@ -28,7 +28,9 @@ export const OFFICE_EXTS = [".pdf", ".docx", ".xlsx", ".pptx"] as const;/*** Text-like formats — decoded server-side with multi-encoding fallback.- * Mirrors `FileTypeRouter.TEXT_EXTENSIONS` in the Python codebase.+ * Mirrors `FileTypeRouter.TEXT_EXTENSIONS` in the Python codebase. Adding+ * a new extension here without also adding it to the backend will cause+ * the upload to be silently dropped.*/export const TEXT_LIKE_EXTS = [// Plain text & markup@@ -37,19 +39,39 @@ export const TEXT_LIKE_EXTS = [".html", ".htm", ".xml",".svg", // vector image, treated as XML source; rendered via <img> client-side// Data & config- ".json", ".yaml", ".yml", ".toml", ".csv", ".tsv",+ ".json", ".jsonc", ".json5",+ ".yaml", ".yml", ".toml", ".csv", ".tsv",".ini", ".cfg", ".conf", ".env", ".properties",// Typesetting".tex", ".latex", ".bib",// Stylesheets".css", ".scss", ".sass", ".less",- // Code- ".py", ".js", ".ts", ".jsx", ".tsx",- ".java", ".c", ".cpp", ".h", ".hpp",- ".go", ".rs", ".rb", ".php",- ".swift", ".kt", ".scala",- ".r", ".sql",- ".sh", ".bash", ".zsh", ".ps1",+ // JavaScript / TypeScript family+ ".js", ".mjs", ".cjs", ".ts", ".mts", ".cts", ".jsx", ".tsx",+ // Web frameworks+ ".vue", ".svelte",+ // Python+ ".py",+ // JVM languages+ ".java", ".kt", ".kts", ".scala", ".groovy", ".gradle",+ // Systems+ ".c", ".h", ".cpp", ".cc", ".cxx", ".hpp", ".hh", ".hxx",+ ".cs", ".go", ".rs", ".zig", ".nim",+ // Apple platforms+ ".swift", ".m", ".mm",+ // Scripting+ ".rb", ".php", ".pl", ".pm", ".lua", ".r", ".jl", ".dart",+ // Functional+ ".hs", ".clj", ".cljs", ".cljc", ".ex", ".exs", ".erl",+ ".ml", ".mli", ".fs", ".fsx", ".lisp", ".lsp", ".scm", ".rkt",+ // Smart contracts+ ".sol",+ // Shells / editors+ ".sh", ".bash", ".zsh", ".fish", ".ps1", ".vim",+ // Query / IDL+ ".sql", ".graphql", ".gql", ".proto",+ // Build / infra+ ".cmake", ".mk", ".tf", ".hcl", ".nginxconf", ".dockerfile",] as const;export const SUPPORTED_DOC_EXTS = [@@ -111,7 +133,7 @@ export const ATTACHMENT_ACCEPT = [export type FileKind = "image" | "doc";-function extOf(filename: string): string {+export function extOf(filename: string): string {const idx = filename.lastIndexOf(".");return idx >= 0 ? filename.slice(idx).toLowerCase() : "";}@@ -160,21 +182,39 @@ export interface DocIconSpec {// Extension → icon category. Grouped so we get meaningful visual differentiation// without carrying 50 distinct icons.const CODE_EXTS = new Set([- ".py", ".js", ".ts", ".jsx", ".tsx",- ".java", ".c", ".cpp", ".h", ".hpp",- ".go", ".rs", ".rb", ".php",- ".swift", ".kt", ".scala",- ".r",+ // JS/TS+ ".js", ".mjs", ".cjs", ".ts", ".mts", ".cts", ".jsx", ".tsx",+ ".vue", ".svelte",+ // Python+ ".py",+ // JVM+ ".java", ".kt", ".kts", ".scala", ".groovy", ".gradle",+ // Systems+ ".c", ".h", ".cpp", ".cc", ".cxx", ".hpp", ".hh", ".hxx",+ ".cs", ".go", ".rs", ".zig", ".nim",+ // Apple+ ".swift", ".m", ".mm",+ // Scripting+ ".rb", ".php", ".pl", ".pm", ".lua", ".r", ".jl", ".dart",+ // Functional+ ".hs", ".clj", ".cljs", ".cljc", ".ex", ".exs", ".erl",+ ".ml", ".mli", ".fs", ".fsx", ".lisp", ".lsp", ".scm", ".rkt",+ // Smart contracts+ ".sol",+]);+const SHELL_EXTS = new Set([+ ".sh", ".bash", ".zsh", ".fish", ".ps1", ".vim", ".sql",]);-const SHELL_EXTS = new Set([".sh", ".bash", ".zsh", ".ps1", ".sql"]);const CONFIG_EXTS = new Set([".yaml", ".yml", ".toml", ".ini", ".cfg", ".conf", ".env", ".properties",+ ".tf", ".hcl", ".nginxconf", ".cmake", ".mk", ".dockerfile",]);-const JSON_EXTS = new Set([".json"]);+const JSON_EXTS = new Set([".json", ".jsonc", ".json5"]);const MARKUP_EXTS = new Set([".md", ".markdown", ".rst", ".asciidoc",".html", ".htm", ".xml",".tex", ".latex", ".bib",+ ".graphql", ".gql", ".proto",]);const DATA_EXTS = new Set([".csv", ".tsv"]);const STYLE_EXTS = new Set([".css", ".scss", ".sass", ".less"]);diff --git a/web/lib/notebook-api.ts b/web/lib/notebook-api.tsindex a8b2f4150..160c80db1 100644--- a/web/lib/notebook-api.ts+++ b/web/lib/notebook-api.ts@@ -12,7 +12,8 @@ export type NotebookRecordType =| "question"| "research"| "chat"- | "co_writer";+ | "co_writer"+ | "tutorbot";export interface NotebookSummary {id: string;diff --git a/web/lib/session-api.ts b/web/lib/session-api.tsindex 9acb63d05..68623bf12 100644--- a/web/lib/session-api.ts+++ b/web/lib/session-api.ts@@ -15,6 +15,8 @@ export interface SessionMessage {base64?: string;url?: string;mime_type?: string;+ id?: string;+ extracted_text?: string;}>;created_at: number;}diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex a4e84e925..68ab2b208 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -339,6 +339,7 @@"session": "session","sessions": "sessions","Chat": "Chat",+ "Tutorbot": "Tutorbot","No history found": "No history found","Your activities will appear here": "Your activities will appear here","Continue": "Continue",@@ -1102,5 +1103,12 @@"lists": "lists","Embedding config changed": "Embedding config changed","Embedding config aligned": "Embedding config aligned",- "Default embedding": "Default embedding"+ "Default embedding": "Default embedding",+ "Remove attachment": "Remove attachment",+ "Loading preview…": "Loading preview…",+ "File preview: {{name}}": "File preview: {{name}}",+ "Copy link": "Copy link",+ "Original file is not stored (sent before preview was supported).": "Original file is not stored (sent before preview was supported).",+ "Preview is not available for this file type.": "Preview is not available for this file type.",+ "Showing extracted text — the same content the assistant reads. Download the original to see full formatting.": "Showing extracted text — the same content the assistant reads. Download the original to see full formatting."}diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex 696044847..6575404c1 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -339,6 +339,7 @@"session": "个会话","sessions": "个会话","Chat": "聊天",+ "Tutorbot": "辅导机器人","No history found": "未找到历史记录","Your activities will appear here": "您的活动将显示在这里","Continue": "继续",@@ -1102,5 +1103,12 @@"lists": "列表","Embedding config changed": "嵌入配置已变化","Embedding config aligned": "嵌入配置已对齐",- "Default embedding": "默认嵌入配置"+ "Default embedding": "默认嵌入配置",+ "Remove attachment": "移除附件",+ "Loading preview…": "正在加载预览…",+ "File preview: {{name}}": "文件预览:{{name}}",+ "Copy link": "复制链接",+ "Original file is not stored (sent before preview was supported).": "原始文件未保存(消息发送于预览功能上线之前)。",+ "Preview is not available for this file type.": "暂不支持预览此类文件。",+ "Showing extracted text — the same content the assistant reads. Download the original to see full formatting.": "以下是提取出的纯文本,也是助手实际读取的内容。如需查看完整排版,请下载原文件。"}