Skip to content

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

fix chat attatchments

Bingxi Zhao (Frank)c0037dfb58fa
diff --git a/Dockerfile b/Dockerfile
index 2024b96da..ac50e4c37 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -270,7 +270,12 @@ echo "[Backend] 🚀 Starting FastAPI backend on ${BACKEND_HOST}:${BACKEND_PORT
# BACKEND_HOST defaults to 0.0.0.0 (LAN-reachable, matches bridge-mode
# port publishing). Set BACKEND_HOST=127.0.0.1 when running with
# network_mode: host to keep the backend on loopback only.
-exec python -m uvicorn deeptutor.api.main:app --host ${BACKEND_HOST} --port ${BACKEND_PORT} --no-access-log
+#
+# --ws-max-size: chat attachments travel base64 inside one WS message; derive
+# the frame cap from the configured attachment policy (system.json) so uploads
+# the policy allows are not severed by uvicorn's 16MB default.
+WS_MAX_SIZE=$(python -c "from deeptutor.services.config import get_ws_max_size; print(get_ws_max_size())" 2>/dev/null || echo 16777216)
+exec python -m uvicorn deeptutor.api.main:app --host ${BACKEND_HOST} --port ${BACKEND_PORT} --no-access-log --ws-max-size ${WS_MAX_SIZE}
EOF
RUN sed -i 's/\r$//' /app/start-backend.sh && chmod +x /app/start-backend.sh
@@ -453,7 +458,7 @@ RUN pip install --no-cache-dir \
# the production stage is reused as-is.
RUN cat > /etc/supervisor/conf.d/programs.conf <<'EOF'
[program:backend]
-command=python -m uvicorn deeptutor.api.main:app --host 0.0.0.0 --port %(ENV_BACKEND_PORT)s --reload --no-access-log
+command=/bin/bash -c "exec python -m uvicorn deeptutor.api.main:app --host 0.0.0.0 --port ${BACKEND_PORT:-8001} --reload --no-access-log --ws-max-size $(python -c 'from deeptutor.services.config import get_ws_max_size; print(get_ws_max_size())' 2>/dev/null || echo 16777216)"
directory=/app
user=deeptutor
autostart=true
diff --git a/deeptutor/api/routers/partners.py b/deeptutor/api/routers/partners.py
index 3b347abcb..c6c704f84 100644
--- a/deeptutor/api/routers/partners.py
+++ b/deeptutor/api/routers/partners.py
@@ -816,10 +816,23 @@ def _resolve_http_session(payload: ChatMessageRequest) -> tuple[str, str]:
return session_id, session_id
-_PARTNER_UPLOAD_MAX_BYTES = 10 * 1024 * 1024
+# Fallback caps when the settings layer is unavailable; the effective values
+# come from the shared chat-attachment policy (data/user/settings/system.json,
+# editable at /settings/attachments).
+_PARTNER_UPLOAD_MAX_BYTES = 20 * 1024 * 1024
_PARTNER_UPLOAD_MAX_TOTAL_BYTES = 25 * 1024 * 1024
+def _partner_upload_caps() -> tuple[int, int]:
+ try:
+ from deeptutor.services.config.runtime_settings import get_chat_attachment_limits
+
+ limits = get_chat_attachment_limits()
+ return limits.max_file_bytes, limits.max_total_bytes
+ except Exception: # pragma: no cover - defensive fallback
+ return _PARTNER_UPLOAD_MAX_BYTES, _PARTNER_UPLOAD_MAX_TOTAL_BYTES
+
+
def _clean_attachment_base64(value: str) -> str:
text = str(value or "").strip()
if text.startswith("data:") and "," in text:
@@ -842,6 +855,7 @@ def _materialize_partner_attachments(
return []
media_dir = get_partner_media_dir(partner_id, "web")
+ max_file_bytes, max_total_bytes = _partner_upload_caps()
total_bytes = 0
media_paths: list[str] = []
for item in attachments:
@@ -857,12 +871,12 @@ def _materialize_partner_attachments(
status_code=422,
detail=f"Invalid attachment data for {item.filename or 'file'}",
) from exc
- if len(data) > _PARTNER_UPLOAD_MAX_BYTES:
+ if len(data) > max_file_bytes:
raise HTTPException(
status_code=413,
detail=f"Attachment too large: {item.filename or 'file'}",
)
- if total_bytes + len(data) > _PARTNER_UPLOAD_MAX_TOTAL_BYTES:
+ if total_bytes + len(data) > max_total_bytes:
raise HTTPException(status_code=413, detail="Attachment batch too large")
total_bytes += len(data)
diff --git a/deeptutor/api/routers/settings.py b/deeptutor/api/routers/settings.py
index 72f6f903b..e2fc7b2e7 100644
--- a/deeptutor/api/routers/settings.py
+++ b/deeptutor/api/routers/settings.py
@@ -27,6 +27,12 @@ from deeptutor.services.config import (
get_runtime_settings_service,
)
from deeptutor.services.config.origins import normalize_origins
+from deeptutor.services.config.runtime_settings import (
+ CHAT_ATTACHMENT_CHARS_RANGE,
+ CHAT_ATTACHMENT_MAX_FILE_MB_RANGE,
+ CHAT_ATTACHMENT_MAX_TOTAL_MB_RANGE,
+ compute_ws_max_size,
+)
from deeptutor.services.embedding.client import reset_embedding_client
from deeptutor.services.llm.client import reset_llm_client
from deeptutor.services.llm.config import clear_llm_config_cache
@@ -138,6 +144,28 @@ class NetworkSettingsUpdate(BaseModel):
cors_origins: list[str] = Field(default_factory=list)
+class ChatAttachmentSettingsUpdate(BaseModel):
+ """Chat attachment policy (size caps + extraction budgets).
+
+ Bounds mirror the normalization clamps in
+ ``runtime_settings.CHAT_ATTACHMENT_*_RANGE`` so the API rejects loudly
+ what the file layer would silently clamp.
+ """
+
+ max_file_mb: int = Field(
+ ge=CHAT_ATTACHMENT_MAX_FILE_MB_RANGE[0], le=CHAT_ATTACHMENT_MAX_FILE_MB_RANGE[1]
+ )
+ max_total_mb: int = Field(
+ ge=CHAT_ATTACHMENT_MAX_TOTAL_MB_RANGE[0], le=CHAT_ATTACHMENT_MAX_TOTAL_MB_RANGE[1]
+ )
+ max_chars_per_doc: int = Field(
+ ge=CHAT_ATTACHMENT_CHARS_RANGE[0], le=CHAT_ATTACHMENT_CHARS_RANGE[1]
+ )
+ max_chars_total: int = Field(
+ ge=CHAT_ATTACHMENT_CHARS_RANGE[0], le=CHAT_ATTACHMENT_CHARS_RANGE[1]
+ )
+
+
class MinerUSettingsUpdate(BaseModel):
"""MinerU PDF-parsing backend settings.
@@ -485,6 +513,61 @@ async def update_network_settings(payload: NetworkSettingsUpdate):
return _network_settings_payload()
+def _chat_attachments_payload() -> dict[str, Any]:
+ service = get_runtime_settings_service()
+ stored = service.load_system(include_process_overrides=False)
+ effective = service.load_system(include_process_overrides=True)
+ max_total_bytes = int(effective["chat_attachment_max_total_mb"]) * 1024 * 1024
+ return {
+ "settings": {
+ "max_file_mb": stored["chat_attachment_max_file_mb"],
+ "max_total_mb": stored["chat_attachment_max_total_mb"],
+ "max_chars_per_doc": stored["chat_attachment_max_chars_per_doc"],
+ "max_chars_total": stored["chat_attachment_max_chars_total"],
+ },
+ "effective": {
+ "max_file_bytes": int(effective["chat_attachment_max_file_mb"]) * 1024 * 1024,
+ "max_total_bytes": max_total_bytes,
+ "max_chars_per_doc": effective["chat_attachment_max_chars_per_doc"],
+ "max_chars_total": effective["chat_attachment_max_chars_total"],
+ "ws_max_size": compute_ws_max_size(max_total_bytes),
+ },
+ "bounds": {
+ "max_file_mb": list(CHAT_ATTACHMENT_MAX_FILE_MB_RANGE),
+ "max_total_mb": list(CHAT_ATTACHMENT_MAX_TOTAL_MB_RANGE),
+ "chars": list(CHAT_ATTACHMENT_CHARS_RANGE),
+ },
+ # Size caps and char budgets are re-read on every message, but the WS
+ # frame ceiling is fixed at process start — uploads bigger than the
+ # old ceiling need a backend restart to actually go through.
+ "restart_required_for_larger_uploads": True,
+ }
+
+
[email protected]("/chat-attachments")
+async def get_chat_attachment_settings():
+ """Chat attachment policy. Readable by any user — the composer needs the
+ caps to gate file picks client-side; only the PUT is admin-gated."""
+ return _chat_attachments_payload()
+
+
[email protected]("/chat-attachments")
+async def update_chat_attachment_settings(payload: ChatAttachmentSettingsUpdate):
+ _require_settings_admin()
+ service = get_runtime_settings_service()
+ current = service.load_system(include_process_overrides=False)
+ service.save_system(
+ {
+ **current,
+ "chat_attachment_max_file_mb": payload.max_file_mb,
+ "chat_attachment_max_total_mb": payload.max_total_mb,
+ "chat_attachment_max_chars_per_doc": payload.max_chars_per_doc,
+ "chat_attachment_max_chars_total": payload.max_chars_total,
+ }
+ )
+ return _chat_attachments_payload()
+
+
def _mineru_settings_payload() -> dict[str, Any]:
"""MinerU settings for the UI, with the API token redacted to a boolean.
diff --git a/deeptutor/api/run_server.py b/deeptutor/api/run_server.py
index 7a877eca3..5f3476150 100644
--- a/deeptutor/api/run_server.py
+++ b/deeptutor/api/run_server.py
@@ -35,6 +35,7 @@ def main() -> None:
# Get port from configuration
from deeptutor.logging import configure_logging
from deeptutor.runtime.mode import RunMode, set_mode
+ from deeptutor.services.config import get_ws_max_size
from deeptutor.services.setup import get_backend_port
set_mode(RunMode.SERVER)
@@ -57,7 +58,8 @@ def main() -> None:
# Filter out non-existent directories to avoid warnings
reload_excludes = [d for d in reload_excludes if Path(d).exists()]
- # Start uvicorn server with reload enabled
+ # Start uvicorn server with reload enabled. ws_max_size tracks the
+ # configured chat-attachment total so base64 uploads fit in one WS frame.
uvicorn.run(
"deeptutor.api.main:app",
host="0.0.0.0",
@@ -66,6 +68,7 @@ def main() -> None:
reload_excludes=reload_excludes,
log_level="info",
access_log=False,
+ ws_max_size=get_ws_max_size(),
)
diff --git a/deeptutor/runtime/launcher.py b/deeptutor/runtime/launcher.py
index 6857f5ec1..841f89f36 100644
--- a/deeptutor/runtime/launcher.py
+++ b/deeptutor/runtime/launcher.py
@@ -728,6 +728,7 @@ def start(home: str | Path | None = None) -> None:
from deeptutor.services.config import (
ensure_runtime_settings_files,
export_runtime_settings_to_env,
+ get_ws_max_size,
load_auth_settings,
load_launch_settings,
)
@@ -843,6 +844,12 @@ def start(home: str | Path | None = None) -> None:
# 200 polling (/settings, /tools, /knowledge/list, ...) stays out of the
# logs — matching run_server.py's access_log=False.
"--no-access-log",
+ # Chat attachments ride the unified WS as base64 in one JSON message;
+ # uvicorn's default 16MB frame cap would sever the socket on uploads
+ # allowed by the configured policy. Derived from system.json — raising
+ # the attachment limits therefore takes a restart to fully apply.
+ "--ws-max-size",
+ str(get_ws_max_size()),
]
processes: list[ManagedProcess] = []
diff --git a/deeptutor/services/config/__init__.py b/deeptutor/services/config/__init__.py
index 784c19a67..c0bf832de 100644
--- a/deeptutor/services/config/__init__.py
+++ b/deeptutor/services/config/__init__.py
@@ -20,10 +20,13 @@ from .loader import (
)
from .model_catalog import ModelCatalogService, get_model_catalog_service
from .runtime_settings import (
+ ChatAttachmentLimits,
RuntimeSettingsService,
ensure_runtime_settings_files,
export_runtime_settings_to_env,
+ get_chat_attachment_limits,
get_runtime_settings_service,
+ get_ws_max_size,
load_auth_settings,
load_graphrag_settings,
load_integrations_settings,
@@ -68,10 +71,13 @@ __all__ = [
"ConfigTestRunner",
"TestRun",
"get_config_test_runner",
+ "ChatAttachmentLimits",
"RuntimeSettingsService",
"ensure_runtime_settings_files",
"export_runtime_settings_to_env",
+ "get_chat_attachment_limits",
"get_runtime_settings_service",
+ "get_ws_max_size",
"load_auth_settings",
"load_graphrag_settings",
"load_integrations_settings",
diff --git a/deeptutor/services/config/runtime_settings.py b/deeptutor/services/config/runtime_settings.py
index c75f5c025..88e5723cd 100644
--- a/deeptutor/services/config/runtime_settings.py
+++ b/deeptutor/services/config/runtime_settings.py
@@ -1,6 +1,7 @@
from __future__ import annotations
from copy import deepcopy
+from dataclasses import dataclass
import json
import os
from pathlib import Path
@@ -27,8 +28,26 @@ DEFAULT_SYSTEM_SETTINGS: dict[str, Any] = {
# deployment shapes; a stronger backend (runner sidecar / bwrap) still
# takes precedence when available. Set false to disable host-side exec.
"sandbox_allow_subprocess": True,
+ # Chat attachment policy. Size caps gate what the composer accepts and
+ # what the turn runtime / partner upload endpoints extract; the char
+ # budgets bound how much extracted text is inlined into the LLM context
+ # per document / per turn. Enforcement reads these at call time, so
+ # changes apply to the next message — but uploads whose base64 payload
+ # exceeds the WebSocket frame ceiling need a restart (see
+ # ``compute_ws_max_size``, wired at every uvicorn launch point).
+ "chat_attachment_max_file_mb": 20,
+ "chat_attachment_max_total_mb": 25,
+ "chat_attachment_max_chars_per_doc": 200_000,
+ "chat_attachment_max_chars_total": 150_000,
}
+# Clamp bounds for the chat attachment knobs. The MB ceilings are deliberately
+# generous (local deployments parse in-process; the WS frame cap is derived
+# from the total) while still refusing nonsense like 0 or 10^9.
+CHAT_ATTACHMENT_MAX_FILE_MB_RANGE = (1, 1024)
+CHAT_ATTACHMENT_MAX_TOTAL_MB_RANGE = (1, 2048)
+CHAT_ATTACHMENT_CHARS_RANGE = (10_000, 5_000_000)
+
DEFAULT_AUTH_SETTINGS: dict[str, Any] = {
"version": 1,
"enabled": False,
@@ -606,6 +625,14 @@ class RuntimeSettingsService:
payload["chat_attachment_dir"] = value
if value := self._process_env_value("DEEPTUTOR_SANDBOX_ALLOW_SUBPROCESS"):
payload["sandbox_allow_subprocess"] = value
+ if value := self._process_env_value("CHAT_ATTACHMENT_MAX_FILE_MB"):
+ payload["chat_attachment_max_file_mb"] = value
+ if value := self._process_env_value("CHAT_ATTACHMENT_MAX_TOTAL_MB"):
+ payload["chat_attachment_max_total_mb"] = value
+ if value := self._process_env_value("CHAT_ATTACHMENT_MAX_CHARS_PER_DOC"):
+ payload["chat_attachment_max_chars_per_doc"] = value
+ if value := self._process_env_value("CHAT_ATTACHMENT_MAX_CHARS_TOTAL"):
+ payload["chat_attachment_max_chars_total"] = value
return self._normalize_system(payload)
def _apply_auth_process_overrides(self, settings: dict[str, Any]) -> dict[str, Any]:
@@ -840,6 +867,18 @@ class RuntimeSettingsService:
public_api_base = _string(settings.get("next_public_api_base_external")) or _string(
settings.get("public_api_base")
)
+ max_file_mb = _coerce_clamped_int(
+ settings.get("chat_attachment_max_file_mb"),
+ DEFAULT_SYSTEM_SETTINGS["chat_attachment_max_file_mb"],
+ *CHAT_ATTACHMENT_MAX_FILE_MB_RANGE,
+ )
+ max_total_mb = _coerce_clamped_int(
+ settings.get("chat_attachment_max_total_mb"),
+ DEFAULT_SYSTEM_SETTINGS["chat_attachment_max_total_mb"],
+ *CHAT_ATTACHMENT_MAX_TOTAL_MB_RANGE,
+ )
+ # A per-message total below the per-file cap is contradictory; lift it.
+ max_total_mb = max(max_total_mb, max_file_mb)
return {
"version": 1,
"backend_port": _coerce_port(settings.get("backend_port"), 8001),
@@ -853,6 +892,18 @@ class RuntimeSettingsService:
"sandbox_allow_subprocess": _coerce_bool(
settings.get("sandbox_allow_subprocess"), True
),
+ "chat_attachment_max_file_mb": max_file_mb,
+ "chat_attachment_max_total_mb": max_total_mb,
+ "chat_attachment_max_chars_per_doc": _coerce_clamped_int(
+ settings.get("chat_attachment_max_chars_per_doc"),
+ DEFAULT_SYSTEM_SETTINGS["chat_attachment_max_chars_per_doc"],
+ *CHAT_ATTACHMENT_CHARS_RANGE,
+ ),
+ "chat_attachment_max_chars_total": _coerce_clamped_int(
+ settings.get("chat_attachment_max_chars_total"),
+ DEFAULT_SYSTEM_SETTINGS["chat_attachment_max_chars_total"],
+ *CHAT_ATTACHMENT_CHARS_RANGE,
+ ),
}
def _normalize_auth(self, settings: dict[str, Any]) -> dict[str, Any]:
@@ -911,6 +962,54 @@ def load_system_settings() -> dict[str, Any]:
return get_runtime_settings_service().load_system()
+@dataclass(frozen=True)
+class ChatAttachmentLimits:
+ """Effective chat-attachment policy, in enforcement-ready units."""
+
+ max_file_bytes: int
+ max_total_bytes: int
+ max_chars_per_doc: int
+ max_chars_total: int
+
+
+def get_chat_attachment_limits() -> ChatAttachmentLimits:
+ """Resolve the chat attachment policy from system.json (+ env overrides).
+
+ Read at call time by every enforcement site (turn runtime extraction,
+ partner uploads, the composer via the settings API) so edits apply to the
+ next message without a restart.
+ """
+ system = load_system_settings()
+ return ChatAttachmentLimits(
+ max_file_bytes=int(system["chat_attachment_max_file_mb"]) * 1024 * 1024,
+ max_total_bytes=int(system["chat_attachment_max_total_mb"]) * 1024 * 1024,
+ max_chars_per_doc=int(system["chat_attachment_max_chars_per_doc"]),
+ max_chars_total=int(system["chat_attachment_max_chars_total"]),
+ )
+
+
+# uvicorn's default WebSocket frame ceiling. Never derive below it so chat
+# behaves identically to older builds even if the configured totals are tiny.
+_WS_MAX_SIZE_FLOOR = 16 * 1024 * 1024
+
+
+def compute_ws_max_size(max_total_bytes: int) -> int:
+ """WebSocket message ceiling that fits a full attachment batch.
+
+ Chat attachments ride the unified WS as base64 inside one JSON message
+ (×4/3 inflation), so uvicorn's frame cap — not the policy above — is the
+ binding constraint for large uploads. Add slack for the JSON envelope
+ (message text, metadata, quoting) on top of the inflated payload.
+ """
+ inflated = (max_total_bytes * 4) // 3
+ return max(_WS_MAX_SIZE_FLOOR, inflated + 8 * 1024 * 1024)
+
+
+def get_ws_max_size() -> int:
+ """Frame ceiling for the current settings — wire into every uvicorn launch."""
+ return compute_ws_max_size(get_chat_attachment_limits().max_total_bytes)
+
+
def load_auth_settings() -> dict[str, Any]:
return get_runtime_settings_service().load_auth()
@@ -944,6 +1043,9 @@ def export_runtime_settings_to_env(*, overwrite: bool = True) -> dict[str, str]:
__all__ = [
+ "CHAT_ATTACHMENT_CHARS_RANGE",
+ "CHAT_ATTACHMENT_MAX_FILE_MB_RANGE",
+ "CHAT_ATTACHMENT_MAX_TOTAL_MB_RANGE",
"DEFAULT_AUTH_SETTINGS",
"DEFAULT_DOCUMENT_PARSING_SETTINGS",
"DEFAULT_GRAPHRAG_SETTINGS",
@@ -960,10 +1062,14 @@ __all__ = [
"DOCUMENT_PARSING_ENGINE_TEXT_ONLY",
"MINERU_MODE_CLOUD",
"MINERU_MODE_LOCAL",
+ "ChatAttachmentLimits",
"RuntimeSettingsService",
+ "compute_ws_max_size",
"ensure_runtime_settings_files",
"export_runtime_settings_to_env",
+ "get_chat_attachment_limits",
"get_runtime_settings_service",
+ "get_ws_max_size",
"load_auth_settings",
"load_document_parsing_settings",
"load_graphrag_settings",
diff --git a/deeptutor/utils/document_extractor.py b/deeptutor/utils/document_extractor.py
index 5754d6cf6..6299d77bd 100644
--- a/deeptutor/utils/document_extractor.py
+++ b/deeptutor/utils/document_extractor.py
@@ -68,11 +68,40 @@ _OFFICE_EXTENSIONS: frozenset[str] = frozenset(FileTypeRouter.PARSER_EXTENSIONS)
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
+# Built-in defaults, kept as module constants for callers that pass explicit
+# budgets (the KB text_only engine, tests). The chat turn path resolves the
+# effective values from system.json via ``_current_limits()`` on every call,
+# so the /settings/attachments page applies without a restart.
+MAX_DOC_BYTES = 20 * 1024 * 1024
MAX_TOTAL_DOC_BYTES = 25 * 1024 * 1024
MAX_EXTRACTED_CHARS_PER_DOC = 200_000
MAX_EXTRACTED_CHARS_TOTAL = 150_000
+
+def _current_limits() -> tuple[int, int, int, int]:
+ """(max_file_bytes, max_total_bytes, max_chars_per_doc, max_chars_total).
+
+ Falls back to the module defaults when the settings layer is unavailable
+ (e.g. unit tests running without a data directory).
+ """
+ try:
+ from deeptutor.services.config.runtime_settings import get_chat_attachment_limits
+
+ limits = get_chat_attachment_limits()
+ return (
+ limits.max_file_bytes,
+ limits.max_total_bytes,
+ limits.max_chars_per_doc,
+ limits.max_chars_total,
+ )
+ except Exception: # pragma: no cover - defensive fallback
+ return (
+ MAX_DOC_BYTES,
+ MAX_TOTAL_DOC_BYTES,
+ MAX_EXTRACTED_CHARS_PER_DOC,
+ MAX_EXTRACTED_CHARS_TOTAL,
+ )
+
_PDF_MAGIC = b"%PDF-"
_OOXML_MAGIC = b"PK\x03\x04"
@@ -562,6 +591,7 @@ def extract_documents_from_records(
"""
doc_texts: list[str] = []
updated: list[dict] = []
+ max_file_bytes, max_total_bytes, max_chars_per_doc, max_chars_total = _current_limits()
total_bytes = 0
total_chars = 0
over_quota = False
@@ -594,7 +624,7 @@ def extract_documents_from_records(
updated.append(record)
continue
- if total_bytes + len(data) > MAX_TOTAL_DOC_BYTES:
+ if total_bytes + len(data) > max_total_bytes:
over_quota = True
doc_texts.append(f"[File: {filename} — skipped: total attachment quota exceeded]")
record["base64"] = ""
@@ -605,7 +635,12 @@ def extract_documents_from_records(
total_bytes += len(data)
try:
- text = extract_text_from_bytes(filename, data)
+ text = extract_text_from_bytes(
+ filename,
+ data,
+ max_bytes=max_file_bytes,
+ max_chars=max_chars_per_doc,
+ )
except DocumentExtractionError as exc:
logger.info("Document extraction failed for %s: %s", filename, exc)
doc_texts.append(f"[File: {filename} — could not be read: {exc}]")
@@ -614,7 +649,7 @@ def extract_documents_from_records(
updated.append(record)
continue
- remaining_budget = MAX_EXTRACTED_CHARS_TOTAL - total_chars
+ remaining_budget = max_chars_total - total_chars
if remaining_budget <= 0:
doc_texts.append(f"[File: {filename} — skipped: total extracted-text quota exceeded]")
record["base64"] = ""
diff --git a/deeptutor_cli/main.py b/deeptutor_cli/main.py
index b1edbcc63..2c881ef85 100644
--- a/deeptutor_cli/main.py
+++ b/deeptutor_cli/main.py
@@ -155,12 +155,17 @@ def serve(
)
raise typer.Exit(code=1)
+ from deeptutor.services.config import get_ws_max_size
+
+ # ws_max_size tracks the configured chat-attachment total so base64
+ # uploads fit in one WS frame (uvicorn defaults to 16MB).
uvicorn.run(
"deeptutor.api.main:app",
host=host,
port=port,
reload=reload,
reload_excludes=["web/*", "data/*"] if reload else None,
+ ws_max_size=get_ws_max_size(),
)
diff --git a/tests/api/test_settings_router.py b/tests/api/test_settings_router.py
index d754bdd6a..f2a4b63d8 100644
--- a/tests/api/test_settings_router.py
+++ b/tests/api/test_settings_router.py
@@ -198,6 +198,37 @@ async def test_network_settings_roundtrip_normalizes_cors_origins(
assert response["auth"]["cross_site_cookie_ready"] is True
+async def test_chat_attachment_settings_roundtrip(
+ monkeypatch: pytest.MonkeyPatch, tmp_path
+) -> None:
+ service = RuntimeSettingsService(tmp_path / "settings", process_env={})
+ service.save_system({"backend_port": 8001, "frontend_port": 3782})
+ monkeypatch.setattr(settings_router, "get_runtime_settings_service", lambda: service)
+
+ initial = await settings_router.get_chat_attachment_settings()
+ assert initial["settings"]["max_file_mb"] == 20
+ assert initial["effective"]["max_file_bytes"] == 20 * 1024 * 1024
+
+ payload = settings_router.ChatAttachmentSettingsUpdate(
+ max_file_mb=100,
+ max_total_mb=200,
+ max_chars_per_doc=400_000,
+ max_chars_total=300_000,
+ )
+ response = await settings_router.update_chat_attachment_settings(payload)
+
+ assert response["settings"]["max_file_mb"] == 100
+ assert response["settings"]["max_total_mb"] == 200
+ assert response["effective"]["max_total_bytes"] == 200 * 1024 * 1024
+ # WS frame ceiling covers the base64-inflated total.
+ assert response["effective"]["ws_max_size"] > (200 * 1024 * 1024 * 4) // 3
+ # Other system.json keys survive the partial update.
+ stored = service.load_system(include_process_overrides=False)
+ assert stored["backend_port"] == 8001
+ assert stored["chat_attachment_max_chars_per_doc"] == 400_000
+
+
@pytest.mark.asyncio
async def test_mineru_settings_roundtrip_redacts_token(
monkeypatch: pytest.MonkeyPatch, tmp_path
diff --git a/tests/services/config/test_runtime_settings.py b/tests/services/config/test_runtime_settings.py
index e6075bc2e..c531d31e6 100644
--- a/tests/services/config/test_runtime_settings.py
+++ b/tests/services/config/test_runtime_settings.py
@@ -382,3 +382,66 @@ def test_runtime_settings_can_ignore_process_overrides(tmp_path: Path) -> None:
assert service.load_system()["backend_port"] == 8001
assert service.load_auth()["enabled"] is False
+
+
+def test_chat_attachment_limits_defaults_and_clamping(tmp_path: Path) -> None:
+ service = RuntimeSettingsService(tmp_path / "settings", process_env={})
+ system = service.load_system()
+ assert system["chat_attachment_max_file_mb"] == 20
+ assert system["chat_attachment_max_total_mb"] == 25
+ assert system["chat_attachment_max_chars_per_doc"] == 200_000
+ assert system["chat_attachment_max_chars_total"] == 150_000
+
+ # Total below the per-file cap is contradictory — lifted to match.
+ saved = service.save_system(
+ {"chat_attachment_max_file_mb": 200, "chat_attachment_max_total_mb": 50}
+ )
+ assert saved["chat_attachment_max_file_mb"] == 200
+ assert saved["chat_attachment_max_total_mb"] == 200
+
+ # Out-of-range / garbage values clamp or fall back to defaults.
+ saved = service.save_system(
+ {
+ "chat_attachment_max_file_mb": 10_000,
+ "chat_attachment_max_total_mb": 0,
+ "chat_attachment_max_chars_per_doc": "not-a-number",
+ "chat_attachment_max_chars_total": 1,
+ }
+ )
+ assert saved["chat_attachment_max_file_mb"] == 1024
+ assert saved["chat_attachment_max_total_mb"] == 1024
+ assert saved["chat_attachment_max_chars_per_doc"] == 200_000
+ assert saved["chat_attachment_max_chars_total"] == 10_000
+
+
+def test_chat_attachment_limits_env_overrides(tmp_path: Path) -> None:
+ service = RuntimeSettingsService(
+ tmp_path / "settings",
+ process_env={
+ "CHAT_ATTACHMENT_MAX_FILE_MB": "64",
+ "CHAT_ATTACHMENT_MAX_TOTAL_MB": "128",
+ "CHAT_ATTACHMENT_MAX_CHARS_PER_DOC": "400000",
+ "CHAT_ATTACHMENT_MAX_CHARS_TOTAL": "300000",
+ },
+ )
+ service.save_system({})
+
+ effective = service.load_system()
+ assert effective["chat_attachment_max_file_mb"] == 64
+ assert effective["chat_attachment_max_total_mb"] == 128
+ assert effective["chat_attachment_max_chars_per_doc"] == 400_000
+ assert effective["chat_attachment_max_chars_total"] == 300_000
+ # The file keeps the stored (default) values — env is a process override.
+ assert _read_json(service.path_for("system"))["chat_attachment_max_file_mb"] == 20
+
+
+def test_compute_ws_max_size_floor_and_inflation() -> None:
+ from deeptutor.services.config.runtime_settings import compute_ws_max_size
+
+ # Small totals never drop below uvicorn's 16MB default.
+ assert compute_ws_max_size(1 * 1024 * 1024) == 16 * 1024 * 1024
+ # Large totals get base64 inflation (×4/3) plus envelope slack.
+ total = 100 * 1024 * 1024
+ derived = compute_ws_max_size(total)
+ assert derived > (total * 4) // 3
+ assert derived == (total * 4) // 3 + 8 * 1024 * 1024
diff --git a/tests/utils/test_document_extractor.py b/tests/utils/test_document_extractor.py
index 66f0608db..f89edf63a 100644
--- a/tests/utils/test_document_extractor.py
+++ b/tests/utils/test_document_extractor.py
@@ -374,3 +374,75 @@ class TestExtractDocumentsFromRecords:
# paths end up as an error marker since resulting bytes won't pass magic check
assert len(doc_texts) == 1
assert "bad.docx" in doc_texts[0]
+
+ def test_limits_come_from_settings_layer(self, monkeypatch) -> None:
+ """extract_documents_from_records honors the configured policy."""
+ from deeptutor.services.config import runtime_settings as rs
+
+ # Tiny caps prove the configured values flow through (defaults would
+ # accept everything here).
+ def set_limits(max_file: int, max_total: int) -> None:
+ monkeypatch.setattr(
+ rs,
+ "get_chat_attachment_limits",
+ lambda: rs.ChatAttachmentLimits(
+ max_file_bytes=max_file,
+ max_total_bytes=max_total,
+ max_chars_per_doc=100_000,
+ max_chars_total=100_000,
+ ),
+ )
+
+ def record(name: str, payload: bytes) -> dict:
+ return {
+ "type": "file",
+ "filename": name,
+ "base64": base64.b64encode(payload).decode(),
+ "mime_type": "",
+ "url": "",
+ }
+
+ # Per-file cap: 5 bytes, generous total.
+ set_limits(max_file=5, max_total=1000)
+ doc_texts, updated = extract_documents_from_records(
+ [record("big.txt", b"0123456789"), record("ok.txt", b"hello")]
+ )
+ assert "per-file limit" in doc_texts[0]
+ assert doc_texts[1] == "[File: ok.txt]\nhello"
+ assert updated[1]["extracted_chars"] == 5
+
+ # Per-turn total: 8 bytes — the second 5-byte file blows it.
+ set_limits(max_file=1000, max_total=8)
+ doc_texts, _ = extract_documents_from_records(
+ [record("a.txt", b"hello"), record("b.txt", b"world")]
+ )
+ assert doc_texts[0] == "[File: a.txt]\nhello"
+ assert "quota exceeded" in doc_texts[1]
+
+ def test_char_budget_comes_from_settings_layer(self, monkeypatch) -> None:
+ from deeptutor.services.config import runtime_settings as rs
+
+ monkeypatch.setattr(
+ rs,
+ "get_chat_attachment_limits",
+ lambda: rs.ChatAttachmentLimits(
+ max_file_bytes=10 * 1024 * 1024,
+ max_total_bytes=25 * 1024 * 1024,
+ max_chars_per_doc=100_000,
+ max_chars_total=10,
+ ),
+ )
+ records = [
+ {
+ "type": "file",
+ "filename": "long.txt",
+ "base64": base64.b64encode(b"a" * 40).decode(),
+ "mime_type": "",
+ "url": "",
+ }
+ ]
+ doc_texts, updated = extract_documents_from_records(records)
+ assert "truncated" in doc_texts[0]
+ assert updated[0]["extracted_chars"] <= 10 + len(
+ "... (truncated, 40 chars total; turn quota hit)"
+ )
diff --git a/web/app/(utility)/settings/attachments/page.tsx b/web/app/(utility)/settings/attachments/page.tsx
new file mode 100644
index 000000000..77afc5ab4
--- /dev/null
+++ b/web/app/(utility)/settings/attachments/page.tsx
@@ -0,0 +1,269 @@
+"use client";
+
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { Loader2 } from "lucide-react";
+import { useTranslation } from "react-i18next";
+
+import {
+ SettingRow,
+ SettingSection,
+ SettingsPageHeader,
+ inputClass,
+} from "@/components/settings/shared";
+import { useSettings } from "@/components/settings/SettingsContext";
+import { apiFetch, apiUrl } from "@/lib/api";
+
+type AttachmentSettings = {
+ max_file_mb: number;
+ max_total_mb: number;
+ max_chars_per_doc: number;
+ max_chars_total: number;
+};
+
+type AttachmentSettingsPayload = {
+ settings: AttachmentSettings;
+ effective: {
+ max_file_bytes: number;
+ max_total_bytes: number;
+ max_chars_per_doc: number;
+ max_chars_total: number;
+ ws_max_size: number;
+ };
+ bounds: {
+ max_file_mb: [number, number];
+ max_total_mb: [number, number];
+ chars: [number, number];
+ };
+ restart_required_for_larger_uploads: boolean;
+};
+
+function normalizeDraft(payload: AttachmentSettingsPayload): AttachmentSettings {
+ return { ...payload.settings };
+}
+
+export default function AttachmentSettingsPage() {
+ const { t } = useTranslation();
+ const { registerExtension } = useSettings();
+ const [payload, setPayload] = useState<AttachmentSettingsPayload | null>(
+ null,
+ );
+ const [draft, setDraft] = useState<AttachmentSettings | null>(null);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState<string | null>(null);
+
+ useEffect(() => {
+ let cancelled = false;
+ async function load() {
+ setLoading(true);
+ setError(null);
+ try {
+ const response = await apiFetch(
+ apiUrl("/api/v1/settings/chat-attachments"),
+ );
+ const data = (await response.json().catch(() => ({}))) as
+ | AttachmentSettingsPayload
+ | { detail?: string };
+ if (!response.ok) {
+ throw new Error(
+ "detail" in data && data.detail
+ ? data.detail
+ : t("Failed to load attachment settings."),
+ );
+ }
+ if (cancelled) return;
+ const next = data as AttachmentSettingsPayload;
+ setPayload(next);
+ setDraft(normalizeDraft(next));
+ } catch (err) {
+ if (!cancelled) {
+ setError(err instanceof Error ? err.message : String(err));
+ }
+ } finally {
+ if (!cancelled) setLoading(false);
+ }
+ }
+ load();
+ return () => {
+ cancelled = true;
+ };
+ }, [t]);
+
+ const dirty = useMemo(() => {
+ if (!payload || !draft) return false;
+ const current = normalizeDraft(payload);
+ return (
+ current.max_file_mb !== draft.max_file_mb ||
+ current.max_total_mb !== draft.max_total_mb ||
+ current.max_chars_per_doc !== draft.max_chars_per_doc ||
+ current.max_chars_total !== draft.max_chars_total
+ );
+ }, [draft, payload]);
+
+ // Flush through the global Apply (top toolbar) instead of a local button.
+ const draftRef = useRef(draft);
+ draftRef.current = draft;
+ const save = useCallback(async () => {
+ const current = draftRef.current;
+ if (!current) return;
+ setError(null);
+ try {
+ const response = await apiFetch(
+ apiUrl("/api/v1/settings/chat-attachments"),
+ {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(current),
+ },
+ );
+ const data = (await response.json().catch(() => ({}))) as
+ | AttachmentSettingsPayload
+ | { detail?: string };
+ if (!response.ok) {
+ throw new Error(
+ "detail" in data && data.detail
+ ? String(data.detail)
+ : t("Failed to save attachment settings."),
+ );
+ }
+ const next = data as AttachmentSettingsPayload;
+ setPayload(next);
+ setDraft(normalizeDraft(next));
+ } catch (err) {
+ setError(err instanceof Error ? err.message : String(err));
+ }
+ }, [t]);
+
+ useEffect(() => {
+ registerExtension("chat-attachments", { dirty, save });
+ return () => registerExtension("chat-attachments", null);
+ }, [dirty, save, registerExtension]);
+
+ const setField = (field: keyof AttachmentSettings) => (value: number) =>
+ setDraft((current) =>
+ current ? { ...current, [field]: value } : current,
+ );
+
+ const bounds = payload?.bounds;
+
+ return (
+ <div>
+ <SettingsPageHeader
+ title={t("Attachments")}
+ description={t(
+ "Upload caps and extraction budgets for files attached in chat — shared by the main chat, books, quiz follow-ups, and partners.",
+ )}
+ />
+
+ {loading && (
+ <div className="flex items-center gap-2 text-[13px] text-[var(--muted-foreground)]">
+ <Loader2 className="h-4 w-4 animate-spin" />
+ {t("Loading attachment settings...")}
+ </div>
+ )}
+
+ {!loading && error && (
+ <div className="mb-5 rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-[13px] text-red-600 dark:text-red-300">
+ {error}
+ </div>
+ )}
+
+ {!loading && payload && draft && (
+ <>
+ <SettingSection
+ title={t("Size limits")}
+ description={t(
+ "Caps are enforced when a file is picked and again server-side on every message. Lower limits apply immediately; raising them needs a backend restart so larger uploads fit through the WebSocket transport.",
+ )}
+ >
+ <SettingRow
+ title={t("Max file size (MB)")}
+ description={t("Largest single file the composer accepts.")}
+ control={
+ <input
+ className={`${inputClass} w-28`}
+ type="number"
+ min={bounds?.max_file_mb[0] ?? 1}
+ max={bounds?.max_file_mb[1] ?? 1024}
+ value={draft.max_file_mb}
+ onChange={(event) =>
+ setField("max_file_mb")(Number(event.target.value))
+ }
+ />
+ }
+ />
+ <SettingRow
+ title={t("Max total per message (MB)")}
+ description={t(
+ "Combined size of all attachments on a single message. Never below the per-file cap.",
+ )}
+ control={
+ <input
+ className={`${inputClass} w-28`}
+ type="number"
+ min={bounds?.max_total_mb[0] ?? 1}
+ max={bounds?.max_total_mb[1] ?? 2048}
+ value={draft.max_total_mb}
+ onChange={(event) =>
+ setField("max_total_mb")(Number(event.target.value))
+ }
+ />
+ }
+ />
+ </SettingSection>
+
+ <SettingSection
+ title={t("Extraction budgets")}
+ description={t(
+ "Documents are converted to text and inlined into the model context. These budgets bound how much text a single file and a whole message may contribute — raise them for large documents, at the cost of context window and tokens.",
+ )}
+ >
+ <SettingRow
+ title={t("Max characters per document")}
+ description={t(
+ "Text extracted beyond this from one file is truncated with a notice.",
+ )}
+ control={
+ <input
+ className={`${inputClass} w-36`}
+ type="number"
+ min={bounds?.chars[0] ?? 10000}
+ max={bounds?.chars[1] ?? 5000000}
+ step={10000}
+ value={draft.max_chars_per_doc}
+ onChange={(event) =>
+ setField("max_chars_per_doc")(Number(event.target.value))
+ }
+ />
+ }
+ />
+ <SettingRow
+ title={t("Max characters per message")}
+ description={t(
+ "Total extracted text across all documents on one message.",
+ )}
+ control={
+ <input
+ className={`${inputClass} w-36`}
+ type="number"
+ min={bounds?.chars[0] ?? 10000}
+ max={bounds?.chars[1] ?? 5000000}
+ step={10000}
+ value={draft.max_chars_total}
+ onChange={(event) =>
+ setField("max_chars_total")(Number(event.target.value))
+ }
+ />
+ }
+ />
+ </SettingSection>
+
+ <p className="mt-2 text-[11.5px] leading-relaxed text-[var(--muted-foreground)]">
+ {t(
+ "Note: images are sent to the model provider as-is — provider-side size limits still apply regardless of these caps.",
+ )}
+ </p>
+ </>
+ )}
+ </div>
+ );
+}
diff --git a/web/app/(workspace)/book/components/BookChatPanel.tsx b/web/app/(workspace)/book/components/BookChatPanel.tsx
index 01128c2ff..846690763 100644
--- a/web/app/(workspace)/book/components/BookChatPanel.tsx
+++ b/web/app/(workspace)/book/components/BookChatPanel.tsx
@@ -23,9 +23,8 @@ import {
ATTACHMENT_ACCEPT,
classifyFile,
formatBytes,
- MAX_ATTACHMENT_BYTES,
- MAX_TOTAL_ATTACHMENT_BYTES,
} from "@/lib/doc-attachments";
+import { useAttachmentLimits } from "@/lib/attachment-limits";
import {
extractBase64FromDataUrl,
readFileAsDataUrl,
@@ -109,6 +108,7 @@ export default function BookChatPanel({
const [busy, setBusy] = useState(false);
const [width, setWidth] = useState(360);
const [attachments, setAttachments] = useState<PendingAttachment[]>([]);
+ const attachmentLimits = useAttachmentLimits();
const [attachmentError, setAttachmentError] = useState<string | null>(null);
const sessionIdRef = useRef<string | null>(null);
const clientRef = useRef<UnifiedWSClient | null>(null);
@@ -323,13 +323,13 @@ export default function BookChatPanel({
setAttachmentError(t("Unsupported file type."));
continue;
}
- if (file.size > MAX_ATTACHMENT_BYTES) {
+ if (file.size > attachmentLimits.maxFileBytes) {
setAttachmentError(
t("File is too large ({{size}}).", { size: formatBytes(file.size) }),
);
continue;
}
- if (nextTotal + file.size > MAX_TOTAL_ATTACHMENT_BYTES) {
+ if (nextTotal + file.size > attachmentLimits.maxTotalBytes) {
setAttachmentError(t("Attachments exceed the total upload limit."));
continue;
}
diff --git a/web/app/(workspace)/home/[[...sessionId]]/page.tsx b/web/app/(workspace)/home/[[...sessionId]]/page.tsx
index a14a490f3..dd259fe98 100644
--- a/web/app/(workspace)/home/[[...sessionId]]/page.tsx
+++ b/web/app/(workspace)/home/[[...sessionId]]/page.tsx
@@ -66,12 +66,8 @@ import {
extractBase64FromDataUrl,
readFileAsDataUrl,
} from "@/lib/file-attachments";
-import {
- classifyFile,
- isSvgFilename,
- MAX_ATTACHMENT_BYTES,
- MAX_TOTAL_ATTACHMENT_BYTES,
-} from "@/lib/doc-attachments";
+import { classifyFile, isSvgFilename } from "@/lib/doc-attachments";
+import { useAttachmentLimits } from "@/lib/attachment-limits";
import { useChatAutoScroll } from "@/hooks/useChatAutoScroll";
import { useMeasuredHeight } from "@/hooks/useMeasuredHeight";
import {
@@ -367,6 +363,7 @@ export default function ChatPage() {
null,
);
const [attachments, setAttachments] = useState<PendingAttachment[]>([]);
+ const attachmentLimits = useAttachmentLimits();
const [dragging, setDragging] = useState(false);
const [attachmentError, setAttachmentError] = useState<string | null>(null);
const [previewSource, setPreviewSource] = useState<FilePreviewSource | null>(
@@ -1181,11 +1178,11 @@ export default function ChatPage() {
rejected.push({ name: f.name, reason: "unsupported" });
continue;
}
- if (f.size > MAX_ATTACHMENT_BYTES) {
+ if (f.size > attachmentLimits.maxFileBytes) {
rejected.push({ name: f.name, reason: "too_large" });
continue;
}
- if (runningTotal + f.size > MAX_TOTAL_ATTACHMENT_BYTES) {
+ if (runningTotal + f.size > attachmentLimits.maxTotalBytes) {
rejected.push({ name: f.name, reason: "quota" });
break;
}
@@ -1206,7 +1203,7 @@ export default function ChatPage() {
}
return accepted;
},
- [attachments, showAttachmentError, t],
+ [attachments, attachmentLimits, showAttachmentError, t],
);
const handlePaste = useCallback(
diff --git a/web/components/partners/PartnerComposer.tsx b/web/components/partners/PartnerComposer.tsx
index 2aa51d68f..57ddc8513 100644
--- a/web/components/partners/PartnerComposer.tsx
+++ b/web/components/partners/PartnerComposer.tsx
@@ -16,13 +16,12 @@ import {
} from "@/lib/partners-api";
import {
ATTACHMENT_ACCEPT,
- MAX_ATTACHMENT_BYTES,
- MAX_TOTAL_ATTACHMENT_BYTES,
classifyFile,
docIconFor,
formatBytes,
isSvgFilename,
} from "@/lib/doc-attachments";
+import { useAttachmentLimits } from "@/lib/attachment-limits";
import {
extractBase64FromDataUrl,
readFileAsDataUrl,
@@ -57,6 +56,7 @@ export const PartnerComposer = memo(function PartnerComposer({
const [attachments, setAttachments] = useState<PartnerPendingAttachment[]>(
[],
);
+ const attachmentLimits = useAttachmentLimits();
const [dragging, setDragging] = useState(false);
const [attachmentError, setAttachmentError] = useState<string | null>(null);
const [commands, setCommands] = useState<PartnerCommandInfo[]>([]);
@@ -133,11 +133,11 @@ export const PartnerComposer = memo(function PartnerComposer({
rejected.push({ name: file.name, reason: "unsupported" });
continue;
}
- if (file.size > MAX_ATTACHMENT_BYTES) {
+ if (file.size > attachmentLimits.maxFileBytes) {
rejected.push({ name: file.name, reason: "too_large" });
continue;
}
- if (runningTotal + file.size > MAX_TOTAL_ATTACHMENT_BYTES) {
+ if (runningTotal + file.size > attachmentLimits.maxTotalBytes) {
rejected.push({ name: file.name, reason: "quota" });
break;
}
@@ -162,7 +162,7 @@ export const PartnerComposer = memo(function PartnerComposer({
return accepted;
},
- [attachments, showAttachmentError, t],
+ [attachments, attachmentLimits, showAttachmentError, t],
);
const fileToAttachment = useCallback(
diff --git a/web/components/quiz/FollowupChatComposer.tsx b/web/components/quiz/FollowupChatComposer.tsx
index d616d19bc..3cd057bd7 100644
--- a/web/components/quiz/FollowupChatComposer.tsx
+++ b/web/components/quiz/FollowupChatComposer.tsx
@@ -23,12 +23,8 @@ import {
useQuizFollowupController,
} from "@/context/QuizFollowupContext";
import { buildQuizFollowupConfig } from "@/lib/quiz-types";
-import {
- classifyFile,
- isSvgFilename,
- MAX_ATTACHMENT_BYTES,
- MAX_TOTAL_ATTACHMENT_BYTES,
-} from "@/lib/doc-attachments";
+import { classifyFile, isSvgFilename } from "@/lib/doc-attachments";
+import { useAttachmentLimits } from "@/lib/attachment-limits";
import {
extractBase64FromDataUrl,
readFileAsDataUrl,
@@ -111,6 +107,7 @@ function FollowupChatComposerImpl({ context }: FollowupChatComposerProps) {
// ── Composer local state ──────────────────────────────────────
const [attachments, setAttachments] = useState<PendingAttachment[]>([]);
+ const attachmentLimits = useAttachmentLimits();
const [attachmentError, setAttachmentError] = useState<string | null>(null);
const attachmentErrorTimer = useRef<ReturnType<typeof setTimeout> | null>(
null,
@@ -281,11 +278,11 @@ function FollowupChatComposerImpl({ context }: FollowupChatComposerProps) {
rejected.push({ name: f.name, reason: "unsupported" });
continue;
}
- if (f.size > MAX_ATTACHMENT_BYTES) {
+ if (f.size > attachmentLimits.maxFileBytes) {
rejected.push({ name: f.name, reason: "too_large" });
continue;
}
- if (runningTotal + f.size > MAX_TOTAL_ATTACHMENT_BYTES) {
+ if (runningTotal + f.size > attachmentLimits.maxTotalBytes) {
rejected.push({ name: f.name, reason: "quota" });
break;
}
@@ -306,7 +303,7 @@ function FollowupChatComposerImpl({ context }: FollowupChatComposerProps) {
}
return accepted;
},
- [attachments, showAttachmentError, t],
+ [attachments, attachmentLimits, showAttachmentError, t],
);
const handleAddFiles = useCallback(
diff --git a/web/lib/attachment-limits.ts b/web/lib/attachment-limits.ts
new file mode 100644
index 000000000..b6f38bd14
--- /dev/null
+++ b/web/lib/attachment-limits.ts
@@ -0,0 +1,92 @@
+"use client";
+
+import { useEffect, useState } from "react";
+
+import { apiFetch, apiUrl } from "@/lib/api";
+import {
+ DEFAULT_MAX_ATTACHMENT_BYTES,
+ DEFAULT_MAX_TOTAL_ATTACHMENT_BYTES,
+} from "@/lib/doc-attachments";
+
+/**
+ * Runtime chat-attachment limits.
+ *
+ * The caps live in `data/user/settings/system.json` (editable at
+ * /settings/attachments) and are enforced server-side on every message; the
+ * composer mirrors them client-side so oversized picks are rejected before a
+ * pointless upload. Defaults apply until the fetch resolves — they match the
+ * backend defaults, so a pre-hydration pick is never gated more loosely than
+ * the server would allow.
+ */
+export interface AttachmentLimits {
+ /** Per-file cap, bytes. */
+ maxFileBytes: number;
+ /** Per-message total cap, bytes. */
+ maxTotalBytes: number;
+}
+
+export const DEFAULT_ATTACHMENT_LIMITS: AttachmentLimits = {
+ maxFileBytes: DEFAULT_MAX_ATTACHMENT_BYTES,
+ maxTotalBytes: DEFAULT_MAX_TOTAL_ATTACHMENT_BYTES,
+};
+
+// Several composers (home chat, book panel, quiz follow-up, partners) mount
+// at once; share one fetch and keep the resolved value for the session.
+// Admin edits land on the next full page load, which is fine for a policy
+// that changes rarely.
+let cached: AttachmentLimits | null = null;
+let inflight: Promise<AttachmentLimits> | null = null;
+
+function loadAttachmentLimits(): Promise<AttachmentLimits> {
+ if (cached) return Promise.resolve(cached);
+ if (!inflight) {
+ inflight = apiFetch(apiUrl("/api/v1/settings/chat-attachments"))
+ .then(async (response) => {
+ if (!response.ok) return DEFAULT_ATTACHMENT_LIMITS;
+ const data = (await response.json().catch(() => null)) as {
+ effective?: { max_file_bytes?: number; max_total_bytes?: number };
+ } | null;
+ const fileBytes = Number(data?.effective?.max_file_bytes);
+ const totalBytes = Number(data?.effective?.max_total_bytes);
+ if (!Number.isFinite(fileBytes) || fileBytes <= 0) {
+ return DEFAULT_ATTACHMENT_LIMITS;
+ }
+ cached = {
+ maxFileBytes: fileBytes,
+ maxTotalBytes:
+ Number.isFinite(totalBytes) && totalBytes >= fileBytes
+ ? totalBytes
+ : fileBytes,
+ };
+ return cached;
+ })
+ .catch(() => DEFAULT_ATTACHMENT_LIMITS)
+ .finally(() => {
+ inflight = null;
+ });
+ }
+ return inflight;
+}
+
+/**
+ * Effective attachment limits for composer gating. Returns the built-in
+ * defaults synchronously, then re-renders once the backend policy arrives.
+ */
+export function useAttachmentLimits(): AttachmentLimits {
+ const [limits, setLimits] = useState<AttachmentLimits>(
+ () => cached ?? DEFAULT_ATTACHMENT_LIMITS,
+ );
+
+ useEffect(() => {
+ if (cached) return;
+ let alive = true;
+ loadAttachmentLimits().then((value) => {
+ if (alive) setLimits(value);
+ });
+ return () => {
+ alive = false;
+ };
+ }, []);
+
+ return limits;
+}
diff --git a/web/lib/doc-attachments.ts b/web/lib/doc-attachments.ts
index 06146b998..5c24d4b89 100644
--- a/web/lib/doc-attachments.ts
+++ b/web/lib/doc-attachments.ts
@@ -194,8 +194,14 @@ export const SUPPORTED_DOC_MIMES = new Set<string>([
"application/toml",
]);
-export const MAX_ATTACHMENT_BYTES = 10 * 1024 * 1024;
-export const MAX_TOTAL_ATTACHMENT_BYTES = 25 * 1024 * 1024;
+/**
+ * Built-in attachment caps. These are compile-time fallbacks only — the
+ * effective limits come from the backend policy (see
+ * `lib/attachment-limits.ts` / the /settings/attachments page) and must match
+ * the backend defaults in `deeptutor/services/config/runtime_settings.py`.
+ */
+export const DEFAULT_MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024;
+export const DEFAULT_MAX_TOTAL_ATTACHMENT_BYTES = 25 * 1024 * 1024;
/**
* `accept` attribute for the chat composer's file picker. Mirrors the formats
diff --git a/web/lib/settings-nav.ts b/web/lib/settings-nav.ts
index e274be0bc..b1a464255 100644
--- a/web/lib/settings-nav.ts
+++ b/web/lib/settings-nav.ts
@@ -15,6 +15,7 @@ import {
Mic,
Network,
Palette,
+ Paperclip,
Plug,
Search,
SlidersHorizontal,
@@ -186,6 +187,18 @@ const CHAT_CHILDREN: SettingsLeaf[] = [
icon: SlidersHorizontal,
tile: "bg-lime-500/10 text-lime-600 dark:text-lime-400",
},
+ {
+ key: "attachments",
+ href: "/settings/attachments",
+ label: { zh: "附件", en: "Attachments" },
+ blurb: {
+ zh: "聊天附件的大小上限与文本提取预算。",
+ en: "Upload caps and extraction budgets for chat attachments.",
+ },
+ icon: Paperclip,
+ tile: "bg-teal-500/10 text-teal-600 dark:text-teal-400",
+ adminOnly: true,
+ },
];
const AGENT_CHILDREN: SettingsLeaf[] = [
@@ -256,8 +269,8 @@ export const SETTINGS_CATEGORIES: SettingsCategory[] = [
key: "chat",
label: { zh: "聊天", en: "Chat" },
blurb: {
- zh: "工具、MCP 服务器与能力",
- en: "Tools, MCP servers, and capabilities",
+ zh: "工具、MCP 服务器、能力与附件",
+ en: "Tools, MCP servers, capabilities, and attachments",
},
icon: MessagesSquare,
href: "/settings/chat",
@@ -314,6 +327,7 @@ const STORAGE_PATHS: Record<string, string> = {
"/settings/video": "data/user/settings/model_catalog.json",
"/settings/document-parsing": "data/user/settings/document_parsing.json",
"/settings/tools": "data/user/settings/interface.json",
+ "/settings/attachments": "data/user/settings/system.json",
"/settings/mcp": "data/user/settings/mcp.json",
"/settings/capabilities": "data/user/settings/main.yaml · agents.yaml",
"/settings/memory": "data/user/settings/main.yaml",
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index dcf85baa7..c8fd78b71 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -1873,6 +1873,24 @@
"Failed to load network settings.": "Failed to load network settings.",
"Failed to save network settings.": "Failed to save network settings.",
"Network settings saved. Restart DeepTutor to apply them.": "Network settings saved. Restart DeepTutor to apply them.",
+ "Attachments": "Attachments",
+ "Upload caps and extraction budgets for files attached in chat — shared by the main chat, books, quiz follow-ups, and partners.": "Upload caps and extraction budgets for files attached in chat — shared by the main chat, books, quiz follow-ups, and partners.",
+ "Loading attachment settings...": "Loading attachment settings...",
+ "Failed to load attachment settings.": "Failed to load attachment settings.",
+ "Failed to save attachment settings.": "Failed to save attachment settings.",
+ "Size limits": "Size limits",
+ "Caps are enforced when a file is picked and again server-side on every message. Lower limits apply immediately; raising them needs a backend restart so larger uploads fit through the WebSocket transport.": "Caps are enforced when a file is picked and again server-side on every message. Lower limits apply immediately; raising them needs a backend restart so larger uploads fit through the WebSocket transport.",
+ "Max file size (MB)": "Max file size (MB)",
+ "Largest single file the composer accepts.": "Largest single file the composer accepts.",
+ "Max total per message (MB)": "Max total per message (MB)",
+ "Combined size of all attachments on a single message. Never below the per-file cap.": "Combined size of all attachments on a single message. Never below the per-file cap.",
+ "Extraction budgets": "Extraction budgets",
+ "Documents are converted to text and inlined into the model context. These budgets bound how much text a single file and a whole message may contribute — raise them for large documents, at the cost of context window and tokens.": "Documents are converted to text and inlined into the model context. These budgets bound how much text a single file and a whole message may contribute — raise them for large documents, at the cost of context window and tokens.",
+ "Max characters per document": "Max characters per document",
+ "Text extracted beyond this from one file is truncated with a notice.": "Text extracted beyond this from one file is truncated with a notice.",
+ "Max characters per message": "Max characters per message",
+ "Total extracted text across all documents on one message.": "Total extracted text across all documents on one message.",
+ "Note: images are sent to the model provider as-is — provider-side size limits still apply regardless of these caps.": "Note: images are sent to the model provider as-is — provider-side size limits still apply regardless of these caps.",
"Browser API": "Browser API",
"CORS mode": "CORS mode",
"Permissive until auth is enabled": "Permissive until auth is enabled",
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index 197ebf92f..30bd34872 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -1247,6 +1247,24 @@
"Failed to load network settings.": "加载网络设置失败。",
"Failed to save network settings.": "保存网络设置失败。",
"Network settings saved. Restart DeepTutor to apply them.": "网络设置已保存。重启 DeepTutor 后生效。",
+ "Attachments": "附件",
+ "Upload caps and extraction budgets for files attached in chat — shared by the main chat, books, quiz follow-ups, and partners.": "聊天附件的上传上限与文本提取预算——主聊天、书籍、错题跟练与伙伴共用。",
+ "Loading attachment settings...": "正在加载附件设置...",
+ "Failed to load attachment settings.": "加载附件设置失败。",
+ "Failed to save attachment settings.": "保存附件设置失败。",
+ "Size limits": "大小限制",
+ "Caps are enforced when a file is picked and again server-side on every message. Lower limits apply immediately; raising them needs a backend restart so larger uploads fit through the WebSocket transport.": "选择文件时与服务端每条消息都会校验上限。调低立即生效;调高需重启后端,让更大的上传能通过 WebSocket 传输。",
+ "Max file size (MB)": "单文件上限(MB)",
+ "Largest single file the composer accepts.": "输入框接受的最大单个文件。",
+ "Max total per message (MB)": "单条消息总上限(MB)",
+ "Combined size of all attachments on a single message. Never below the per-file cap.": "一条消息所有附件的合计大小,不会低于单文件上限。",
+ "Extraction budgets": "提取预算",
+ "Documents are converted to text and inlined into the model context. These budgets bound how much text a single file and a whole message may contribute — raise them for large documents, at the cost of context window and tokens.": "文档会被转成文本并内联进模型上下文。这两个预算限制单个文件与整条消息可注入的文本量——处理大文档时可调高,代价是占用更多上下文窗口与 token。",
+ "Max characters per document": "单文档字符上限",
+ "Text extracted beyond this from one file is truncated with a notice.": "单个文件提取超出部分将被截断并附截断提示。",
+ "Max characters per message": "单条消息字符上限",
+ "Total extracted text across all documents on one message.": "一条消息所有文档提取文本的合计上限。",
+ "Note: images are sent to the model provider as-is — provider-side size limits still apply regardless of these caps.": "注意:图片会原样发送给模型供应商,供应商自身的大小限制不受此处设置影响。",
"Browser API": "浏览器 API",
"CORS mode": "CORS 模式",
"Permissive until auth is enabled": "未启用认证时自动放行",
diff --git a/web/tests/doc-attachments.test.ts b/web/tests/doc-attachments.test.ts
index 46c96a714..59d1117f7 100644
--- a/web/tests/doc-attachments.test.ts
+++ b/web/tests/doc-attachments.test.ts
@@ -6,7 +6,7 @@ import {
docIconFor,
formatBytes,
isSvgFilename,
- MAX_ATTACHMENT_BYTES,
+ DEFAULT_MAX_ATTACHMENT_BYTES,
} from "../lib/doc-attachments";
function makeFile(name: string, type = "", size = 0): File {
@@ -124,6 +124,6 @@ test("docIconFor: fallback for unknown extension", () => {
// Limits sanity check -------------------------------------------------------
-test("MAX_ATTACHMENT_BYTES is 10 MB", () => {
- assert.equal(MAX_ATTACHMENT_BYTES, 10 * 1024 * 1024);
+test("DEFAULT_MAX_ATTACHMENT_BYTES is 20 MB", () => {
+ assert.equal(DEFAULT_MAX_ATTACHMENT_BYTES, 20 * 1024 * 1024);
});