Skip to content

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

chore: prepare v1.2.4 release

Bingxi Zhao (Frank)c89a3df8a567
diff --git a/README.md b/README.md
index 021fdff5b..00ae57e38 100644
--- a/README.md
+++ b/README.md
@@ -28,6 +28,8 @@
### 📦 Releases
+> **[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.
> **[2026.4.22]** [v1.2.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.2) — User-authored Skills system (CRUD + chat integration), chat input performance overhaul with state colocation, `response_format` auto-fallback for incompatible providers, LAN remote access fix, sidebar version badge, Deep Solve image attachments, TutorBot WebSocket auto-start, Book Library UI, and visualization fullscreen mode.
@@ -140,6 +142,8 @@ python scripts/start_web.py
> **Daily launch** — The tour is only needed once. From now on, just run `python scripts/start_web.py` to boot both the backend and frontend in a single command (the frontend URL is printed in the terminal). Re-run `start_tour.py` only if you want to reconfigure providers, change ports, or install missing extras. Inside the web **Settings** page you can also click **Run Tour** to replay the highlight-based UI walkthrough.
+> **Updating a local install** — If you installed with Option A or Option B from a git clone, run `python scripts/update.py`. The updater fetches the remote for your current branch, shows the local-vs-remote commit gap, asks you to confirm the detected branch mapping, then performs a safe fast-forward pull.
+
### Option B — Manual Local Install
If you prefer full control, install and configure everything yourself.
diff --git a/assets/releases/ver1-2-4.md b/assets/releases/ver1-2-4.md
new file mode 100644
index 000000000..4908d0ad4
--- /dev/null
+++ b/assets/releases/ver1-2-4.md
@@ -0,0 +1,62 @@
+# DeepTutor v1.2.4 Release Notes
+
+**Release Date:** 2026.04.25
+
+## Highlights
+
+### Support More Attachment Formats in Chat
+The v1.2.3 document-attachment pipeline has been expanded beyond Office files. Chat attachments now accept the same text-like formats as the Knowledge Base ingestion router: Markdown, plain text, logs, JSON/YAML/TOML, CSV/TSV, LaTeX/BibTeX, HTML/XML/SVG, stylesheets, scripts, and common source-code files (`.py`, `.js`, `.ts`, `.tsx`, `.java`, `.cpp`, `.go`, `.rs`, `.sql`, `.sh`, and more).
+
+- **Backend parity with KB routing** — `deeptutor/utils/document_extractor.py` imports `FileTypeRouter.TEXT_EXTENSIONS`, so chat attachments and KB uploads share one source of truth for text/code formats. `FileTypeRouter.decode_bytes()` centralizes the UTF-8 / UTF-8-BOM / GBK / GB18030 / Latin-1 / CP1252 fallback chain.
+- **SVG as readable source** — `.svg` was added to the RAG text extension set and is treated as a document attachment instead of a vision image, letting the LLM inspect the XML source while the frontend still renders a safe thumbnail preview.
+- **Typed attachment UX** — `web/lib/doc-attachments.ts` now exposes `OFFICE_EXTS`, `TEXT_LIKE_EXTS`, SVG detection, richer MIME/extension fallback, and category-specific icons for code, shell, JSON, config, data, markup, stylesheets, plain text, Office docs, and SVG.
+- **Composer copy updated** — the drag-and-drop hint now advertises "Images, Office docs, code & text" instead of the older Office-only list.
+
+### One-Command Setup Tour
+`scripts/start_tour.py` has evolved from a pure configuration wizard into a 7-step fresh-install path that can detect the local environment, install dependencies, and then guide provider configuration.
+
+- **Dependency installation step** — the tour checks Python, `uv`, Node.js, and npm; installs backend requirements, installs DeepTutor in editable mode, and runs frontend `npm install` with live terminal output.
+- **`uv pip` compatibility (#376)** — Python dependency installation now prefers `uv pip` when available, and binds `--python <current-interpreter>` so packages land in the interpreter running the tour instead of an unrelated `.venv` / `$VIRTUAL_ENV`.
+- **Windows npm detection (#381)** — npm invocations use `npm.cmd` on Windows, fixing version checks and install commands on systems where npm is exposed as a command shim rather than an executable.
+- **Provider registry-driven LLM choices** — the wizard now reads from the full `PROVIDERS` registry, groups providers by mode, highlights common services, and includes newer options such as `custom_anthropic`, OpenRouter, SiliconFlow, Volcengine / BytePlus coding providers, GitHub Copilot, OpenAI Codex, llama.cpp, OVMS, MiniMax, Mistral, Qianfan, Step Fun, and Xiaomi MiMo.
+- **Search and config hints** — Serper is available in the search-provider list; Azure/API-version and proxy prompts now show inline guidance in both English and Chinese.
+- **Long-list terminal UX** — `scripts/_cli_kit.py` renders long select menus inside a scrolling window with "more above/below" indicators, preventing stale terminal rows when the provider list exceeds the screen height.
+
+### Chat Markdown Export
+The chat page now has a **Download Markdown** action next to "Save to Notebook" and "New Chat". `web/lib/chat-export.ts` serializes the current conversation as Markdown with a title, ISO export timestamp, role headings, capability labels, and attachment metadata, then downloads it with a sanitized date-stamped filename. This gives users a lightweight local export path for sharing, archiving, or moving a conversation into external notes.
+
+### Knowledge Base Management UI Polish
+The Knowledge page was tightened up for denser day-to-day management:
+
+- Creation and upload drop zones are now simpler dashed cards with concise inline upload-policy summaries.
+- KB cards moved from four large stat panels to compact rows showing document count, index readiness, last-updated time, provider, embedding model, live progress, and storage path.
+- Default/delete actions were simplified visually, reducing card height and making large KB lists easier to scan.
+
+### Documentation and Localization Refresh
+The README family was updated to match the new install story and provider surface:
+
+- **Polish README** — `assets/README/README_PL.md` adds a complete Polish translation of the project README (#379).
+- **Setup docs** — the main README and multilingual READMEs now describe the guided tour as the recommended fresh-clone path: create a Python environment, run `python scripts/start_tour.py`, then use `python scripts/start_web.py` for daily launch.
+- **Provider docs** — provider tables were refreshed for the v1.2.3 provider registry, including `custom_anthropic`, MiniMax's canonical endpoints, coding-plan providers, local providers, and clarified authentication notes for OpenAI Codex / GitHub Copilot.
+- **Release/news sections** — multilingual READMEs now include v1.2.2 and v1.2.3 summaries, a contributing-guide callout, and the 20k-star community milestone.
+
+### UI and Theme Fixes
+- **Theme-aware popovers** — composer capability/tool/reference/skill menus now use `--popover` plus backdrop blur instead of `--card`, improving contrast in the Glass theme and dark popover contexts.
+- **Native color-scheme hints** — light, dark, Snow, and Glass theme roots declare the correct `color-scheme`, improving native controls and browser-rendered surfaces.
+- **Smooth-scroll hydration** — global smooth scrolling is now gated behind `html[data-scroll-behavior="smooth"]`, with the attribute set by the root layout to avoid applying it unintentionally.
+- **Sidebar logo sizing** — sidebar logo images now pin explicit rendered width/height classes to prevent small layout shifts.
+
+### Cleanup
+Removed the stale `nanobot` submodule pointer and the deprecated `scripts/extract_numbered_items.sh` stub from the repository. The v1.2.x codebase now relies on the in-tree document extraction and RAG routing paths instead of that legacy helper.
+
+### Test Suite Expansion
+- **Backend document extraction** — `tests/utils/test_document_extractor.py` now covers plain text, Python source, JSON, CSV, Markdown, UTF-8-BOM input, GBK fallback decoding, and SVG source extraction.
+- **Frontend attachment classification** — `web/tests/doc-attachments.test.ts` now covers text/code acceptance, SVG-as-document routing, case-insensitive SVG filename detection, and the new icon categories for code, JSON, config, shell, data, markup, stylesheets, and SVG.
+
+## Community Contributions
+
+- **@kKamUL** — Add the Polish README translation (#379)
+- **@rogercsi / @zouchengfu** — Prefer `uv pip` for setup-tour dependency installation (#376)
+- **@jonathanzhan1975** — Use `npm.cmd` for Windows npm detection in the setup tour (#381)
+
+**Full Changelog**: https://github.com/HKUDS/DeepTutor/compare/v1.2.3...v1.2.4
diff --git a/deeptutor/services/rag/file_routing.py b/deeptutor/services/rag/file_routing.py
index 8cca4cb5e..3cd68af68 100644
--- a/deeptutor/services/rag/file_routing.py
+++ b/deeptutor/services/rag/file_routing.py
@@ -90,6 +90,7 @@ class FileTypeRouter:
".html",
".htm",
".xml",
+ ".svg",
".css",
".scss",
".sass",
@@ -165,12 +166,34 @@ class FileTypeRouter:
unsupported=unsupported,
)
+ TEXT_DECODING_CANDIDATES = (
+ "utf-8",
+ "utf-8-sig",
+ "gbk",
+ "gb2312",
+ "gb18030",
+ "latin-1",
+ "cp1252",
+ )
+
+ @classmethod
+ def decode_bytes(cls, data: bytes) -> str:
+ """Decode raw bytes using the same fallback chain as read_text_file.
+
+ Used by the chat-attachment extractor so path-based and bytes-based
+ callers share one source of truth for supported encodings.
+ """
+ for encoding in cls.TEXT_DECODING_CANDIDATES:
+ try:
+ return data.decode(encoding)
+ except UnicodeDecodeError:
+ continue
+ return data.decode("utf-8", errors="replace")
+
@classmethod
async def read_text_file(cls, file_path: str) -> str:
"""Read a text file with automatic encoding detection."""
- encodings = ["utf-8", "utf-8-sig", "gbk", "gb2312", "gb18030", "latin-1", "cp1252"]
-
- for encoding in encodings:
+ for encoding in cls.TEXT_DECODING_CANDIDATES:
try:
with open(file_path, "r", encoding=encoding) as f:
return f.read()
diff --git a/deeptutor/utils/document_extractor.py b/deeptutor/utils/document_extractor.py
index 3138e7963..2e80ebc90 100644
--- a/deeptutor/utils/document_extractor.py
+++ b/deeptutor/utils/document_extractor.py
@@ -1,8 +1,15 @@
"""Document text extraction for chat attachments.
Bytes-in, text-out. Used by the chat turn runtime to inline the text of
-user-dropped Office documents (.pdf / .docx / .xlsx / .pptx) into the
-``effective_user_message`` sent to the LLM.
+user-dropped files into the ``effective_user_message`` sent to the LLM.
+
+Two format families:
+ * **Binary Office** (.pdf / .docx / .xlsx / .pptx) — parsed with pymupdf /
+ python-docx / openpyxl / python-pptx.
+ * **Text-like** (plain text, Markdown, source code, JSON, XML, CSV, …) —
+ the extension set is imported from ``FileTypeRouter.TEXT_EXTENSIONS`` so
+ the chat composer accepts every format the knowledge-base pipeline
+ already ingests. Decoded with the same multi-encoding fallback chain.
Design mirrors ``nanobot/nanobot/utils/document.py`` but works on bytes
instead of file paths so the server never touches disk.
@@ -16,6 +23,8 @@ import io
import logging
from pathlib import PurePosixPath
+from deeptutor.services.rag.file_routing import FileTypeRouter
+
try:
import fitz # pymupdf
except ImportError: # pragma: no cover
@@ -47,7 +56,11 @@ except ImportError: # pragma: no cover
logger = logging.getLogger(__name__)
-SUPPORTED_DOC_EXTENSIONS: frozenset[str] = frozenset({".pdf", ".docx", ".xlsx", ".pptx"})
+_OFFICE_EXTENSIONS: frozenset[str] = frozenset({".pdf", ".docx", ".xlsx", ".pptx"})
+# Text-like formats are sourced from the KB file router so chat and KB stay
+# in sync. Adding a new code / config extension in one place propagates here.
+TEXT_LIKE_EXTENSIONS: frozenset[str] = frozenset(FileTypeRouter.TEXT_EXTENSIONS)
+SUPPORTED_DOC_EXTENSIONS: frozenset[str] = _OFFICE_EXTENSIONS | TEXT_LIKE_EXTENSIONS
MAX_DOC_BYTES = 10 * 1024 * 1024
MAX_TOTAL_DOC_BYTES = 25 * 1024 * 1024
@@ -97,7 +110,12 @@ def _truncate(text: str, max_length: int) -> str:
def _check_magic(ext: str, data: bytes, filename: str) -> None:
- """Validate file header to catch extension spoofing."""
+ """Validate file header to catch extension spoofing.
+
+ Only binary formats have well-known magic prefixes. Text-like extensions
+ (code, markup, config, …) are decoded directly; a mislabeled binary blob
+ either decodes as garbage or fails at decode time, which is fine.
+ """
if ext == ".pdf":
if not data.startswith(_PDF_MAGIC):
raise CorruptDocumentError(
@@ -141,6 +159,8 @@ def extract_text_from_bytes(filename: str, data: bytes) -> str:
text = _extract_xlsx(data, filename)
elif ext == ".pptx":
text = _extract_pptx(data, filename)
+ elif ext in TEXT_LIKE_EXTENSIONS:
+ text = _extract_text_like(data, filename)
else: # pragma: no cover - guarded above
raise UnsupportedDocumentError(f"{filename}: unreachable", filename=filename)
@@ -250,6 +270,21 @@ def _extract_pptx(data: bytes, filename: str) -> str:
return "\n\n".join(slides)
+def _extract_text_like(data: bytes, filename: str) -> str:
+ """Decode a plain-text / code / config / markup file.
+
+ Uses the same encoding fallback chain as the KB pipeline
+ (``FileTypeRouter.decode_bytes``) so a GBK-encoded Python file or a
+ UTF-8-BOM Markdown works the same way in both places.
+ """
+ try:
+ return FileTypeRouter.decode_bytes(data)
+ except Exception as exc: # pragma: no cover - decode_bytes never raises
+ raise CorruptDocumentError(
+ f"{filename}: failed to decode text ({exc})", filename=filename
+ ) from exc
+
+
def _collect_pptx_shape_text(shape, out: list[str]) -> None:
"""Recurse into groups + tables, same semantics as nanobot's version."""
sub_shapes = getattr(shape, "shapes", None)
diff --git a/scripts/start_tour.py b/scripts/start_tour.py
index d41c711d1..75f326668 100644
--- a/scripts/start_tour.py
+++ b/scripts/start_tour.py
@@ -42,19 +42,24 @@ def _resolve_python() -> str:
_PYTHON: str = _resolve_python()
-def _resolve_pip_cmd() -> list[str]:
- """Return the best available pip invocation for the current environment.
+def _resolve_pip_cmd() -> tuple[list[str], list[str]]:
+ """Return ``(prefix, python_args)`` for the best pip invocation.
Prefer ``uv pip`` when uv is on PATH (uv-managed venvs may have pip
- disabled). Fall back to ``python -m pip`` otherwise.
+ disabled). When using uv, also bind ``--python _PYTHON`` so packages land
+ in the same interpreter that's running this script — without it ``uv pip``
+ falls back to its own venv discovery (``$VIRTUAL_ENV`` / ``./.venv``) and
+ may install into a different environment.
+
+ Falls back to ``python -m pip`` (with no extra args) when uv is absent.
"""
uv = shutil.which("uv")
if uv:
- return [uv, "pip"]
- return [_PYTHON, "-m", "pip"]
+ return [uv, "pip"], ["--python", _PYTHON]
+ return [_PYTHON, "-m", "pip"], []
-_PIP_CMD: list[str] = _resolve_pip_cmd()
+_PIP_CMD, _PIP_PYTHON_ARGS = _resolve_pip_cmd()
_BOOTSTRAP_PACKAGES = [
("yaml", "PyYAML>=6.0"),
@@ -76,7 +81,7 @@ def _bootstrap() -> None:
return
print(f" Installing bootstrap dependencies: {', '.join(missing)} ...")
subprocess.check_call(
- [*_PIP_CMD, "install", *missing, "-q"],
+ [*_PIP_CMD, "install", *missing, *_PIP_PYTHON_ARGS, "-q"],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
@@ -440,12 +445,17 @@ def _install_commands(
cmds: list[tuple[list[str], Path]] = []
for req in PROFILE_COMMANDS[profile]:
- cmds.append(([*_PIP_CMD, "install", "-r", req], PROJECT_ROOT))
+ cmds.append(([*_PIP_CMD, "install", "-r", req, *_PIP_PYTHON_ARGS], PROJECT_ROOT))
if include_math_animator:
cmds.append(
- ([*_PIP_CMD, "install", "-r", MATH_ANIMATOR_REQUIREMENTS], PROJECT_ROOT)
+ (
+ [*_PIP_CMD, "install", "-r", MATH_ANIMATOR_REQUIREMENTS, *_PIP_PYTHON_ARGS],
+ PROJECT_ROOT,
+ )
)
- cmds.append(([*_PIP_CMD, "install", "-e", ".", "--no-deps"], PROJECT_ROOT))
+ cmds.append(
+ ([*_PIP_CMD, "install", "-e", ".", "--no-deps", *_PIP_PYTHON_ARGS], PROJECT_ROOT)
+ )
if profile.startswith("web"):
cmds.append(([_get_npm_command(), "install"], PROJECT_ROOT / "web"))
return cmds
@@ -743,7 +753,12 @@ def _get_version(cmd: list[str]) -> str | None:
def _resolve_uv() -> str:
- """Return path to uv, installing it via pip if necessary."""
+ """Return path to uv, installing it via pip if necessary.
+
+ NOTE: kept on ``python -m pip`` intentionally — if ``shutil.which("uv")``
+ returned None we cannot bootstrap uv with itself, and a pip-less venv
+ would have already failed in ``_bootstrap()`` above.
+ """
found = shutil.which("uv")
if found:
return found
diff --git a/scripts/update.py b/scripts/update.py
new file mode 100644
index 000000000..3760c07cc
--- /dev/null
+++ b/scripts/update.py
@@ -0,0 +1,435 @@
+#!/usr/bin/env python
+"""Safely update a local DeepTutor git checkout.
+
+The updater is intentionally conservative:
+1. Fetch the remote for the current branch.
+2. Show the local-vs-remote gap and ask for confirmation.
+3. Fast-forward pull only when the branch can be updated safely.
+"""
+
+from __future__ import annotations
+
+import argparse
+from dataclasses import dataclass
+from pathlib import Path
+import subprocess
+import sys
+from typing import Sequence
+
+PROJECT_ROOT = Path(__file__).resolve().parent.parent
+
+
+class UpdateError(Exception):
+ """Raised for user-actionable update failures."""
+
+
+@dataclass(frozen=True)
+class GitResult:
+ args: tuple[str, ...]
+ returncode: int
+ stdout: str
+ stderr: str
+
+
+@dataclass(frozen=True)
+class BranchTarget:
+ local_branch: str
+ remote: str
+ remote_branch: str
+ remote_ref: str
+ upstream: str | None
+ source: str
+
+ @property
+ def display_remote_ref(self) -> str:
+ return f"{self.remote}/{self.remote_branch}"
+
+
+@dataclass(frozen=True)
+class BranchGap:
+ local_sha: str
+ local_subject: str
+ remote_sha: str
+ remote_subject: str
+ ahead: int
+ behind: int
+ incoming_commits: list[str]
+ outgoing_commits: list[str]
+ diff_stat: str
+ dirty_entries: list[str]
+
+ @property
+ def is_up_to_date(self) -> bool:
+ return self.ahead == 0 and self.behind == 0
+
+ @property
+ def is_fast_forwardable(self) -> bool:
+ return self.ahead == 0 and self.behind > 0
+
+ @property
+ def is_diverged(self) -> bool:
+ return self.ahead > 0 and self.behind > 0
+
+
+class Git:
+ def __init__(self, repo_root: Path) -> None:
+ self.repo_root = repo_root
+
+ def run(
+ self,
+ args: Sequence[str],
+ *,
+ check: bool = True,
+ timeout: int | None = 60,
+ ) -> GitResult:
+ cmd = ["git", *args]
+ completed = subprocess.run(
+ cmd,
+ cwd=self.repo_root,
+ capture_output=True,
+ encoding="utf-8",
+ errors="replace",
+ text=True,
+ timeout=timeout,
+ )
+ result = GitResult(
+ args=tuple(args),
+ returncode=completed.returncode,
+ stdout=completed.stdout.strip(),
+ stderr=completed.stderr.strip(),
+ )
+ if check and result.returncode != 0:
+ message = result.stderr or result.stdout or f"git {' '.join(args)} failed"
+ raise UpdateError(message)
+ return result
+
+
+def _print_section(title: str) -> None:
+ print()
+ print(f"== {title} ==")
+
+
+def _print_list(title: str, items: list[str], *, empty: str) -> None:
+ print(f"{title}:")
+ if not items:
+ print(f" {empty}")
+ return
+ for item in items:
+ print(f" {item}")
+
+
+def ensure_git_checkout(git: Git) -> None:
+ inside = git.run(["rev-parse", "--is-inside-work-tree"]).stdout
+ if inside != "true":
+ raise UpdateError("This directory is not inside a git checkout.")
+
+
+def current_branch(git: Git) -> str:
+ branch = git.run(["branch", "--show-current"]).stdout
+ if not branch:
+ raise UpdateError(
+ "Detached HEAD detected. Please switch to a branch before running the updater."
+ )
+ return branch
+
+
+def git_config(git: Git, key: str) -> str | None:
+ result = git.run(["config", "--get", key], check=False)
+ if result.returncode != 0:
+ return None
+ return result.stdout or None
+
+
+def available_remotes(git: Git) -> list[str]:
+ remotes = git.run(["remote"], check=False).stdout.splitlines()
+ return [remote.strip() for remote in remotes if remote.strip()]
+
+
+def normalize_merge_ref(merge_ref: str | None, fallback_branch: str) -> str:
+ if not merge_ref:
+ return fallback_branch
+ prefix = "refs/heads/"
+ if merge_ref.startswith(prefix):
+ return merge_ref[len(prefix) :]
+ return merge_ref
+
+
+def resolve_branch_target(git: Git, branch: str) -> BranchTarget:
+ remote = git_config(git, f"branch.{branch}.remote")
+ merge_ref = git_config(git, f"branch.{branch}.merge")
+
+ if remote and remote != ".":
+ remote_branch = normalize_merge_ref(merge_ref, branch)
+ return BranchTarget(
+ local_branch=branch,
+ remote=remote,
+ remote_branch=remote_branch,
+ remote_ref=f"refs/remotes/{remote}/{remote_branch}",
+ upstream=f"{remote}/{remote_branch}",
+ source="configured upstream",
+ )
+
+ remotes = available_remotes(git)
+ if not remotes:
+ raise UpdateError("No git remote is configured for this checkout.")
+
+ selected_remote = "origin" if "origin" in remotes else remotes[0]
+ return BranchTarget(
+ local_branch=branch,
+ remote=selected_remote,
+ remote_branch=branch,
+ remote_ref=f"refs/remotes/{selected_remote}/{branch}",
+ upstream=None,
+ source=f"default remote '{selected_remote}' with matching branch name",
+ )
+
+
+def fetch_remote(git: Git, target: BranchTarget) -> None:
+ print(f"Fetching latest refs from {target.remote} ...")
+ git.run(["fetch", "--prune", target.remote], timeout=None)
+
+
+def verify_remote_branch(git: Git, target: BranchTarget) -> None:
+ result = git.run(
+ ["rev-parse", "--verify", "--quiet", f"{target.remote_ref}^{{commit}}"],
+ check=False,
+ )
+ if result.returncode == 0:
+ return
+ raise UpdateError(
+ "Remote branch not found after fetch: "
+ f"{target.display_remote_ref}. Set the branch upstream or push it first."
+ )
+
+
+def short_commit(git: Git, ref: str) -> tuple[str, str]:
+ sha = git.run(["rev-parse", "--short", ref]).stdout
+ subject = git.run(["log", "-1", "--format=%s", ref]).stdout
+ return sha, subject
+
+
+def log_lines(git: Git, revision_range: str, limit: int = 8) -> list[str]:
+ result = git.run(
+ ["log", "--oneline", "--decorate", f"--max-count={limit}", revision_range],
+ check=False,
+ )
+ if result.returncode != 0 or not result.stdout:
+ return []
+ return result.stdout.splitlines()
+
+
+def tracked_dirty_entries(git: Git) -> list[str]:
+ git.run(["update-index", "-q", "--refresh"], check=False)
+ result = git.run(["status", "--porcelain=v1", "--untracked-files=no"], check=False)
+ if result.returncode != 0 or not result.stdout:
+ return []
+ return result.stdout.splitlines()
+
+
+def analyze_gap(git: Git, target: BranchTarget) -> BranchGap:
+ local_sha, local_subject = short_commit(git, "HEAD")
+ remote_sha, remote_subject = short_commit(git, target.remote_ref)
+
+ counts = git.run(["rev-list", "--left-right", "--count", f"HEAD...{target.remote_ref}"])
+ ahead_str, behind_str = counts.stdout.split()
+ ahead = int(ahead_str)
+ behind = int(behind_str)
+
+ diff_stat = ""
+ if behind:
+ diff_stat = git.run(["diff", "--stat", "--compact-summary", f"HEAD..{target.remote_ref}"]).stdout
+
+ return BranchGap(
+ local_sha=local_sha,
+ local_subject=local_subject,
+ remote_sha=remote_sha,
+ remote_subject=remote_subject,
+ ahead=ahead,
+ behind=behind,
+ incoming_commits=log_lines(git, f"HEAD..{target.remote_ref}"),
+ outgoing_commits=log_lines(git, f"{target.remote_ref}..HEAD"),
+ diff_stat=diff_stat,
+ dirty_entries=tracked_dirty_entries(git),
+ )
+
+
+def print_gap(target: BranchTarget, gap: BranchGap) -> None:
+ _print_section("Detected branch")
+ print(f"Local branch: {target.local_branch}")
+ print(f"Remote branch: {target.display_remote_ref}")
+ print(f"Selection: {target.source}")
+ if target.upstream:
+ print(f"Upstream: {target.upstream}")
+ else:
+ print("Upstream: not configured")
+
+ _print_section("Local vs remote")
+ print(f"Local HEAD: {gap.local_sha} {gap.local_subject}")
+ print(f"Remote HEAD: {gap.remote_sha} {gap.remote_subject}")
+ print(f"Gap: local is {gap.ahead} commit(s) ahead, {gap.behind} commit(s) behind")
+
+ _print_list(
+ "Incoming commits from remote",
+ gap.incoming_commits,
+ empty="none",
+ )
+ _print_list(
+ "Local commits not on remote",
+ gap.outgoing_commits,
+ empty="none",
+ )
+
+ if gap.diff_stat:
+ print("Incoming file summary:")
+ for line in gap.diff_stat.splitlines():
+ print(f" {line}")
+
+ if gap.dirty_entries:
+ _print_list(
+ "Tracked local changes",
+ gap.dirty_entries,
+ empty="none",
+ )
+
+
+def confirm_update(assume_yes: bool, target: BranchTarget, gap: BranchGap) -> bool:
+ if assume_yes:
+ return True
+
+ if not sys.stdin.isatty():
+ print()
+ print("Confirmation required, but stdin is not interactive. Re-run with --yes to update.")
+ return False
+
+ print()
+ answer = input(
+ "Confirm this branch mapping and update "
+ f"{target.local_branch} from {target.display_remote_ref}? [y/N] "
+ ).strip()
+ return answer.lower() in {"y", "yes"}
+
+
+def ensure_safe_to_update(gap: BranchGap) -> None:
+ if gap.dirty_entries:
+ raise UpdateError(
+ "Tracked local changes are present. Commit or stash them before updating."
+ )
+ if gap.is_diverged:
+ raise UpdateError(
+ "Local and remote branches have diverged. Resolve manually, then rerun the updater."
+ )
+ if gap.ahead > 0 and gap.behind == 0:
+ raise UpdateError(
+ "Local branch has commits not present on the remote, and there are no remote "
+ "commits to pull."
+ )
+ if not gap.is_fast_forwardable:
+ raise UpdateError("This branch cannot be updated with a safe fast-forward pull.")
+
+
+def dependency_hints(changed_files: list[str]) -> list[str]:
+ hints: list[str] = []
+ if any(
+ path == "pyproject.toml" or path.startswith("requirements/")
+ for path in changed_files
+ ):
+ hints.append('Backend dependencies changed: consider running python -m pip install -e ".[server]"')
+ if any(
+ path in {"web/package.json", "web/package-lock.json", "web/pnpm-lock.yaml"}
+ or path == "web/yarn.lock"
+ for path in changed_files
+ ):
+ hints.append("Frontend dependencies changed: consider running cd web && npm install")
+ return hints
+
+
+def pull_updates(git: Git, target: BranchTarget) -> list[str]:
+ old_sha = git.run(["rev-parse", "HEAD"]).stdout
+ _print_section("Updating")
+ git.run(["pull", "--ff-only", target.remote, target.remote_branch], timeout=None)
+ new_sha = git.run(["rev-parse", "HEAD"]).stdout
+ if old_sha == new_sha:
+ return []
+ changed = git.run(["diff", "--name-only", f"{old_sha}..{new_sha}"]).stdout
+ return [line for line in changed.splitlines() if line.strip()]
+
+
+def run_update(repo_root: Path, *, assume_yes: bool) -> int:
+ git = Git(repo_root)
+ ensure_git_checkout(git)
+ branch = current_branch(git)
+ target = resolve_branch_target(git, branch)
+ fetch_remote(git, target)
+ verify_remote_branch(git, target)
+ gap = analyze_gap(git, target)
+ print_gap(target, gap)
+
+ if gap.dirty_entries:
+ raise UpdateError(
+ "Tracked local changes are present. Commit or stash them before updating."
+ )
+ if gap.is_diverged:
+ raise UpdateError(
+ "Local and remote branches have diverged. Resolve manually, then rerun the updater."
+ )
+ if gap.is_up_to_date:
+ print()
+ print("Already up to date. No update is needed.")
+ return 0
+ if gap.ahead > 0 and gap.behind == 0:
+ print()
+ print("No remote commits to pull. Local branch is ahead of the remote.")
+ return 0
+
+ if not confirm_update(assume_yes, target, gap):
+ print("Update cancelled.")
+ return 0
+
+ ensure_safe_to_update(gap)
+ changed_files = pull_updates(git, target)
+
+ print()
+ print(f"Updated {target.local_branch} from {target.display_remote_ref}.")
+ if changed_files:
+ print(f"Changed files: {len(changed_files)}")
+ for hint in dependency_hints(changed_files):
+ print(f"Next step: {hint}")
+ print("Restart DeepTutor if it is currently running.")
+ return 0
+
+
+def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
+ parser = argparse.ArgumentParser(
+ description="Fetch, review, and fast-forward update a local DeepTutor checkout."
+ )
+ parser.add_argument(
+ "--yes",
+ "-y",
+ action="store_true",
+ help="Skip the interactive confirmation after printing the branch comparison.",
+ )
+ parser.add_argument(
+ "--repo",
+ type=Path,
+ default=PROJECT_ROOT,
+ help="Path to the git checkout to update. Defaults to this DeepTutor repository.",
+ )
+ return parser.parse_args(argv)
+
+
+def main(argv: Sequence[str] | None = None) -> int:
+ args = parse_args(argv)
+ try:
+ return run_update(args.repo.resolve(), assume_yes=args.yes)
+ except KeyboardInterrupt:
+ print()
+ print("Update cancelled.")
+ return 130
+ except (OSError, subprocess.SubprocessError, UpdateError) as exc:
+ print()
+ print(f"Update failed: {exc}", file=sys.stderr)
+ return 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tests/scripts/test_update.py b/tests/scripts/test_update.py
new file mode 100644
index 000000000..306955de2
--- /dev/null
+++ b/tests/scripts/test_update.py
@@ -0,0 +1,124 @@
+from __future__ import annotations
+
+import importlib.util
+from pathlib import Path
+import subprocess
+import sys
+
+
+def _load_update_module():
+ module_path = Path(__file__).resolve().parents[2] / "scripts" / "update.py"
+ module_name = "update_script_under_test"
+ sys.modules.pop(module_name, None)
+ spec = importlib.util.spec_from_file_location(module_name, module_path)
+ assert spec and spec.loader
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[module_name] = module
+ spec.loader.exec_module(module)
+ return module
+
+
+def _run(args: list[str], cwd: Path) -> subprocess.CompletedProcess[str]:
+ return subprocess.run(
+ args,
+ cwd=cwd,
+ check=True,
+ capture_output=True,
+ encoding="utf-8",
+ errors="replace",
+ text=True,
+ )
+
+
+def _git(cwd: Path, *args: str) -> str:
+ return _run(["git", *args], cwd).stdout.strip()
+
+
+def _write(path: Path, text: str) -> None:
+ path.write_text(text, encoding="utf-8")
+
+
+def _commit(repo: Path, message: str) -> None:
+ _git(repo, "add", ".")
+ _git(repo, "commit", "-m", message)
+
+
+def _configure_user(repo: Path) -> None:
+ _git(repo, "config", "user.email", "[email protected]")
+ _git(repo, "config", "user.name", "DeepTutor Tests")
+
+
+def _create_checkout(tmp_path: Path, branch: str = "main") -> tuple[Path, Path]:
+ remote = tmp_path / "remote.git"
+ seed = tmp_path / "seed"
+ checkout = tmp_path / "checkout"
+
+ _run(["git", "init", "--bare", str(remote)], tmp_path)
+ _run(["git", "init", "-b", branch, str(seed)], tmp_path)
+ _configure_user(seed)
+ _write(seed / "app.txt", "v1\n")
+ _commit(seed, "initial")
+ _git(seed, "remote", "add", "origin", str(remote))
+ _git(seed, "push", "-u", "origin", branch)
+
+ _run(["git", "clone", "--branch", branch, str(remote), str(checkout)], tmp_path)
+ _configure_user(checkout)
+ return seed, checkout
+
+
+def _push_remote_commit(seed: Path, branch: str, text: str = "v2\n") -> None:
+ _write(seed / "app.txt", text)
+ _commit(seed, "remote update")
+ _git(seed, "push", "origin", branch)
+
+
+def test_update_fast_forwards_the_current_non_main_branch(tmp_path: Path) -> None:
+ update = _load_update_module()
+ seed, checkout = _create_checkout(tmp_path, branch="dev")
+ _push_remote_commit(seed, "dev")
+
+ exit_code = update.main(["--repo", str(checkout), "--yes"])
+
+ assert exit_code == 0
+ assert _git(checkout, "branch", "--show-current") == "dev"
+ assert (checkout / "app.txt").read_text(encoding="utf-8") == "v2\n"
+ assert _git(checkout, "rev-parse", "HEAD") == _git(checkout, "rev-parse", "origin/dev")
+
+
+def test_update_refuses_tracked_local_changes(tmp_path: Path) -> None:
+ update = _load_update_module()
+ seed, checkout = _create_checkout(tmp_path)
+ _push_remote_commit(seed, "main")
+ _write(checkout / "app.txt", "local edit\n")
+
+ exit_code = update.main(["--repo", str(checkout), "--yes"])
+
+ assert exit_code == 1
+ assert (checkout / "app.txt").read_text(encoding="utf-8") == "local edit\n"
+ assert _git(checkout, "rev-parse", "HEAD") != _git(checkout, "rev-parse", "origin/main")
+
+
+def test_update_refuses_diverged_branches(tmp_path: Path) -> None:
+ update = _load_update_module()
+ seed, checkout = _create_checkout(tmp_path)
+ _push_remote_commit(seed, "main")
+ _write(checkout / "app.txt", "local commit\n")
+ _commit(checkout, "local update")
+
+ exit_code = update.main(["--repo", str(checkout), "--yes"])
+
+ assert exit_code == 1
+ assert (checkout / "app.txt").read_text(encoding="utf-8") == "local commit\n"
+ assert _git(checkout, "rev-parse", "HEAD") != _git(checkout, "rev-parse", "origin/main")
+
+
+def test_dependency_hints_cover_backend_and_frontend_manifests() -> None:
+ update = _load_update_module()
+
+ hints = update.dependency_hints(
+ ["pyproject.toml", "requirements/server.txt", "web/package-lock.json"]
+ )
+
+ assert len(hints) == 2
+ assert "Backend dependencies changed" in hints[0]
+ assert "Frontend dependencies changed" in hints[1]
diff --git a/tests/utils/test_document_extractor.py b/tests/utils/test_document_extractor.py
index 8f4e5d923..9973d0a33 100644
--- a/tests/utils/test_document_extractor.py
+++ b/tests/utils/test_document_extractor.py
@@ -71,15 +71,26 @@ def _make_pptx(slides_text: list[list[str]]) -> bytes:
class TestIsDocumentExtension:
- def test_supported(self) -> None:
+ def test_office(self) -> None:
assert is_document_extension("foo.pdf")
assert is_document_extension("foo.DOCX")
assert is_document_extension("report.xlsx")
assert is_document_extension("deck.pptx")
+ def test_text_and_code(self) -> None:
+ # Any extension in FileTypeRouter.TEXT_EXTENSIONS should be supported.
+ assert is_document_extension("notes.txt")
+ assert is_document_extension("readme.md")
+ assert is_document_extension("module.py")
+ assert is_document_extension("config.yaml")
+ assert is_document_extension("data.json")
+ assert is_document_extension("index.html")
+ assert is_document_extension("table.csv")
+
def test_unsupported(self) -> None:
assert not is_document_extension("foo.png")
- assert not is_document_extension("foo.txt")
+ assert not is_document_extension("foo.zip")
+ assert not is_document_extension("foo.exe")
assert not is_document_extension("foo")
assert not is_document_extension("")
@@ -122,6 +133,56 @@ class TestExtractPptx:
assert "Slide 2 only text" in text
+class TestExtractTextLike:
+ def test_plain_txt(self) -> None:
+ text = extract_text_from_bytes("note.txt", "hello world\nline two".encode("utf-8"))
+ assert "hello world" in text
+ assert "line two" in text
+
+ def test_python_source(self) -> None:
+ src = b"def greet(name: str) -> str:\n return f'hi {name}'\n"
+ text = extract_text_from_bytes("greet.py", src)
+ assert "def greet" in text
+
+ def test_json(self) -> None:
+ text = extract_text_from_bytes("data.json", b'{"x": 42, "y": "ok"}')
+ assert '"x": 42' in text
+
+ def test_csv(self) -> None:
+ text = extract_text_from_bytes("table.csv", b"a,b,c\n1,2,3\n")
+ assert "a,b,c" in text
+ assert "1,2,3" in text
+
+ def test_markdown(self) -> None:
+ text = extract_text_from_bytes("doc.md", b"# Heading\n\nBody.\n")
+ assert "# Heading" in text
+
+ def test_utf8_with_bom(self) -> None:
+ # The candidate chain has utf-8 before utf-8-sig (same order as KB
+ # pipeline), so BOM-prefixed bytes decode as utf-8 and the BOM is
+ # retained. Mirror that behavior here.
+ text = extract_text_from_bytes("note.txt", b"\xef\xbb\xbfhello")
+ assert "hello" in text
+
+ def test_gbk_fallback(self) -> None:
+ # "你好" in GBK
+ text = extract_text_from_bytes("note.txt", "你好".encode("gbk"))
+ assert text == "你好"
+
+ def test_svg(self) -> None:
+ svg = (
+ b'<?xml version="1.0"?>'
+ b'<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">'
+ b'<circle cx="50" cy="50" r="40" fill="red"/>'
+ b'<text x="50" y="55">Hello</text>'
+ b'</svg>'
+ )
+ text = extract_text_from_bytes("logo.svg", svg)
+ assert "<svg" in text
+ assert "<circle" in text
+ assert "Hello" in text
+
+
class TestExtractPdf:
def test_minimal_pdf(self) -> None:
# Build a minimal valid PDF via pymupdf (dependency already in project).
diff --git a/web/app/(utility)/knowledge/page.tsx b/web/app/(utility)/knowledge/page.tsx
index 6ff9b49b2..205283185 100644
--- a/web/app/(utility)/knowledge/page.tsx
+++ b/web/app/(utility)/knowledge/page.tsx
@@ -36,7 +36,6 @@ import {
Pencil,
Plus,
Search,
- Sparkles,
Star,
Trash2,
Upload,
@@ -384,15 +383,6 @@ function KnowledgePageContent() {
[uploadFiles, validateFileSelection],
);
- const visibleSupportedFormats = useMemo(
- () => uploadPolicy.extensions.slice(0, 8),
- [uploadPolicy.extensions],
- );
- const hiddenSupportedFormatCount = Math.max(
- 0,
- uploadPolicy.extensions.length - visibleSupportedFormats.length,
- );
-
const removeNewKbFile = (fileId: string) => {
setNewKbFiles((prev) =>
prev.filter((file) => selectionFileId(file) !== fileId),
@@ -1595,44 +1585,6 @@ function KnowledgePageContent() {
))}
</select>
- <div className="rounded-2xl border border-[var(--border)] bg-[var(--background)]/70 p-4">
- <div className="mb-3 flex items-start justify-between gap-3">
- <div>
- <div className="flex items-center gap-2 text-[12px] font-medium text-[var(--foreground)]">
- <Sparkles className="h-3.5 w-3.5 text-[var(--muted-foreground)]" />
- {t("Supported formats")}
- </div>
- <p className="mt-1 text-[11px] leading-relaxed text-[var(--muted-foreground)]">
- {t("Maximum file size: {{size}}", {
- size: formatFileSize(uploadPolicy.max_file_size_bytes),
- })}{" "}
- ·{" "}
- {t("PDF limit: {{size}}", {
- size: formatFileSize(uploadPolicy.max_pdf_size_bytes),
- })}
- </p>
- </div>
- <div className="rounded-full bg-[var(--muted)] px-2 py-1 text-[10px] text-[var(--muted-foreground)]">
- {uploadPolicy.extensions.length} {t("types")}
- </div>
- </div>
- <div className="flex flex-wrap gap-1.5">
- {visibleSupportedFormats.map((extension) => (
- <span
- key={`create-ext-${extension}`}
- className="rounded-full border border-[var(--border)] bg-[var(--card)] px-2 py-1 text-[10px] font-medium uppercase tracking-[0.12em] text-[var(--muted-foreground)]"
- >
- {extension.replace(".", "")}
- </span>
- ))}
- {hiddenSupportedFormatCount > 0 && (
- <span className="rounded-full border border-[var(--border)] bg-[var(--muted)] px-2 py-1 text-[10px] font-medium text-[var(--muted-foreground)]">
- +{hiddenSupportedFormatCount}
- </span>
- )}
- </div>
- </div>
-
<button
type="button"
onClick={() => createFileRef.current?.click()}
@@ -1640,18 +1592,15 @@ function KnowledgePageContent() {
onDragLeave={(event) => handleDropZoneLeave("create", event)}
onDragOver={(event) => handleDropZoneOver("create", event)}
onDrop={(event) => handleDropZoneDrop("create", event)}
- className={`group relative flex w-full flex-col items-center justify-center gap-2 overflow-hidden rounded-2xl border border-dashed px-5 py-6 text-center transition-all ${
+ className={`group flex w-full flex-col items-center justify-center gap-2 rounded-lg border border-dashed px-5 py-7 text-center transition-colors ${
createDropZone.active
? createDropZone.invalid
- ? "border-amber-400 bg-amber-50/90 shadow-[0_0_0_4px_rgba(245,158,11,0.08)] dark:border-amber-700 dark:bg-amber-950/20"
- : "border-sky-400 bg-sky-50/90 shadow-[0_0_0_4px_rgba(56,189,248,0.08)] dark:border-sky-700 dark:bg-sky-950/20"
- : "border-[var(--border)] bg-[linear-gradient(180deg,var(--background),var(--muted)_180%)] hover:border-[var(--foreground)]/25 hover:bg-[var(--muted)]/30"
+ ? "border-amber-400 bg-amber-50/60 dark:border-amber-700 dark:bg-amber-950/20"
+ : "border-sky-400 bg-sky-50/60 dark:border-sky-700 dark:bg-sky-950/20"
+ : "border-[var(--border)] bg-[var(--background)] hover:border-[var(--foreground)]/25 hover:bg-[var(--muted)]/40"
}`}
>
- <div className="pointer-events-none absolute inset-0 bg-[radial-gradient(circle_at_top,rgba(255,255,255,0.32),transparent_60%)] opacity-60" />
- <div className="rounded-2xl bg-[var(--muted)] p-3 text-[var(--muted-foreground)] transition-colors group-hover:text-[var(--foreground)]">
- <Files className="h-5 w-5" />
- </div>
+ <Files className="h-5 w-5 text-[var(--muted-foreground)] transition-colors group-hover:text-[var(--foreground)]" />
<div className="space-y-1">
<div className="text-[13px] font-medium text-[var(--foreground)]">
{createDropZone.active
@@ -1681,6 +1630,16 @@ function KnowledgePageContent() {
</p>
</div>
</button>
+ <p className="text-[11px] text-[var(--muted-foreground)]">
+ {uploadPolicy.extensions.length} {t("types")} ·{" "}
+ {t("Maximum file size: {{size}}", {
+ size: formatFileSize(uploadPolicy.max_file_size_bytes),
+ })}{" "}
+ ·{" "}
+ {t("PDF limit: {{size}}", {
+ size: formatFileSize(uploadPolicy.max_pdf_size_bytes),
+ })}
+ </p>
<input
ref={createFileRef}
type="file"
@@ -1801,44 +1760,6 @@ function KnowledgePageContent() {
</div>
)}
- <div className="rounded-2xl border border-[var(--border)] bg-[var(--background)]/70 p-4">
- <div className="mb-3 flex items-start justify-between gap-3">
- <div>
- <div className="flex items-center gap-2 text-[12px] font-medium text-[var(--foreground)]">
- <Sparkles className="h-3.5 w-3.5 text-[var(--muted-foreground)]" />
- {t("Supported formats")}
- </div>
- <p className="mt-1 text-[11px] leading-relaxed text-[var(--muted-foreground)]">
- {t("Maximum file size: {{size}}", {
- size: formatFileSize(uploadPolicy.max_file_size_bytes),
- })}{" "}
- ·{" "}
- {t("PDF limit: {{size}}", {
- size: formatFileSize(uploadPolicy.max_pdf_size_bytes),
- })}
- </p>
- </div>
- <div className="rounded-full bg-[var(--muted)] px-2 py-1 text-[10px] text-[var(--muted-foreground)]">
- {uploadPolicy.extensions.length} {t("types")}
- </div>
- </div>
- <div className="flex flex-wrap gap-1.5">
- {visibleSupportedFormats.map((extension) => (
- <span
- key={`upload-ext-${extension}`}
- className="rounded-full border border-[var(--border)] bg-[var(--card)] px-2 py-1 text-[10px] font-medium uppercase tracking-[0.12em] text-[var(--muted-foreground)]"
- >
- {extension.replace(".", "")}
- </span>
- ))}
- {hiddenSupportedFormatCount > 0 && (
- <span className="rounded-full border border-[var(--border)] bg-[var(--muted)] px-2 py-1 text-[10px] font-medium text-[var(--muted-foreground)]">
- +{hiddenSupportedFormatCount}
- </span>
- )}
- </div>
- </div>
-
<button
type="button"
onClick={() => uploadFileRef.current?.click()}
@@ -1846,18 +1767,15 @@ function KnowledgePageContent() {
onDragLeave={(event) => handleDropZoneLeave("upload", event)}
onDragOver={(event) => handleDropZoneOver("upload", event)}
onDrop={(event) => handleDropZoneDrop("upload", event)}
- className={`group relative flex w-full flex-col items-center justify-center gap-2 overflow-hidden rounded-2xl border border-dashed px-5 py-6 text-center transition-all ${
+ className={`group flex w-full flex-col items-center justify-center gap-2 rounded-lg border border-dashed px-5 py-7 text-center transition-colors ${
uploadDropZone.active
? uploadDropZone.invalid
- ? "border-amber-400 bg-amber-50/90 shadow-[0_0_0_4px_rgba(245,158,11,0.08)] dark:border-amber-700 dark:bg-amber-950/20"
- : "border-sky-400 bg-sky-50/90 shadow-[0_0_0_4px_rgba(56,189,248,0.08)] dark:border-sky-700 dark:bg-sky-950/20"
- : "border-[var(--border)] bg-[linear-gradient(180deg,var(--background),var(--muted)_180%)] hover:border-[var(--foreground)]/25 hover:bg-[var(--muted)]/30"
+ ? "border-amber-400 bg-amber-50/60 dark:border-amber-700 dark:bg-amber-950/20"
+ : "border-sky-400 bg-sky-50/60 dark:border-sky-700 dark:bg-sky-950/20"
+ : "border-[var(--border)] bg-[var(--background)] hover:border-[var(--foreground)]/25 hover:bg-[var(--muted)]/40"
}`}
>
- <div className="pointer-events-none absolute inset-0 bg-[radial-gradient(circle_at_top,rgba(255,255,255,0.32),transparent_60%)] opacity-60" />
- <div className="rounded-2xl bg-[var(--muted)] p-3 text-[var(--muted-foreground)] transition-colors group-hover:text-[var(--foreground)]">
- <Files className="h-5 w-5" />
- </div>
+ <Files className="h-5 w-5 text-[var(--muted-foreground)] transition-colors group-hover:text-[var(--foreground)]" />
<div className="space-y-1">
<div className="text-[13px] font-medium text-[var(--foreground)]">
{uploadDropZone.active
@@ -1887,6 +1805,16 @@ function KnowledgePageContent() {
</p>
</div>
</button>
+ <p className="text-[11px] text-[var(--muted-foreground)]">
+ {uploadPolicy.extensions.length} {t("types")} ·{" "}
+ {t("Maximum file size: {{size}}", {
+ size: formatFileSize(uploadPolicy.max_file_size_bytes),
+ })}{" "}
+ ·{" "}
+ {t("PDF limit: {{size}}", {
+ size: formatFileSize(uploadPolicy.max_pdf_size_bytes),
+ })}
+ </p>
<input
ref={uploadFileRef}
type="file"
@@ -1974,12 +1902,6 @@ function KnowledgePageContent() {
const isLive = kbHasLiveProgress(kb);
const percent = resolveProgressPercent(progress);
const documentsCount = kb.statistics?.raw_documents ?? 0;
- const imagesCount = kb.statistics?.images ?? 0;
- const contentListsCount = kb.statistics?.content_lists ?? 0;
- const assetCount = imagesCount + contentListsCount;
- const createdLabel =
- formatKnowledgeTimestamp(kbMetadata.created_at) ||
- t("Unknown time");
const updatedLabel =
formatKnowledgeTimestamp(kbMetadata.last_updated) ||
t("Unknown time");
@@ -2012,21 +1934,17 @@ function KnowledgePageContent() {
return (
<div
key={kb.name}
- className="group rounded-2xl border border-[var(--border)] bg-[linear-gradient(180deg,var(--card),var(--background)_180%)] p-4 transition-colors hover:border-[var(--foreground)]/10"
+ className="group rounded-xl border border-[var(--border)] bg-[var(--card)] p-4 transition-colors hover:border-[var(--foreground)]/15"
>
<div className="flex flex-wrap items-start justify-between gap-3">
- <div className="flex min-w-0 flex-1 items-start gap-4">
- <div className="relative hidden h-14 w-14 shrink-0 overflow-hidden rounded-2xl border border-[var(--border)] bg-[linear-gradient(180deg,var(--card),var(--muted)_160%)] sm:block">
- <div className="absolute -right-3 -top-3 h-10 w-10 rounded-full bg-[var(--primary)]/12 blur-xl" />
- <div className="absolute inset-0 bg-[radial-gradient(circle_at_top,rgba(255,255,255,0.26),transparent_58%)]" />
- <div className="relative flex h-full items-center justify-center text-[var(--foreground)]">
- <Layers className="h-5 w-5 opacity-80" />
- </div>
+ <div className="flex min-w-0 flex-1 items-center gap-3">
+ <div className="hidden h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-[var(--muted)]/60 text-[var(--muted-foreground)] sm:flex">
+ <Layers className="h-4 w-4" />
</div>
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-2">
- <h3 className="text-[15px] font-semibold text-[var(--foreground)]">
+ <h3 className="text-[14px] font-semibold text-[var(--foreground)]">
{kb.name}
</h3>
{kb.is_default && (
@@ -2055,18 +1973,15 @@ function KnowledgePageContent() {
{statusLabel}
</span>
</div>
- <div className="mt-2 flex flex-wrap gap-2 text-[11px] text-[var(--muted-foreground)]">
- <span className="rounded-full border border-[var(--border)] px-2.5 py-1">
- {t("Provider")}:{" "}
- {kb.statistics?.rag_provider || "llamaindex"}
- </span>
- <span className="rounded-full border border-[var(--border)] px-2.5 py-1">
- {t("Embedding")}: {embeddingLabel}
- </span>
+ <div className="mt-1 truncate text-[11px] text-[var(--muted-foreground)]">
+ {kb.statistics?.rag_provider || "llamaindex"}
+ {" · "}
+ {embeddingLabel}
{!!progress?.current && !!progress?.total && isLive && (
- <span className="rounded-full border border-[var(--border)] px-2.5 py-1">
+ <>
+ {" · "}
{t("Progress")}: {progress.current}/{progress.total}
- </span>
+ </>
)}
</div>
</div>
@@ -2076,76 +1991,43 @@ function KnowledgePageContent() {
{!kb.is_default && (
<button
onClick={() => setDefaultKnowledgeBase(kb.name)}
- className="rounded-md border border-[var(--border)] px-2.5 py-1 text-[12px] text-[var(--foreground)] transition-colors hover:bg-[var(--muted)]"
+ className="rounded-md px-2.5 py-1 text-[12px] text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
>
{t("Set default")}
</button>
)}
<button
onClick={() => deleteKnowledgeBase(kb.name)}
- className="rounded-md border border-[var(--border)] p-1.5 text-[var(--muted-foreground)] transition-colors hover:border-red-200 hover:bg-red-50 hover:text-red-600 dark:hover:border-red-900 dark:hover:bg-red-950/30 dark:hover:text-red-400"
+ className="rounded-md p-1.5 text-[var(--muted-foreground)] transition-colors hover:bg-red-50 hover:text-red-600 dark:hover:bg-red-950/30 dark:hover:text-red-400"
>
<Trash2 size={13} />
</button>
</div>
</div>
- <div className="mt-4 grid gap-2 sm:grid-cols-2 xl:grid-cols-4">
- <div className="rounded-2xl border border-[var(--border)] bg-[var(--background)]/65 p-3">
- <div className="text-[10px] font-medium uppercase tracking-[0.14em] text-[var(--muted-foreground)]">
- {t("Documents")}
- </div>
- <div className="mt-2 text-[20px] font-semibold text-[var(--foreground)]">
+ <div className="mt-3 flex flex-wrap items-center gap-x-4 gap-y-1 text-[12px] text-[var(--muted-foreground)]">
+ <span>
+ <span className="font-medium text-[var(--foreground)]">
{documentsCount}
- </div>
- <div className="mt-1 text-[11px] text-[var(--muted-foreground)]">
- {assetCount > 0
- ? t("{{count}} derived assets", { count: assetCount })
- : t("No derived assets yet")}
- </div>
- </div>
-
- <div className="rounded-2xl border border-[var(--border)] bg-[var(--background)]/65 p-3">
- <div className="text-[10px] font-medium uppercase tracking-[0.14em] text-[var(--muted-foreground)]">
- {t("Updated")}
- </div>
- <div className="mt-2 text-[13px] font-medium leading-relaxed text-[var(--foreground)]">
- {updatedLabel}
- </div>
- <div className="mt-1 text-[11px] text-[var(--muted-foreground)]">
- {t("Created")}: {createdLabel}
- </div>
- </div>
-
- <div className="rounded-2xl border border-[var(--border)] bg-[var(--background)]/65 p-3">
- <div className="text-[10px] font-medium uppercase tracking-[0.14em] text-[var(--muted-foreground)]">
- {t("Index")}
- </div>
- <div className="mt-2 text-[13px] font-medium text-[var(--foreground)]">
- {kb.statistics?.rag_initialized
- ? t("Vector index ready")
- : t("Index not ready")}
- </div>
- <div className="mt-1 break-all text-[11px] text-[var(--muted-foreground)]">
- {kb.path || t("No storage path")}
- </div>
- </div>
-
- <div className="rounded-2xl border border-[var(--border)] bg-[var(--background)]/65 p-3">
- <div className="text-[10px] font-medium uppercase tracking-[0.14em] text-[var(--muted-foreground)]">
- {t("Assets")}
- </div>
- <div className="mt-2 text-[13px] font-medium text-[var(--foreground)]">
- {imagesCount} {t("images")} · {contentListsCount}{" "}
- {t("lists")}
- </div>
- <div className="mt-1 text-[11px] text-[var(--muted-foreground)]">
- {kbMetadata.embedding_mismatch
- ? t("Embedding config changed")
- : t("Embedding config aligned")}
- </div>
- </div>
+ </span>{" "}
+ {documentsCount === 1 ? t("document") : t("documents")}
+ </span>
+ <span className="h-3 w-px bg-[var(--border)]" aria-hidden />
+ <span>
+ {kb.statistics?.rag_initialized
+ ? t("Vector index ready")
+ : t("Index not ready")}
+ </span>
+ <span className="h-3 w-px bg-[var(--border)]" aria-hidden />
+ <span>
+ {t("Updated")} {updatedLabel}
+ </span>
</div>
+ {kb.path && (
+ <div className="mt-1 truncate font-mono text-[10.5px] text-[var(--muted-foreground)]/80">
+ {kb.path}
+ </div>
+ )}
{(isLive || isError || needsReindex) && activityMessage && (
<div
diff --git a/web/app/(workspace)/chat/[[...sessionId]]/page.tsx b/web/app/(workspace)/chat/[[...sessionId]]/page.tsx
index e51d6b664..9977414f8 100644
--- a/web/app/(workspace)/chat/[[...sessionId]]/page.tsx
+++ b/web/app/(workspace)/chat/[[...sessionId]]/page.tsx
@@ -36,6 +36,7 @@ import {
} from "@/lib/file-attachments";
import {
classifyFile,
+ isSvgFilename,
MAX_ATTACHMENT_BYTES,
MAX_TOTAL_ATTACHMENT_BYTES,
} from "@/lib/doc-attachments";
@@ -71,6 +72,7 @@ import {
} from "@/lib/research-types";
import { listKnowledgeBases } from "@/lib/knowledge-api";
import { listSkills, type SkillInfo } from "@/lib/skills-api";
+import { downloadChatMarkdown } from "@/lib/chat-export";
const NotebookRecordPicker = dynamic(
() => import("@/components/notebook/NotebookRecordPicker"),
@@ -654,13 +656,17 @@ export default function ChatPage() {
new Promise((resolve, reject) => {
readFileAsDataUrl(f)
.then((raw) => {
- const isImage = f.type.startsWith("image/");
+ // SVG: treat as file (text extraction on server, vision models
+ // reject SVG) but keep the data URL so the chip can render a
+ // thumbnail via a raw <img> tag.
+ const svg = isSvgFilename(f.name) || f.type === "image/svg+xml";
+ const isImage = !svg && f.type.startsWith("image/");
const b64 = extractBase64FromDataUrl(raw);
resolve({
type: isImage ? "image" : "file",
filename: f.name,
base64: b64,
- previewUrl: isImage ? raw : undefined,
+ previewUrl: isImage || svg ? raw : undefined,
size: f.size,
mimeType: f.type || undefined,
});
@@ -998,6 +1004,16 @@ export default function ChatPage() {
router.push("/chat");
}, [router]);
+ const handleDownloadMarkdown = useCallback(() => {
+ if (!state.messages.length) return;
+ const title =
+ state.messages
+ .find((msg) => msg.role === "user")
+ ?.content.trim()
+ .slice(0, 80) || "Chat Session";
+ downloadChatMarkdown(state.messages, { title });
+ }, [state.messages]);
+
return (
<div className="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">
@@ -1012,6 +1028,14 @@ export default function ChatPage() {
>
{t("Save to Notebook")}
</button>
+ <button
+ onClick={handleDownloadMarkdown}
+ disabled={!state.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>
<button
onClick={handleNewChat}
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)]"
diff --git a/web/app/api/version/route.ts b/web/app/api/version/route.ts
index 0dd333eb5..abcbb2085 100644
--- a/web/app/api/version/route.ts
+++ b/web/app/api/version/route.ts
@@ -1,14 +1,27 @@
import { NextResponse } from "next/server";
+import { execFileSync } from "node:child_process";
+import {
+ parseBuild,
+ unknownBuild,
+ type ParsedBuild,
+ type VersionSource,
+} from "@/lib/version";
/**
- * Returns the latest GitHub release for the project, used by the sidebar
- * version badge. The response is cached on the server side (ISR) so that
- * each visit doesn't hit GitHub directly — at most one upstream request
- * per `revalidate` window across all clients.
+ * Returns both:
+ * - current: the version of the code that is actually running
+ * - latest: the latest GitHub release for update awareness
+ *
+ * The route itself stays dynamic so current git metadata is not frozen into
+ * the client bundle. The GitHub release lookup is cached separately below.
*/
-// Refresh at most once per hour. Tune via env if needed.
-export const revalidate = 3600;
+export const dynamic = "force-dynamic";
+export const runtime = "nodejs";
+
+// Refresh the remote release lookup at most once per hour. Tune via env if needed.
+const LATEST_REVALIDATE_SECONDS = 3600;
+const LATEST_FALLBACK_CACHE_SECONDS = 300;
const DEFAULT_REPO = "HKUDS/DeepTutor";
@@ -21,7 +34,7 @@ interface GithubRelease {
draft: boolean;
}
-interface VersionPayload {
+interface LatestVersionPayload {
tag: string | null;
name: string | null;
url: string | null;
@@ -29,7 +42,17 @@ interface VersionPayload {
source: "github" | "fallback";
}
-const FALLBACK: VersionPayload = {
+interface CurrentVersionPayload extends ParsedBuild {
+ source: VersionSource;
+ detectedAt: string;
+}
+
+interface VersionPayload extends LatestVersionPayload {
+ current: CurrentVersionPayload;
+ latest: LatestVersionPayload;
+}
+
+const FALLBACK_LATEST: LatestVersionPayload = {
tag: null,
name: null,
url: `https://github.com/${DEFAULT_REPO}/releases`,
@@ -37,8 +60,68 @@ const FALLBACK: VersionPayload = {
source: "fallback",
};
-export async function GET() {
- const repo = process.env.NEXT_PUBLIC_GITHUB_REPO || DEFAULT_REPO;
+let latestCache:
+ | {
+ repo: string;
+ expiresAt: number;
+ payload: LatestVersionPayload;
+ }
+ | null = null;
+
+function readGitDescribe(): string | null {
+ try {
+ return execFileSync("git", ["describe", "--tags", "--always", "--dirty=-dev"], {
+ cwd: process.cwd(),
+ encoding: "utf8",
+ stdio: ["ignore", "pipe", "ignore"],
+ timeout: 2000,
+ }).trim();
+ } catch {
+ return null;
+ }
+}
+
+function detectCurrentVersion(): CurrentVersionPayload {
+ const detectedAt = new Date().toISOString();
+ const gitRaw = readGitDescribe();
+ const envRaw = process.env.APP_VERSION || process.env.NEXT_PUBLIC_APP_VERSION || "";
+ const raw = gitRaw || envRaw;
+ const parsed = parseBuild(raw) ?? unknownBuild(raw);
+
+ return {
+ ...parsed,
+ source: gitRaw ? "git" : envRaw ? "env" : "unknown",
+ detectedAt,
+ };
+}
+
+function rememberLatest(
+ repo: string,
+ payload: LatestVersionPayload,
+ ttlSeconds: number,
+): LatestVersionPayload {
+ latestCache = {
+ repo,
+ expiresAt: Date.now() + ttlSeconds * 1000,
+ payload,
+ };
+ return payload;
+}
+
+async function fetchLatestRelease(
+ repo: string,
+ forceRefresh: boolean,
+): Promise<LatestVersionPayload> {
+ const now = Date.now();
+ if (
+ !forceRefresh &&
+ latestCache &&
+ latestCache.repo === repo &&
+ latestCache.expiresAt > now
+ ) {
+ return latestCache.payload;
+ }
+
const url = `https://api.github.com/repos/${repo}/releases/latest`;
const headers: Record<string, string> = {
@@ -53,33 +136,54 @@ export async function GET() {
try {
const res = await fetch(url, {
headers,
- next: { revalidate },
+ cache: "no-store",
+ signal: AbortSignal.timeout(2500),
});
if (!res.ok) {
- return NextResponse.json(
- { ...FALLBACK, url: `https://github.com/${repo}/releases` },
- { status: 200 },
+ return rememberLatest(
+ repo,
+ { ...FALLBACK_LATEST, url: `https://github.com/${repo}/releases` },
+ LATEST_FALLBACK_CACHE_SECONDS,
);
}
const data = (await res.json()) as GithubRelease;
- const payload: VersionPayload = {
+ const payload: LatestVersionPayload = {
tag: data.tag_name ?? null,
name: data.name ?? null,
url: data.html_url ?? `https://github.com/${repo}/releases`,
publishedAt: data.published_at ?? null,
source: "github",
};
- return NextResponse.json(payload, {
- status: 200,
- headers: {
- // Browser-side cache hint; server-side caching already handled by ISR.
- "Cache-Control": "public, s-maxage=3600, stale-while-revalidate=86400",
- },
- });
+ return rememberLatest(repo, payload, LATEST_REVALIDATE_SECONDS);
} catch {
- return NextResponse.json(
- { ...FALLBACK, url: `https://github.com/${repo}/releases` },
- { status: 200 },
+ return rememberLatest(
+ repo,
+ { ...FALLBACK_LATEST, url: `https://github.com/${repo}/releases` },
+ LATEST_FALLBACK_CACHE_SECONDS,
);
}
}
+
+export async function GET(request: Request) {
+ const repo = process.env.NEXT_PUBLIC_GITHUB_REPO || DEFAULT_REPO;
+ const { searchParams } = new URL(request.url);
+ const forceRefresh = searchParams.get("refresh") === "1";
+
+ const current = detectCurrentVersion();
+ const latest = await fetchLatestRelease(repo, forceRefresh);
+
+ return NextResponse.json(
+ {
+ ...latest,
+ current,
+ latest,
+ } satisfies VersionPayload,
+ {
+ status: 200,
+ headers: {
+ // The running version is dynamic; callers should not reuse stale payloads.
+ "Cache-Control": "no-store",
+ },
+ },
+ );
+}
diff --git a/web/app/globals.css b/web/app/globals.css
index 305e5afcf..3dda8928b 100644
--- a/web/app/globals.css
+++ b/web/app/globals.css
@@ -4,6 +4,7 @@
@layer base {
:root {
+ color-scheme: light;
--background: #faf9f6;
--foreground: #1f1d1b;
--card: #ffffff;
@@ -26,6 +27,7 @@
}
.dark {
+ color-scheme: dark;
--background: #1a1918;
--foreground: #e8e4de;
--card: #242220;
@@ -48,6 +50,7 @@
}
.theme-snow {
+ color-scheme: light;
--background: #f8fafc;
--foreground: #0f172a;
--card: #ffffff;
@@ -70,11 +73,12 @@
}
.theme-glass {
+ color-scheme: dark;
--background: #111111;
--foreground: #ffffff;
--card: rgba(255, 255, 255, 0.05);
--card-foreground: #ffffff;
- --popover: rgba(255, 255, 255, 0.1);
+ --popover: rgba(24, 22, 36, 0.92);
--popover-foreground: #ffffff;
--primary: #9d50bb;
--primary-foreground: #ffffff;
diff --git a/web/components/chat/home/ChatComposer.tsx b/web/components/chat/home/ChatComposer.tsx
index e2ec66830..cca51141d 100644
--- a/web/components/chat/home/ChatComposer.tsx
+++ b/web/components/chat/home/ChatComposer.tsx
@@ -30,6 +30,7 @@ import {
ATTACHMENT_ACCEPT,
docIconFor,
formatBytes,
+ isSvgFilename,
} from "@/lib/doc-attachments";
import { useTranslation } from "react-i18next";
import type { SelectedHistorySession } from "@/components/chat/HistorySessionPicker";
@@ -333,7 +334,7 @@ export default memo(function ChatComposer({
className="absolute bottom-full left-0 right-0 z-50 mb-1"
>
<div className="mx-auto">
- <div className="w-[280px] rounded-xl border border-[var(--border)] bg-[var(--card)] py-1.5 shadow-lg">
+ <div className="w-[280px] rounded-xl border border-[var(--border)] bg-[var(--popover)] py-1.5 shadow-lg backdrop-blur-md">
{capabilities.map((cap) => {
const Icon = cap.icon;
const selected = activeCap.value === cap.value;
@@ -392,7 +393,7 @@ export default memo(function ChatComposer({
{t("Drop files here")}
</span>
<span className="text-[11px] text-[var(--primary)]/70">
- {t("Images, PDF, DOCX, XLSX, PPTX")}
+ {t("Images, Office docs, code & text")}
</span>
</div>
</div>
@@ -463,6 +464,33 @@ export default memo(function ChatComposer({
</div>
);
}
+ if (isSvgFilename(a.filename) && a.previewUrl) {
+ return (
+ <div
+ key={`${a.filename}-${i}`}
+ className="group relative"
+ title={a.filename}
+ >
+ <div className="relative h-16 w-16 overflow-hidden rounded-lg border border-[var(--border)] bg-[var(--card)]">
+ {/* Native <img> is safe for SVG: scripts inside an
+ SVG don't execute under <img> context. Next.js
+ <Image> rejects SVG by default. */}
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img
+ src={a.previewUrl}
+ 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>
+ </div>
+ );
+ }
const spec = docIconFor(a.filename);
const Icon = spec.Icon;
const sizeLabel = a.size ? formatBytes(a.size) : "";
@@ -567,7 +595,7 @@ export default memo(function ChatComposer({
{toolMenuOpen && (
<div
ref={toolMenuRef}
- className="absolute bottom-full left-0 z-50 mb-1.5 min-w-[180px] rounded-lg border border-[var(--border)] bg-[var(--card)] py-1 shadow-lg"
+ className="absolute bottom-full left-0 z-50 mb-1.5 min-w-[180px] rounded-lg border border-[var(--border)] bg-[var(--popover)] py-1 shadow-lg backdrop-blur-md"
>
{researchSources.map((source) => {
const active = researchConfig.sources.includes(
@@ -635,7 +663,7 @@ export default memo(function ChatComposer({
{toolMenuOpen && (
<div
ref={toolMenuRef}
- className="absolute bottom-full left-0 z-50 mb-1.5 min-w-[180px] rounded-lg border border-[var(--border)] bg-[var(--card)] py-1 shadow-lg"
+ className="absolute bottom-full left-0 z-50 mb-1.5 min-w-[180px] rounded-lg border border-[var(--border)] bg-[var(--popover)] py-1 shadow-lg backdrop-blur-md"
>
{visibleTools.map((tool) => {
const active = selectedTools.has(tool.name);
@@ -701,7 +729,7 @@ export default memo(function ChatComposer({
{refMenuOpen && (
<div
ref={refMenuRef}
- className="absolute bottom-full left-0 z-50 mb-1.5 min-w-[180px] rounded-lg border border-[var(--border)] bg-[var(--card)] py-1 shadow-lg"
+ className="absolute bottom-full left-0 z-50 mb-1.5 min-w-[180px] rounded-lg border border-[var(--border)] bg-[var(--popover)] py-1 shadow-lg backdrop-blur-md"
>
<button
onClick={() => {
@@ -798,7 +826,7 @@ export default memo(function ChatComposer({
{skillMenuOpen && (
<div
ref={skillMenuRef}
- className="absolute bottom-full left-0 z-50 mb-1.5 max-h-[280px] min-w-[220px] overflow-y-auto rounded-lg border border-[var(--border)] bg-[var(--card)] py-1 shadow-lg"
+ className="absolute bottom-full left-0 z-50 mb-1.5 max-h-[280px] min-w-[220px] overflow-y-auto rounded-lg border border-[var(--border)] bg-[var(--popover)] py-1 shadow-lg backdrop-blur-md"
>
<button
onClick={() => onSetSkillsAuto(!skillsAutoMode)}
diff --git a/web/components/sidebar/VersionBadge.tsx b/web/components/sidebar/VersionBadge.tsx
index 5497d8601..5b5b20fea 100644
--- a/web/components/sidebar/VersionBadge.tsx
+++ b/web/components/sidebar/VersionBadge.tsx
@@ -2,8 +2,13 @@
import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
+import {
+ normalizeVersionTag,
+ parseBuild,
+ type ParsedBuild,
+} from "@/lib/version";
-interface VersionPayload {
+interface LatestVersionPayload {
tag: string | null;
name: string | null;
url: string | null;
@@ -11,23 +16,36 @@ interface VersionPayload {
source: "github" | "fallback";
}
+interface CurrentVersionPayload extends ParsedBuild {
+ source: "git" | "env" | "unknown";
+ detectedAt: string;
+}
+
+interface VersionPayload extends LatestVersionPayload {
+ current?: CurrentVersionPayload;
+ latest?: LatestVersionPayload;
+}
+
interface VersionBadgeProps {
/** Render the compact variant for the collapsed sidebar (currently hidden). */
collapsed?: boolean;
}
let _cache: VersionPayload | null = null;
+let _cacheAt = 0;
let _inflight: Promise<VersionPayload | null> | null = null;
+const CACHE_TTL_MS = 60_000;
async function loadVersion(): Promise<VersionPayload | null> {
- if (_cache) return _cache;
+ if (_cache && Date.now() - _cacheAt < CACHE_TTL_MS) return _cache;
if (_inflight) return _inflight;
_inflight = (async () => {
try {
- const res = await fetch("/api/version", { cache: "force-cache" });
+ const res = await fetch("/api/version", { cache: "no-store" });
if (!res.ok) return null;
const data = (await res.json()) as VersionPayload;
_cache = data;
+ _cacheAt = Date.now();
return data;
} catch {
return null;
@@ -38,60 +56,6 @@ async function loadVersion(): Promise<VersionPayload | null> {
return _inflight;
}
-interface ParsedBuild {
- /** Clean tag if exactly on a release commit, else null. */
- tag: string | null;
- /** True if `git describe` shows commits past the tag, or a dirty worktree. */
- isDev: boolean;
- /** True if the worktree was dirty at build time. */
- isDirty: boolean;
- /** Human-readable display ("v1.2.3", "v1.2.3+5", "v1.2.3+5·dev"). */
- display: string;
- /** Original raw value, for tooltip. */
- raw: string;
-}
-
-// Parse `git describe --tags --always --dirty=-dev` style output.
-// Examples we want to handle:
-// "v1.2.3" → exactly on tag
-// "v1.2.3-5-gabc1234" → 5 commits past v1.2.3
-// "v1.2.3-5-gabc1234-dev" → 5 commits past v1.2.3 + dirty
-// "v1.2.3-dev" → on tag but dirty
-// "abc1234" → no tag yet (shouldn't happen here)
-function parseBuild(raw: string): ParsedBuild | null {
- if (!raw) return null;
- const isDirty = raw.endsWith("-dev");
- const stripped = isDirty ? raw.slice(0, -4) : raw;
-
- const cleanTag = stripped.match(/^v?(\d+\.\d+\.\d+)$/);
- if (cleanTag) {
- const tag = `v${cleanTag[1]}`;
- return {
- tag,
- isDev: isDirty,
- isDirty,
- display: isDirty ? `${tag}·dev` : tag,
- raw,
- };
- }
-
- const ahead = stripped.match(/^v?(\d+\.\d+\.\d+)-(\d+)-g[0-9a-f]+$/);
- if (ahead) {
- const tag = `v${ahead[1]}`;
- const display = `${tag}+${ahead[2]}${isDirty ? "·dev" : ""}`;
- return { tag, isDev: true, isDirty, display, raw };
- }
-
- return { tag: null, isDev: true, isDirty, display: "dev", raw };
-}
-
-// Strict normalization for the GitHub release tag (always "v1.2.3" form).
-function normalizeStrict(raw: string | null | undefined): string | null {
- if (!raw) return null;
- const m = raw.match(/^v?(\d+\.\d+\.\d+)$/);
- return m ? `v${m[1]}` : null;
-}
-
type Status = "latest" | "outdated" | "dev" | "unknown";
export function VersionBadge({ collapsed = false }: VersionBadgeProps) {
@@ -100,26 +64,35 @@ export function VersionBadge({ collapsed = false }: VersionBadgeProps) {
useEffect(() => {
let cancelled = false;
- if (!_cache) {
+ const refresh = () => {
loadVersion().then((v) => {
if (!cancelled) setData(v);
});
- }
+ };
+ refresh();
+ const interval = window.setInterval(refresh, CACHE_TTL_MS);
return () => {
cancelled = true;
+ window.clearInterval(interval);
};
}, []);
- const buildRaw = process.env.NEXT_PUBLIC_APP_VERSION || "";
- const build = parseBuild(buildRaw);
- const latestNorm = normalizeStrict(data?.tag);
+ const fallbackBuild = parseBuild(process.env.NEXT_PUBLIC_APP_VERSION || "");
+ const build = data?.current?.raw ? data.current : fallbackBuild;
+ const latest = data?.latest ?? data;
+ const latestNorm = normalizeVersionTag(latest?.tag);
const { status, displayTag, href, tooltip } = useMemo(() => {
let status: Status = "unknown";
- if (build?.isDev) {
+ if (build?.tag && latestNorm) {
+ status =
+ build.tag === latestNorm
+ ? build.isDev
+ ? "dev"
+ : "latest"
+ : "outdated";
+ } else if (build?.isDev) {
status = "dev";
- } else if (build?.tag && latestNorm) {
- status = build.tag === latestNorm ? "latest" : "outdated";
}
// Display: prefer the running build (most accurate), fall back to the
@@ -127,7 +100,7 @@ export function VersionBadge({ collapsed = false }: VersionBadgeProps) {
const displayTag = build?.display ?? latestNorm ?? null;
const href =
- data?.url ??
+ latest?.url ??
(latestNorm
? `https://github.com/HKUDS/DeepTutor/releases/tag/${latestNorm}`
: "https://github.com/HKUDS/DeepTutor/releases");
@@ -135,8 +108,8 @@ export function VersionBadge({ collapsed = false }: VersionBadgeProps) {
let tooltip: string;
if (status === "latest" && displayTag) {
tooltip = `${displayTag} · ${t("Up to date")}`;
- } else if (status === "outdated" && build?.tag && latestNorm) {
- tooltip = `${build.tag} · ${t("Update available")}: ${latestNorm}`;
+ } else if (status === "outdated" && displayTag && latestNorm) {
+ tooltip = `${displayTag} · ${t("Update available")}: ${latestNorm}`;
} else if (status === "dev") {
const base = `${t("Development build")}: ${build?.raw ?? ""}`;
tooltip = latestNorm
@@ -149,7 +122,7 @@ export function VersionBadge({ collapsed = false }: VersionBadgeProps) {
}
return { status, displayTag, href, tooltip };
- }, [build, latestNorm, data?.url, t]);
+ }, [build, latestNorm, latest?.url, t]);
// Keep the collapsed sidebar entirely free of version chrome.
if (collapsed) return null;
diff --git a/web/lib/chat-export.ts b/web/lib/chat-export.ts
new file mode 100644
index 000000000..17dd028c8
--- /dev/null
+++ b/web/lib/chat-export.ts
@@ -0,0 +1,66 @@
+import type { MessageItem, MessageAttachment } from "@/context/UnifiedChatContext";
+
+function roleHeading(role: MessageItem["role"]): string {
+ if (role === "user") return "User";
+ if (role === "assistant") return "Assistant";
+ return "System";
+}
+
+function formatAttachments(attachments?: MessageAttachment[]): string {
+ if (!attachments?.length) return "";
+ const items = attachments
+ .map((a) => {
+ const name = a.filename || a.type || "attachment";
+ return a.mime_type ? `\`${name}\` (${a.mime_type})` : `\`${name}\``;
+ })
+ .join(", ");
+ return `_Attachments:_ ${items}\n\n`;
+}
+
+export interface BuildChatMarkdownOptions {
+ title?: string;
+ exportedAt?: Date;
+}
+
+export function buildChatMarkdown(
+ messages: MessageItem[],
+ options: BuildChatMarkdownOptions = {},
+): string {
+ const title = options.title?.trim() || "Chat Session";
+ const exportedAt = (options.exportedAt ?? new Date()).toISOString();
+ const header = `# ${title}\n\n_Exported: ${exportedAt}_\n\n---\n\n`;
+ const body = messages
+ .map((msg) => {
+ const role = roleHeading(msg.role);
+ const cap = msg.capability ? ` _(${msg.capability})_` : "";
+ const attachments = formatAttachments(msg.attachments);
+ const content = (msg.content ?? "").trim();
+ return `## ${role}${cap}\n\n${attachments}${content}`.trimEnd();
+ })
+ .join("\n\n---\n\n");
+ return header + body + "\n";
+}
+
+function sanitizeFilename(input: string): string {
+ const cleaned = input
+ .replace(/[\\/:*?"<>|\n\r\t]/g, "")
+ .replace(/\s+/g, "-")
+ .slice(0, 60);
+ return cleaned || "chat";
+}
+
+export function downloadChatMarkdown(
+ messages: MessageItem[],
+ options: BuildChatMarkdownOptions = {},
+): void {
+ if (!messages.length) return;
+ const markdown = buildChatMarkdown(messages, options);
+ const blob = new Blob([markdown], { type: "text/markdown;charset=utf-8" });
+ const url = URL.createObjectURL(blob);
+ const anchor = document.createElement("a");
+ anchor.href = url;
+ const date = new Date().toISOString().slice(0, 10);
+ anchor.download = `${sanitizeFilename(options.title || "chat")}-${date}.md`;
+ anchor.click();
+ URL.revokeObjectURL(url);
+}
diff --git a/web/lib/doc-attachments.ts b/web/lib/doc-attachments.ts
index c4e5c3126..44612eba9 100644
--- a/web/lib/doc-attachments.ts
+++ b/web/lib/doc-attachments.ts
@@ -1,25 +1,97 @@
/**
* Helpers for drag-and-drop document attachments in the chat composer.
*
- * Must stay in sync with backend `deeptutor/utils/document_extractor.py`.
+ * The accepted extension / MIME sets MUST stay in sync with the backend
+ * `deeptutor/utils/document_extractor.py` (which in turn mirrors the KB
+ * pipeline's `FileTypeRouter.TEXT_EXTENSIONS`). If you add a new format
+ * server-side, add it here too.
*/
import type { LucideIcon } from "lucide-react";
import {
+ Braces,
+ FileCode2,
+ FileImage,
+ FileJson,
FilePlus2,
FileSpreadsheet,
FileText,
FileType2,
+ Palette,
Presentation,
+ Settings2,
+ SquareTerminal,
} from "lucide-react";
-export const SUPPORTED_DOC_EXTS = [".pdf", ".docx", ".xlsx", ".pptx"] as const;
+/** Binary Office formats — handled by dedicated parsers server-side. */
+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.
+ */
+export const TEXT_LIKE_EXTS = [
+ // Plain text & markup
+ ".txt", ".text", ".log",
+ ".md", ".markdown", ".rst", ".asciidoc",
+ ".html", ".htm", ".xml",
+ ".svg", // vector image, treated as XML source; rendered via <img> client-side
+ // Data & config
+ ".json", ".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",
+] as const;
+
+export const SUPPORTED_DOC_EXTS = [
+ ...OFFICE_EXTS,
+ ...TEXT_LIKE_EXTS,
+] as const;
export const SUPPORTED_DOC_MIMES = new Set<string>([
+ // Office
"application/pdf",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
+ // Common text MIMEs — browsers are inconsistent so the extension fallback
+ // in classifyFile is the real workhorse.
+ "text/plain",
+ "text/markdown",
+ "text/html",
+ "text/xml",
+ "application/xml",
+ "application/json",
+ "text/csv",
+ "text/tab-separated-values",
+ "text/yaml",
+ "application/yaml",
+ "application/x-yaml",
+ "text/x-python",
+ "application/x-python-code",
+ "text/javascript",
+ "application/javascript",
+ "application/typescript",
+ "text/css",
+ "text/x-c",
+ "text/x-c++",
+ "text/x-java",
+ "text/x-go",
+ "text/x-rust",
+ "text/x-ruby",
+ "text/x-php",
+ "text/x-shellscript",
+ "application/sql",
+ "application/toml",
]);
export const MAX_ATTACHMENT_BYTES = 10 * 1024 * 1024;
@@ -47,19 +119,28 @@ function extOf(filename: string): string {
/**
* Classify a dropped/pasted file. Returns null for unsupported types.
*
- * Checks MIME first, falls back to extension because some OSes report an empty
- * `File.type` for .pptx / .xlsx.
+ * SVG is classified as "doc" even though its MIME starts with `image/`, because
+ * vision models reject SVG and sending the XML source lets the LLM reason about
+ * the vector content. The composer still renders a thumbnail via a raw <img>
+ * tag (safe — scripts inside an SVG don't run under <img> context).
+ *
+ * Otherwise MIME wins; extension is a fallback because browsers frequently
+ * report empty `File.type` for OOXML, code, and config files.
*/
export function classifyFile(file: File): FileKind | null {
+ const ext = extOf(file.name);
+ if (ext === ".svg" || file.type === "image/svg+xml") return "doc";
if (file.type && file.type.startsWith("image/")) return "image";
if (file.type && SUPPORTED_DOC_MIMES.has(file.type)) return "doc";
- const ext = extOf(file.name);
if (ext && (SUPPORTED_DOC_EXTS as readonly string[]).includes(ext)) return "doc";
- // Some browsers report application/zip for unknown OOXML — fall back to extension above.
- if (!file.type && ext === "") return null;
return null;
}
+/** Whether a filename refers to an SVG (case-insensitive). */
+export function isSvgFilename(filename: string): boolean {
+ return extOf(filename) === ".svg";
+}
+
/**
* Human-readable byte size: `1.2 MB`, `34.0 KB`.
*/
@@ -76,8 +157,32 @@ export interface DocIconSpec {
label: string; // e.g. "PDF"
}
+// 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",
+]);
+const SHELL_EXTS = new Set([".sh", ".bash", ".zsh", ".ps1", ".sql"]);
+const CONFIG_EXTS = new Set([
+ ".yaml", ".yml", ".toml", ".ini", ".cfg", ".conf", ".env", ".properties",
+]);
+const JSON_EXTS = new Set([".json"]);
+const MARKUP_EXTS = new Set([
+ ".md", ".markdown", ".rst", ".asciidoc",
+ ".html", ".htm", ".xml",
+ ".tex", ".latex", ".bib",
+]);
+const DATA_EXTS = new Set([".csv", ".tsv"]);
+const STYLE_EXTS = new Set([".css", ".scss", ".sass", ".less"]);
+const PLAIN_EXTS = new Set([".txt", ".text", ".log"]);
+
export function docIconFor(filename: string): DocIconSpec {
const ext = extOf(filename);
+ // Office first — keep the original distinctive colors
switch (ext) {
case ".pdf":
return { Icon: FileType2, tint: "text-red-500/80", label: "PDF" };
@@ -87,11 +192,38 @@ export function docIconFor(filename: string): DocIconSpec {
return { Icon: FileSpreadsheet, tint: "text-emerald-500/80", label: "XLSX" };
case ".pptx":
return { Icon: Presentation, tint: "text-orange-500/80", label: "PPTX" };
- default:
- return {
- Icon: FilePlus2,
- tint: "text-[var(--muted-foreground)]",
- label: ext ? ext.slice(1).toUpperCase() : "FILE",
- };
+ case ".svg":
+ return { Icon: FileImage, tint: "text-teal-500/80", label: "SVG" };
+ }
+ const label = ext ? ext.slice(1).toUpperCase() : "FILE";
+ if (CODE_EXTS.has(ext)) {
+ return { Icon: FileCode2, tint: "text-violet-500/80", label };
+ }
+ if (SHELL_EXTS.has(ext)) {
+ return { Icon: SquareTerminal, tint: "text-slate-500/80", label };
+ }
+ if (JSON_EXTS.has(ext)) {
+ return { Icon: FileJson, tint: "text-amber-500/80", label };
+ }
+ if (CONFIG_EXTS.has(ext)) {
+ return { Icon: Settings2, tint: "text-slate-500/80", label };
+ }
+ if (STYLE_EXTS.has(ext)) {
+ return { Icon: Palette, tint: "text-pink-500/80", label };
+ }
+ if (DATA_EXTS.has(ext)) {
+ return { Icon: FileSpreadsheet, tint: "text-emerald-400/80", label };
+ }
+ if (MARKUP_EXTS.has(ext)) {
+ return { Icon: Braces, tint: "text-sky-500/80", label };
+ }
+ if (PLAIN_EXTS.has(ext)) {
+ return { Icon: FileText, tint: "text-[var(--muted-foreground)]", label };
}
+ // Unknown text-ish file — neutral fallback
+ return {
+ Icon: FilePlus2,
+ tint: "text-[var(--muted-foreground)]",
+ label,
+ };
}
diff --git a/web/lib/version.ts b/web/lib/version.ts
new file mode 100644
index 000000000..6f46ecaa0
--- /dev/null
+++ b/web/lib/version.ts
@@ -0,0 +1,87 @@
+export type VersionSource = "git" | "env" | "unknown";
+
+export interface ParsedBuild {
+ /** Clean base tag if the version can be traced to a semver tag. */
+ tag: string | null;
+ /** True when commits exist after the tag, the tree is dirty, or no tag exists. */
+ isDev: boolean;
+ /** True when git reported a dirty worktree. */
+ isDirty: boolean;
+ /** Human-readable display, e.g. "v1.2.3" or "v1.2.3+5". */
+ display: string;
+ /** Original version string before parsing. */
+ raw: string;
+ /** Number of commits after the base tag, when available. */
+ commitsAhead: number | null;
+ /** Short git commit hash, when available. */
+ commit: string | null;
+}
+
+const SEMVER_TAG = String.raw`(\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?)`;
+const DIRTY_SUFFIX = "-dev";
+const DIRTY_DISPLAY = "\u00b7dev";
+
+export function parseBuild(rawValue: string | null | undefined): ParsedBuild | null {
+ const raw = rawValue?.trim() ?? "";
+ if (!raw) return null;
+
+ const isDirty = raw.endsWith(DIRTY_SUFFIX);
+ const stripped = isDirty ? raw.slice(0, -DIRTY_SUFFIX.length) : raw;
+
+ const ahead = stripped.match(new RegExp(`^v?${SEMVER_TAG}-(\\d+)-g([0-9a-f]+)$`));
+ if (ahead) {
+ const tag = `v${ahead[1]}`;
+ const commitsAhead = Number.parseInt(ahead[2], 10);
+ const commit = ahead[3];
+ return {
+ tag,
+ isDev: true,
+ isDirty,
+ display: `${tag}+${commitsAhead}${isDirty ? DIRTY_DISPLAY : ""}`,
+ raw,
+ commitsAhead,
+ commit,
+ };
+ }
+
+ const cleanTag = stripped.match(new RegExp(`^v?${SEMVER_TAG}$`));
+ if (cleanTag) {
+ const tag = `v${cleanTag[1]}`;
+ return {
+ tag,
+ isDev: isDirty,
+ isDirty,
+ display: isDirty ? `${tag}${DIRTY_DISPLAY}` : tag,
+ raw,
+ commitsAhead: null,
+ commit: null,
+ };
+ }
+
+ return {
+ tag: null,
+ isDev: true,
+ isDirty,
+ display: "dev",
+ raw,
+ commitsAhead: null,
+ commit: null,
+ };
+}
+
+export function normalizeVersionTag(raw: string | null | undefined): string | null {
+ const parsed = parseBuild(raw);
+ return parsed && !parsed.isDev ? parsed.tag : null;
+}
+
+export function unknownBuild(raw = ""): ParsedBuild {
+ return {
+ tag: null,
+ isDev: true,
+ isDirty: false,
+ display: raw.trim() || "unknown",
+ raw: raw.trim(),
+ commitsAhead: null,
+ commit: null,
+ };
+}
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index a6cd13c21..a4e84e925 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -51,6 +51,7 @@
"Drop images here": "Drop images here",
"Drop files here": "Drop files here",
"Images, PDF, DOCX, XLSX, PPTX": "Images, PDF, DOCX, XLSX, PPTX",
+ "Images, Office docs, code & text": "Images, Office docs, code & text",
"Unsupported file type: {{name}}": "Unsupported file type: {{name}}",
"File too large: {{name}}": "File too large: {{name}}",
"Too many files, skipped some": "Too many files, skipped some",
@@ -291,6 +292,8 @@
"New Chat": "New Chat",
"New chat": "New chat",
"Save to Notebook": "Save to Notebook",
+ "Download Markdown": "Download Markdown",
+ "Download chat history as Markdown": "Download chat history as Markdown",
"Saved to notebook.": "Saved to notebook.",
"Add some content before saving to a notebook.": "Add some content before saving to a notebook.",
"Untitled Co-Writer Document": "Untitled Co-Writer Document",
@@ -450,6 +453,8 @@
"RAG-Anything": "LlamaIndex",
"RAG-Anything (Docling)": "LlamaIndex",
"Documents": "Documents",
+ "document": "document",
+ "documents": "documents",
"Images": "Images",
"Ready": "Ready",
"Processing": "Processing",
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index 51f7ee480..696044847 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -51,6 +51,7 @@
"Drop images here": "将图片拖放到此处",
"Drop files here": "拖拽文件到此处",
"Images, PDF, DOCX, XLSX, PPTX": "图片、PDF、DOCX、XLSX、PPTX",
+ "Images, Office docs, code & text": "图片、Office 文档、代码和文本",
"Unsupported file type: {{name}}": "不支持的文件类型:{{name}}",
"File too large: {{name}}": "文件过大:{{name}}",
"Too many files, skipped some": "附件总量超出限制,已跳过部分文件",
@@ -291,6 +292,8 @@
"New Chat": "新对话",
"New chat": "新对话",
"Save to Notebook": "保存到笔记本",
+ "Download Markdown": "下载 Markdown",
+ "Download chat history as Markdown": "将聊天记录下载为 Markdown 文件",
"Saved to notebook.": "已保存到笔记本。",
"Add some content before saving to a notebook.": "请先写一些内容再保存到笔记本。",
"Untitled Co-Writer Document": "未命名的 Co-Writer 文档",
@@ -450,6 +453,8 @@
"RAG-Anything": "LlamaIndex",
"RAG-Anything (Docling)": "LlamaIndex",
"Documents": "文档",
+ "document": "个文档",
+ "documents": "个文档",
"Images": "图片",
"Ready": "就绪",
"Processing": "处理中",
diff --git a/web/tests/doc-attachments.test.ts b/web/tests/doc-attachments.test.ts
index 570b6db0b..d31aa0d58 100644
--- a/web/tests/doc-attachments.test.ts
+++ b/web/tests/doc-attachments.test.ts
@@ -5,6 +5,7 @@ import {
classifyFile,
docIconFor,
formatBytes,
+ isSvgFilename,
MAX_ATTACHMENT_BYTES,
} from "../lib/doc-attachments";
@@ -33,9 +34,38 @@ test("classifyFile: doc via extension fallback when MIME empty", () => {
assert.equal(classifyFile(makeFile("REPORT.XLSX")), "doc");
});
+test("classifyFile: accepts text & code", () => {
+ assert.equal(classifyFile(makeFile("notes.txt", "text/plain")), "doc");
+ assert.equal(classifyFile(makeFile("README.md", "text/markdown")), "doc");
+ assert.equal(classifyFile(makeFile("main.py", "text/x-python")), "doc");
+ // Empty MIME (common for code files) still accepted via extension
+ assert.equal(classifyFile(makeFile("script.js")), "doc");
+ assert.equal(classifyFile(makeFile("config.yaml")), "doc");
+ assert.equal(classifyFile(makeFile("data.csv")), "doc");
+});
+
+test("classifyFile: SVG classified as doc (not image)", () => {
+ // SVG has an image/* MIME but we route it through text extraction so the
+ // LLM gets its XML source. Thumbnail preview still renders via <img>.
+ assert.equal(classifyFile(makeFile("logo.svg", "image/svg+xml")), "doc");
+ assert.equal(classifyFile(makeFile("icon.SVG")), "doc");
+});
+
+test("isSvgFilename: case-insensitive extension check", () => {
+ assert.equal(isSvgFilename("foo.svg"), true);
+ assert.equal(isSvgFilename("FOO.SVG"), true);
+ assert.equal(isSvgFilename("foo.svg.bak"), false);
+ assert.equal(isSvgFilename("foo.png"), false);
+});
+
+test("docIconFor: SVG gets its own label", () => {
+ assert.equal(docIconFor("logo.svg").label, "SVG");
+ assert.ok(docIconFor("logo.svg").tint.includes("teal"));
+});
+
test("classifyFile: rejects unsupported", () => {
assert.equal(classifyFile(makeFile("a.zip", "application/zip")), null);
- assert.equal(classifyFile(makeFile("a.txt", "text/plain")), null);
+ assert.equal(classifyFile(makeFile("a.exe", "application/x-msdownload")), null);
assert.equal(classifyFile(makeFile("noext")), null);
});
@@ -56,13 +86,29 @@ test("formatBytes: negative / NaN returns empty string", () => {
// docIconFor -----------------------------------------------------------------
-test("docIconFor: labels by extension", () => {
+test("docIconFor: office labels & tints", () => {
assert.equal(docIconFor("report.pdf").label, "PDF");
+ assert.ok(docIconFor("report.pdf").tint.includes("red"));
assert.equal(docIconFor("report.docx").label, "DOCX");
assert.equal(docIconFor("report.xlsx").label, "XLSX");
assert.equal(docIconFor("report.pptx").label, "PPTX");
});
+test("docIconFor: code files share a code icon", () => {
+ assert.ok(docIconFor("main.py").tint.includes("violet"));
+ assert.ok(docIconFor("main.js").tint.includes("violet"));
+ assert.ok(docIconFor("main.rs").tint.includes("violet"));
+});
+
+test("docIconFor: json/config/data/markup categories", () => {
+ assert.ok(docIconFor("data.json").tint.includes("amber"));
+ assert.ok(docIconFor("config.yaml").tint.includes("slate"));
+ assert.ok(docIconFor("run.sh").tint.includes("slate"));
+ assert.ok(docIconFor("table.csv").tint.includes("emerald"));
+ assert.ok(docIconFor("doc.md").tint.includes("sky"));
+ assert.ok(docIconFor("style.css").tint.includes("pink"));
+});
+
test("docIconFor: fallback for unknown extension", () => {
assert.equal(docIconFor("mystery.bin").label, "BIN");
assert.equal(docIconFor("noext").label, "FILE");
diff --git a/web/tests/version.test.ts b/web/tests/version.test.ts
new file mode 100644
index 000000000..c0d5f3a4d
--- /dev/null
+++ b/web/tests/version.test.ts
@@ -0,0 +1,62 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { normalizeVersionTag, parseBuild, unknownBuild } from "../lib/version";
+
+test("parseBuild normalizes clean release tags", () => {
+ assert.deepEqual(parseBuild("1.2.3"), {
+ tag: "v1.2.3",
+ isDev: false,
+ isDirty: false,
+ display: "v1.2.3",
+ raw: "1.2.3",
+ commitsAhead: null,
+ commit: null,
+ });
+});
+
+test("parseBuild handles commits ahead of a release tag", () => {
+ assert.deepEqual(parseBuild("v1.2.3-5-gabc1234"), {
+ tag: "v1.2.3",
+ isDev: true,
+ isDirty: false,
+ display: "v1.2.3+5",
+ raw: "v1.2.3-5-gabc1234",
+ commitsAhead: 5,
+ commit: "abc1234",
+ });
+});
+
+test("parseBuild preserves dirty worktree state", () => {
+ assert.deepEqual(parseBuild("v1.2.3-5-gabc1234-dev"), {
+ tag: "v1.2.3",
+ isDev: true,
+ isDirty: true,
+ display: "v1.2.3+5\u00b7dev",
+ raw: "v1.2.3-5-gabc1234-dev",
+ commitsAhead: 5,
+ commit: "abc1234",
+ });
+});
+
+test("parseBuild supports prerelease tags", () => {
+ assert.equal(parseBuild("v1.0.0-beta.4")?.tag, "v1.0.0-beta.4");
+ assert.equal(parseBuild("v1.0.0-beta.4-2-gabc1234")?.display, "v1.0.0-beta.4+2");
+});
+
+test("normalizeVersionTag only returns exact version tags", () => {
+ assert.equal(normalizeVersionTag("1.2.3"), "v1.2.3");
+ assert.equal(normalizeVersionTag("v1.2.3-dev"), null);
+ assert.equal(normalizeVersionTag("v1.2.3-5-gabc1234"), null);
+});
+
+test("unknownBuild keeps an unknown raw version visible", () => {
+ assert.deepEqual(unknownBuild("abc1234"), {
+ tag: null,
+ isDev: true,
+ isDirty: false,
+ display: "abc1234",
+ raw: "abc1234",
+ commitsAhead: null,
+ commit: null,
+ });
+});