Skip to content

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

release: v1.1.1 — universal answer-now, co-writer scroll sync, notebook system unification, tutorbot config refactor

Bingxi Zhao (Frank)e8aa57d73716
diff --git a/README.md b/README.md
index 3b0f2c94f..0aca7d3f1 100644
--- a/README.md
+++ b/README.md
@@ -26,6 +26,8 @@
### 📦 Releases
+> **[2026.4.17]** [v1.1.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.1) — Universal "Answer now" escape hatch across every capability, Co-Writer resizable split with line-anchored scroll sync, Save-to-Notebook message-selection mode, real notebook system adoption across Knowledge/Guide/Save flows, unified collapsible settings panel, dedicated streaming Stop button, TutorBot config manager refactor with atomic writes, light/Snow theme refresh, and expanded test suite.
+
> **[2026.4.15]** [v1.1.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0) — LaTeX block math parsing overhaul, LLM diagnostic probe agents.yaml configuration, extra headers forwarding in LLM factory, SaveToNotebookModal UUID fix, Docker + local LLM guidance, and expanded test suite.
> **[2026.4.14]** [v1.1.0-beta](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0-beta) — URL-based chat routing with bookmarkable sessions, Snow theme, WebSocket heartbeat & auto-reconnect with resume, ChatComposer performance optimization, embedding provider registry overhaul, Serper search provider, streaming idle timeout, and expanded test suite.
diff --git a/assets/releases/ver1-1-1.md b/assets/releases/ver1-1-1.md
new file mode 100644
index 000000000..9391206ff
--- /dev/null
+++ b/assets/releases/ver1-1-1.md
@@ -0,0 +1,52 @@
+# DeepTutor v1.1.1 Release Notes
+
+**Release Date:** 2026.04.17
+
+## Highlights
+
+### Universal "Answer Now" Escape Hatch
+Promoted "Answer now" from a chat-only affordance to a universal interrupt that works across every capability. The orchestrator now inspects `config_overrides["answer_now_context"]` and re-routes the turn to `chat._stage_answer_now` regardless of the originally selected capability, so users can short-circuit `deep_solve`, `deep_research`, `math_animator`, etc. and synthesize a final answer from whatever partial trace has streamed so far. The frontend mirrors the contract by forcing the follow-up turn to `chat` and packaging the in-flight assistant content + events into the snapshot. A new `AnswerNowRow` component renders the action inline below the streaming trace panel and disables itself after a single click to prevent duplicate cancel/restart races.
+
+### Co-Writer — Resizable Split & Line-Anchored Scroll Sync
+The Co-Writer page picked up a draggable splitter between the editor and preview panes (with a persisted ratio in `localStorage`) and a true bidirectional scroll-sync that survives soft-wrapped lines. Each preview block now carries a `data-source-line` attribute pointing back at its starting line in the markdown source (provided by remark's AST positions); on the editor side a hidden mirror element mimics the textarea's wrap geometry so we can read the real pixel-`y` of every source line. With both sides expressed as pixel coordinates the sync becomes a single piecewise-linear interpolation in either direction, with a per-source-line cache that invalidates only when the content or wrap width changes.
+
+### Save-to-Notebook — Message Selection Mode
+`SaveToNotebookModal` now accepts an optional `messages` prop that flips the modal into "selection mode": the user picks exactly which user/assistant turns to include, and the transcript + `userQuery` shipped to the backend are rebuilt from the selected subset. Quick presets ("Select all", "Last turn", "Last 3 turns") and an auto-derived title that tracks the first selected user message keep the flow fast for the common cases. The modal also now uses `Check` / `MessageSquare` / `User` icons to distinguish roles at a glance, and reports loading state for the notebook list separately from the save spinner.
+
+### Real Notebook System Adoption Across the Stack
+Migrated every remaining Notebook surface off the legacy quiz-category API onto the real `/api/v1/notebook/*` endpoints. A new `web/lib/notebook-api.ts` block exports typed helpers — `listNotebooks`, `getNotebook`, `createNotebook`, `updateNotebook`, `deleteNotebook`, `deleteNotebookRecord` — alongside the preserved quiz-only helpers. The Knowledge → Notebooks tab, the Guide page's notebook reference picker (`useNotebookSelection`), and the Save-to-Notebook modal all now resolve UUIDs end-to-end, so records saved from Co-Writer, Chat, or Guided Learning are immediately discoverable as references everywhere.
+
+### Unified Collapsible Settings Panel
+Extracted the collapsible "Settings" section that previously only existed in `ResearchConfigPanel` into a shared `CollapsibleConfigSection` component. The Quiz, Math Animator, and Visualize panels now share the exact same chevron + summary header, and each form ships a `summarizeXxxConfig` helper so the collapsed state shows a meaningful one-liner (e.g. *Custom · 5q · Hard · MCQ* or *Mimic · paper.pdf · max 10*). The chat page now keeps a single `panelCollapsed` state for whichever capability is active, auto-expands on capability switch, and auto-collapses after sending a message so the composer stays compact during conversation.
+
+### Streaming Stop Button & Composer Polish
+Replaced the spinner-inside-the-Send-button with a dedicated **Stop** button that appears in place of Send while a turn is streaming. A faint ring slowly rotates around the rim to signal "still working — click to cancel", with a white square front-and-center as the click target. The header above the messages (capability label + Save / New chat buttons) is now always rendered, and the messages container picks up a soft mask gradient at the top and bottom so streaming content fades in/out instead of clipping at the scroll edge. In Deep Research mode, sources moved into a dropdown with a compact summary line of the active picks, matching the pattern used by the tool selector.
+
+### TutorBot Config Manager Refactor
+Rewrote `TutorBotManager`'s config persistence into a small public API (`load_bot_config`, `save_bot_config`, `merge_bot_config`) with three meaningful improvements: writes are now **atomic** (write-temp + `Path.replace`) so a killed process never leaves a half-written `config.yaml`; merges have **explicit-clear semantics** — `None` means "leave as-is", an empty string or empty dict is an intentional clear — so clients can deliberately wipe a description or channels list; and the API endpoint forwards only `model_dump(exclude_unset=True)` so omitted fields fall through to the on-disk value. New regression tests cover the atomic-write contract, the corrupt-yaml fallback, and the four merge-semantics cases.
+
+### Markdown Renderer Refinements
+The `MarkdownRenderer` family gained a `trackSourceLines` prop that propagates `data-source-line` attributes through every block element (headings, lists, paragraphs, etc.) and bypasses the line-shifting normalization passes (`processMarkdownContent`, `normalizeMarkdownForDisplay`) so AST positions stay faithful for editor/preview sync consumers. `RichCodeBlock` now skips `react-syntax-highlighter` entirely for unlabeled / `text` / `plaintext` fences (eliminating Prism "unknown language" warnings) and renders them as a tidy plain-monospace block. Mermaid detection was also extended to recognize editor.md style ` ```flow `, ` ```seq `, and ` ```sequence ` fences that get rewritten to mermaid by the preprocessor.
+
+### Theme & Guide UI Refresh
+Tightened the default light and Snow themes with deeper foregrounds, warmer borders, and a slightly more saturated `--primary` (`#B0501E`) for better legibility against the new card surfaces. The Guided Learning page (`/guide`) was migrated off hardcoded `slate-*` / `indigo-*` palettes onto the design tokens (`var(--card)`, `var(--primary)`, `var(--muted-foreground)`, etc.) so it now respects the theme switcher. `HistorySessionPicker` got the same treatment, plus a fix for session timestamps that were being treated as milliseconds instead of seconds (which produced 1970 dates).
+
+### System Message Rendering Fix
+Backend system messages (e.g. quiz follow-up grounding context written by the turn runtime) are now filtered out at the `UnifiedChatContext.hydrateMessages` boundary and again defensively in `ChatMessageList`, so they never surface as ghost chat bubbles in the UI while still flowing into the LLM context as intended.
+
+### Bug Fixes
+- **TutorBot channel config wiped on every server restart (#332)** — `create_and_start_bot` was constructing a fresh `BotConfig` with empty defaults on every call, which `_save_bot_config` then persisted over the existing `config.yaml`, wiping user-configured channels (e.g. Telegram). The endpoint now loads the existing config first and overlays only client-supplied fields.
+- **`selective_access_log` middleware crash on every non-200 response (#334 / #335)** — the middleware passed four args to uvicorn's `AccessFormatter` which expects five (omitting `http_version`), raising `ValueError: not enough values to unpack` on every error response. Now reads `http_version` from the ASGI scope with a `1.1` fallback.
+- **15 npm security vulnerabilities (#330)** — bumped `jspdf` 4.0.0 → 4.2.0 (9 CVEs incl. critical PDF injection), `next` 16.1.1 → 16.2.3 (8 CVEs incl. HTTP smuggling, CSRF bypass), `mermaid` 11.12.2 → 11.14.0, and the matching `eslint-config-next`. `npm audit fix` swept up the indirect chain (`flatted`, `lodash-es`, `minimatch`, `picomatch`, `dompurify`, `ajv`, `brace-expansion`). End state: 0 vulnerabilities, no breaking changes.
+- **`.env.example_CN`** — removed an accidental `// README` suffix on the provider-list comment.
+
+### Test Suite Expansion
+Added a new `tests/services/tutorbot/test_manager_config.py` module covering load/save round-trips, the corrupt-yaml fallback, atomic temp-file writes, failure-recovery after a mid-write `OSError`, and all four `merge_bot_config` semantics (no existing config, omitted-field passthrough, `None`-as-not-provided, and empty-value-as-explicit-clear). Extended `tests/api/test_tutorbot_router.py` with the explicit-clear test class, and added an orchestrator routing test (`test_answer_now_context_reroutes_to_chat`) that asserts a `deep_solve` turn is intercepted and handed to the chat capability when `answer_now_context` is present.
+
+## Community Contributions
+
+- **@srinivasrk** — Resolve 15 npm security vulnerabilities (#330)
+- **@srinivasrk** — Preserve existing TutorBot config when starting bot via API (#332)
+- **@kagura-agent** — Fix `selective_access_log` middleware unpack crash (#335)
+
+**Full Changelog**: https://github.com/HKUDS/DeepTutor/compare/v1.1.0...v1.1.1
diff --git a/deeptutor/api/routers/tutorbot.py b/deeptutor/api/routers/tutorbot.py
index b8df6940e..58f0b4369 100644
--- a/deeptutor/api/routers/tutorbot.py
+++ b/deeptutor/api/routers/tutorbot.py
@@ -11,7 +11,6 @@ from fastapi import APIRouter, HTTPException, WebSocket, WebSocketDisconnect
from pydantic import BaseModel
from deeptutor.services.tutorbot import get_tutorbot_manager
-from deeptutor.services.tutorbot.manager import BotConfig
logger = logging.getLogger(__name__)
router = APIRouter()
@@ -20,9 +19,9 @@ router = APIRouter()
class CreateBotRequest(BaseModel):
bot_id: str
name: str | None = None
- description: str = ""
- persona: str = ""
- channels: dict = {}
+ description: str | None = None
+ persona: str | None = None
+ channels: dict | None = None
model: str | None = None
@@ -103,15 +102,12 @@ async def recent_bots(limit: int = 3):
@router.post("")
async def create_and_start_bot(payload: CreateBotRequest):
mgr = get_tutorbot_manager()
- # Load existing config from disk first so fields like channels are preserved
- existing = mgr._load_bot_config(payload.bot_id)
- config = BotConfig(
- name=payload.name or (existing.name if existing else payload.bot_id),
- description=payload.description or (existing.description if existing else ""),
- persona=payload.persona or (existing.persona if existing else ""),
- channels=payload.channels if payload.channels else (existing.channels if existing else {}),
- model=payload.model or (existing.model if existing else None),
- )
+ # Only fields the client actually sent are forwarded as overrides; this lets
+ # users explicitly clear values (e.g. ``description=""``) while *omitted*
+ # fields fall back to the on-disk config — preventing the historical bug
+ # where each restart wiped out user-configured channels.
+ overrides = payload.model_dump(exclude_unset=True, exclude={"bot_id"})
+ config = mgr.merge_bot_config(payload.bot_id, overrides)
try:
instance = await mgr.start_bot(payload.bot_id, config)
except RuntimeError as e:
@@ -125,7 +121,7 @@ async def get_bot(bot_id: str):
instance = mgr.get_bot(bot_id)
if instance:
return instance.to_dict()
- cfg = mgr._load_bot_config(bot_id)
+ cfg = mgr.load_bot_config(bot_id)
if cfg:
return {
"bot_id": bot_id, "name": cfg.name, "description": cfg.description,
@@ -169,7 +165,7 @@ async def update_bot(bot_id: str, payload: UpdateBotRequest):
if payload.model is not None:
instance.config.model = payload.model
- mgr._save_bot_config(bot_id, instance.config)
+ mgr.save_bot_config(bot_id, instance.config)
return instance.to_dict()
diff --git a/deeptutor/capabilities/request_contracts.py b/deeptutor/capabilities/request_contracts.py
index 8b1774975..ef615ed3f 100644
--- a/deeptutor/capabilities/request_contracts.py
+++ b/deeptutor/capabilities/request_contracts.py
@@ -15,7 +15,15 @@ from deeptutor.agents.research.request_config import (
validate_research_request_config,
)
-_RUNTIME_ONLY_KEYS = {"_persist_user_message", "followup_question_context"}
+_RUNTIME_ONLY_KEYS = {
+ "_persist_user_message",
+ "followup_question_context",
+ # "answer_now" is a universal escape hatch: the orchestrator re-routes
+ # any capability to chat when this is present. It is never declared on
+ # any per-capability ``RequestConfig`` schema, so we strip it before
+ # pydantic validation and re-attach it on the runtime-only side.
+ "answer_now_context",
+}
class ChatRequestConfig(BaseModel):
diff --git a/deeptutor/runtime/orchestrator.py b/deeptutor/runtime/orchestrator.py
index 9843e7dea..d5a4039b0 100644
--- a/deeptutor/runtime/orchestrator.py
+++ b/deeptutor/runtime/orchestrator.py
@@ -43,7 +43,18 @@ class ChatOrchestrator:
if not context.session_id:
context.session_id = str(uuid.uuid4())
- cap_name = context.active_capability or "chat"
+ # "Answer now" is a universal escape hatch: the user is impatient and
+ # wants the system to synthesize a final reply from the partial trace
+ # captured so far. The chat capability owns this synthesis path
+ # (see _stage_answer_now), so we re-route here regardless of the
+ # original capability so this works uniformly across deep_solve,
+ # deep_research, math_animator, etc.
+ if isinstance(context.config_overrides, dict) and context.config_overrides.get(
+ "answer_now_context"
+ ):
+ cap_name = "chat"
+ else:
+ cap_name = context.active_capability or "chat"
capability = self._cap_registry.get(cap_name)
if capability is None:
diff --git a/deeptutor/services/session/turn_runtime.py b/deeptutor/services/session/turn_runtime.py
index f90cd5251..c928251ff 100644
--- a/deeptutor/services/session/turn_runtime.py
+++ b/deeptutor/services/session/turn_runtime.py
@@ -206,7 +206,11 @@ class TurnRuntimeManager:
async def start_turn(self, payload: dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any]]:
capability = str(payload.get("capability") or "chat")
raw_config = dict(payload.get("config", {}) or {})
- runtime_only_keys = ("_persist_user_message", "followup_question_context")
+ runtime_only_keys = (
+ "_persist_user_message",
+ "followup_question_context",
+ "answer_now_context",
+ )
runtime_only_config = {
key: raw_config.pop(key)
for key in runtime_only_keys
diff --git a/deeptutor/services/tutorbot/manager.py b/deeptutor/services/tutorbot/manager.py
index 5ee73fb92..f239e3702 100644
--- a/deeptutor/services/tutorbot/manager.py
+++ b/deeptutor/services/tutorbot/manager.py
@@ -185,7 +185,11 @@ class TutorBotManager:
# ── Config persistence ────────────────────────────────────────
- def _load_bot_config(self, bot_id: str) -> BotConfig | None:
+ # Field names from BotConfig that are persisted via merge.
+ _MERGEABLE_FIELDS = ("name", "description", "persona", "channels", "model")
+
+ def load_bot_config(self, bot_id: str) -> BotConfig | None:
+ """Read the on-disk ``config.yaml`` for a bot, or ``None`` if missing."""
path = self._bot_dir(bot_id) / "config.yaml"
if not path.exists():
return None
@@ -202,7 +206,12 @@ class TutorBotManager:
logger.exception("Failed to load bot config %s", bot_id)
return None
- def _save_bot_config(self, bot_id: str, config: BotConfig, *, auto_start: bool = True) -> None:
+ def save_bot_config(self, bot_id: str, config: BotConfig, *, auto_start: bool = True) -> None:
+ """Persist ``config`` to ``config.yaml`` atomically (write-temp + replace).
+
+ Atomic write ensures we never leave a half-written/corrupt yaml on disk
+ if the process is killed mid-write.
+ """
bot_dir = self._bot_dir(bot_id)
bot_dir.mkdir(parents=True, exist_ok=True)
path = bot_dir / "config.yaml"
@@ -215,7 +224,27 @@ class TutorBotManager:
}
if config.model:
data["model"] = config.model
- path.write_text(yaml.dump(data, allow_unicode=True), encoding="utf-8")
+
+ tmp_path = path.with_suffix(path.suffix + ".tmp")
+ tmp_path.write_text(yaml.dump(data, allow_unicode=True), encoding="utf-8")
+ tmp_path.replace(path)
+
+ def merge_bot_config(self, bot_id: str, overrides: dict[str, Any]) -> BotConfig:
+ """Build a ``BotConfig`` by overlaying ``overrides`` onto the on-disk config.
+
+ Keys in ``overrides`` whose value is ``None`` are treated as "not provided"
+ and fall through to the existing on-disk value (or to the dataclass default
+ for a brand-new bot). Empty strings / empty dicts are intentional clears
+ and DO override — callers must use ``None`` to mean "leave as-is".
+
+ Unknown keys are silently ignored.
+ """
+ existing = self.load_bot_config(bot_id)
+ base = existing or BotConfig(name=bot_id)
+ for key in self._MERGEABLE_FIELDS:
+ if key in overrides and overrides[key] is not None:
+ setattr(base, key, overrides[key])
+ return base
# ── Bot lifecycle ─────────────────────────────────────────────
@@ -227,10 +256,10 @@ class TutorBotManager:
self._ensure_bot_dirs(bot_id)
if config is None:
- config = self._load_bot_config(bot_id)
+ config = self.load_bot_config(bot_id)
if config is None:
config = BotConfig(name=bot_id)
- self._save_bot_config(bot_id, config)
+ self.save_bot_config(bot_id, config)
from deeptutor.tutorbot.providers.deeptutor_adapter import create_deeptutor_provider
from deeptutor.tutorbot.bus.queue import MessageBus
@@ -335,7 +364,7 @@ class TutorBotManager:
await heartbeat.start()
self._bots[bot_id] = instance
- self._save_bot_config(bot_id, config)
+ self.save_bot_config(bot_id, config)
logger.info("TutorBot '%s' started (workspace=%s)", bot_id, workspace)
return instance
@@ -419,7 +448,7 @@ class TutorBotManager:
except Exception:
pass
- self._save_bot_config(bot_id, instance.config, auto_start=False)
+ self.save_bot_config(bot_id, instance.config, auto_start=False)
del self._bots[bot_id]
logger.info("TutorBot '%s' stopped", bot_id)
return True
@@ -450,7 +479,7 @@ class TutorBotManager:
if bid in result:
continue
self._maybe_migrate_legacy(bid)
- cfg = self._load_bot_config(bid)
+ cfg = self.load_bot_config(bid)
result[bid] = {
"bot_id": bid,
"name": cfg.name if cfg else bid,
@@ -528,7 +557,7 @@ class TutorBotManager:
except Exception:
pass
- cfg = self._load_bot_config(bid)
+ cfg = self.load_bot_config(bid)
instance = self._bots.get(bid)
bot_activity.append((mtime, bid, {
"bot_id": bid,
diff --git a/tests/api/test_tutorbot_router.py b/tests/api/test_tutorbot_router.py
index 144a7ae2a..5ccb75d63 100644
--- a/tests/api/test_tutorbot_router.py
+++ b/tests/api/test_tutorbot_router.py
@@ -3,7 +3,7 @@
from __future__ import annotations
import importlib
-from pathlib import Path
+from typing import Any
from unittest.mock import MagicMock
import pytest
@@ -24,26 +24,45 @@ pytestmark = pytest.mark.skipif(
# Helpers
# ---------------------------------------------------------------------------
-def _make_fake_manager(existing_channels: dict | None = None):
+def _make_fake_manager(existing: dict | None = None):
"""Return a (manager, saved) pair.
- manager — fake TutorBotManager whose start_bot captures the final config
- saved — dict populated with {"config": BotConfig} after start_bot runs
+ Parameters
+ ----------
+ existing
+ If ``None``, simulates "no on-disk config". Otherwise, treated as a
+ partial override on top of sensible defaults to construct an existing
+ ``BotConfig``.
"""
from deeptutor.services.tutorbot.manager import BotConfig
saved: dict = {}
- class FakeManager:
- def _load_bot_config(self, bot_id: str) -> BotConfig | None:
- if existing_channels is not None:
- return BotConfig(
- name=bot_id,
- description="existing description",
- persona="existing persona",
- channels=existing_channels,
- )
+ def _build_existing() -> BotConfig | None:
+ if existing is None:
return None
+ defaults: dict[str, Any] = {
+ "name": "existing-name",
+ "description": "existing description",
+ "persona": "existing persona",
+ "channels": {},
+ "model": None,
+ }
+ defaults.update(existing)
+ return BotConfig(**defaults)
+
+ class FakeManager:
+ _MERGEABLE_FIELDS = ("name", "description", "persona", "channels", "model")
+
+ def load_bot_config(self, bot_id: str) -> BotConfig | None:
+ return _build_existing()
+
+ def merge_bot_config(self, bot_id: str, overrides: dict[str, Any]) -> BotConfig:
+ base = self.load_bot_config(bot_id) or BotConfig(name=bot_id)
+ for key in self._MERGEABLE_FIELDS:
+ if key in overrides and overrides[key] is not None:
+ setattr(base, key, overrides[key])
+ return base
async def start_bot(self, bot_id: str, config: BotConfig):
saved["config"] = config
@@ -59,9 +78,9 @@ def _make_fake_manager(existing_channels: dict | None = None):
return FakeManager(), saved
-def _make_client(monkeypatch, existing_channels: dict | None = None):
+def _make_client(monkeypatch, existing: dict | None = None):
"""Build a TestClient with the tutorbot router and a patched manager."""
- manager, saved = _make_fake_manager(existing_channels)
+ manager, saved = _make_fake_manager(existing)
tutorbot_router_mod = importlib.import_module("deeptutor.api.routers.tutorbot")
monkeypatch.setattr(tutorbot_router_mod, "get_tutorbot_manager", lambda: manager)
@@ -76,7 +95,7 @@ def _make_client(monkeypatch, existing_channels: dict | None = None):
# ---------------------------------------------------------------------------
class TestCreateBotPreservesExistingConfig:
- """Regression tests for the config-wipe bug.
+ """Regression tests for the config-wipe bug (issue #331 / PR #332).
When the web UI starts a bot via POST /api/v1/tutorbot without supplying
channel config, the previously saved channels must be kept — not wiped.
@@ -91,7 +110,9 @@ class TestCreateBotPreservesExistingConfig:
"allow_from": ["999"],
}
}
- client, saved = _make_client(monkeypatch, existing_channels=existing_channels)
+ client, saved = _make_client(
+ monkeypatch, existing={"channels": existing_channels}
+ )
resp = client.post("/api/v1/tutorbot", json={"bot_id": "my-bot"})
@@ -105,7 +126,9 @@ class TestCreateBotPreservesExistingConfig:
existing_channels = {"telegram": {"enabled": True, "token": "old"}}
new_channels = {"slack": {"enabled": True, "token": "new-slack-token"}}
- client, saved = _make_client(monkeypatch, existing_channels=existing_channels)
+ client, saved = _make_client(
+ monkeypatch, existing={"channels": existing_channels}
+ )
resp = client.post(
"/api/v1/tutorbot",
@@ -119,7 +142,7 @@ class TestCreateBotPreservesExistingConfig:
def test_fresh_bot_with_no_existing_config(self, monkeypatch):
"""A brand-new bot with no existing config should start without error."""
- client, saved = _make_client(monkeypatch, existing_channels=None)
+ client, saved = _make_client(monkeypatch, existing=None)
resp = client.post(
"/api/v1/tutorbot",
@@ -132,11 +155,99 @@ class TestCreateBotPreservesExistingConfig:
def test_existing_name_and_persona_preserved(self, monkeypatch):
"""Other fields (description, persona) from disk must also survive when not in payload."""
- existing_channels = {"telegram": {"enabled": True, "token": "tok"}}
- client, saved = _make_client(monkeypatch, existing_channels=existing_channels)
+ client, saved = _make_client(
+ monkeypatch, existing={"channels": {"telegram": {"enabled": True}}}
+ )
resp = client.post("/api/v1/tutorbot", json={"bot_id": "my-bot"})
assert resp.status_code == 200
assert saved["config"].description == "existing description"
assert saved["config"].persona == "existing persona"
+
+
+class TestCreateBotExplicitClearSemantics:
+ """Verify the new "explicit empty value clears the field" semantics.
+
+ The original PR #332 fix used ``payload.x or existing.x`` which silently
+ swallowed empty strings / empty dicts. Following the upgrade to
+ ``model_dump(exclude_unset=True)`` + ``is not None`` merging, clients
+ can now intentionally clear fields by sending an explicit empty value.
+ """
+
+ def test_explicit_empty_channels_clears_existing(self, monkeypatch):
+ """Sending ``channels: {}`` explicitly must clear the disk channels."""
+ client, saved = _make_client(
+ monkeypatch, existing={"channels": {"telegram": {"enabled": True}}}
+ )
+
+ resp = client.post(
+ "/api/v1/tutorbot",
+ json={"bot_id": "my-bot", "channels": {}},
+ )
+
+ assert resp.status_code == 200
+ assert saved["config"].channels == {}, (
+ "Explicit empty channels dict should clear existing channels, "
+ "not silently fall back to the disk value"
+ )
+
+ def test_explicit_empty_description_clears_existing(self, monkeypatch):
+ """Sending ``description: ''`` explicitly must clear the existing description."""
+ client, saved = _make_client(
+ monkeypatch,
+ existing={"description": "old long description"},
+ )
+
+ resp = client.post(
+ "/api/v1/tutorbot",
+ json={"bot_id": "my-bot", "description": ""},
+ )
+
+ assert resp.status_code == 200
+ assert saved["config"].description == ""
+
+ def test_omitted_fields_fall_back_to_existing(self, monkeypatch):
+ """Fields entirely missing from the payload must inherit from disk."""
+ client, saved = _make_client(
+ monkeypatch,
+ existing={
+ "name": "Disk Name",
+ "description": "Disk Desc",
+ "persona": "Disk Persona",
+ "channels": {"telegram": {"enabled": True}},
+ "model": "gpt-4o",
+ },
+ )
+
+ resp = client.post(
+ "/api/v1/tutorbot",
+ json={"bot_id": "my-bot", "persona": "New Persona"},
+ )
+
+ assert resp.status_code == 200
+ cfg = saved["config"]
+ assert cfg.name == "Disk Name"
+ assert cfg.description == "Disk Desc"
+ assert cfg.persona == "New Persona"
+ assert cfg.channels == {"telegram": {"enabled": True}}
+ assert cfg.model == "gpt-4o"
+
+ def test_null_field_in_payload_falls_back_to_existing(self, monkeypatch):
+ """Explicit ``null`` for an optional field is treated as 'not provided'.
+
+ This guarantees a frontend that sends ``{description: null}`` (e.g.
+ because a form input was unset) does NOT clobber the existing value —
+ only an explicit empty string does that.
+ """
+ client, saved = _make_client(
+ monkeypatch, existing={"description": "Disk Desc"}
+ )
+
+ resp = client.post(
+ "/api/v1/tutorbot",
+ json={"bot_id": "my-bot", "description": None},
+ )
+
+ assert resp.status_code == 200
+ assert saved["config"].description == "Disk Desc"
diff --git a/tests/runtime/test_orchestrator.py b/tests/runtime/test_orchestrator.py
index e1e6832e6..47240dbff 100644
--- a/tests/runtime/test_orchestrator.py
+++ b/tests/runtime/test_orchestrator.py
@@ -115,6 +115,42 @@ class TestOrchestratorRouting:
assert len(content_events) == 1
assert content_events[0].content == "hello"
+ @pytest.mark.asyncio
+ async def test_answer_now_context_reroutes_to_chat(self) -> None:
+ """When ``answer_now_context`` is set, the orchestrator must route
+ to the ``chat`` capability so the answer-now synthesizer handles the
+ turn regardless of the original ``active_capability``."""
+ chat_cap = _EchoCapability()
+ chat_cap.manifest = CapabilityManifest(
+ name="chat", description="Chat capability.", stages=["responding"]
+ )
+ deep_cap = _EchoCapability()
+ deep_cap.manifest = CapabilityManifest(
+ name="deep_solve", description="Deep solve.", stages=["responding"]
+ )
+ deep_cap.run = AsyncMock(side_effect=AssertionError("deep_solve must not run"))
+ orch = _make_orchestrator({"chat": chat_cap, "deep_solve": deep_cap})
+
+ ctx = UnifiedContext(
+ user_message="ping",
+ active_capability="deep_solve",
+ config_overrides={
+ "answer_now_context": {
+ "original_user_message": "ping",
+ "partial_response": "",
+ "events": [],
+ }
+ },
+ )
+ events: list[StreamEvent] = []
+ async for event in orch.handle(ctx):
+ events.append(event)
+
+ content_events = [e for e in events if e.type == StreamEventType.CONTENT]
+ assert len(content_events) == 1
+ assert content_events[0].content == "ping"
+ deep_cap.run.assert_not_called()
+
@pytest.mark.asyncio
async def test_unknown_capability_yields_error(self) -> None:
orch = _make_orchestrator({})
diff --git a/tests/services/tutorbot/__init__.py b/tests/services/tutorbot/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/tests/services/tutorbot/test_manager_config.py b/tests/services/tutorbot/test_manager_config.py
new file mode 100644
index 000000000..d51656948
--- /dev/null
+++ b/tests/services/tutorbot/test_manager_config.py
@@ -0,0 +1,179 @@
+"""Unit tests for TutorBotManager config persistence & merging."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+import yaml
+
+from deeptutor.services.tutorbot.manager import BotConfig, TutorBotManager
+
+
+def manager(tmp_path: Path) -> TutorBotManager:
+ """Return a TutorBotManager whose data dir is a fresh temp directory."""
+ mgr = TutorBotManager()
+ # Replace the path service with a stub so reads/writes stay sandboxed.
+ mgr._path_service = SimpleNamespace( # type: ignore[assignment]
+ project_root=tmp_path,
+ get_memory_dir=lambda: tmp_path / "memory",
+ )
+ return mgr
+
+
+# ---------------------------------------------------------------------------
+# load_bot_config / save_bot_config
+# ---------------------------------------------------------------------------
+
+class TestLoadAndSave:
+ def test_load_returns_none_when_no_config(self, manager: TutorBotManager):
+ assert manager.load_bot_config("nonexistent") is None
+
+ def test_save_then_load_roundtrip(self, manager: TutorBotManager):
+ cfg = BotConfig(
+ name="My Bot",
+ description="d",
+ persona="p",
+ channels={"telegram": {"enabled": True, "token": "tok"}},
+ model="gpt-4o",
+ )
+ manager.save_bot_config("bot-a", cfg)
+
+ loaded = manager.load_bot_config("bot-a")
+ assert loaded == cfg
+
+ def test_load_corrupt_yaml_returns_none(self, manager: TutorBotManager):
+ bot_dir = manager._bot_dir("bad-bot")
+ bot_dir.mkdir(parents=True, exist_ok=True)
+ (bot_dir / "config.yaml").write_text(": not :: valid : yaml ::", encoding="utf-8")
+
+ assert manager.load_bot_config("bad-bot") is None
+
+
+# ---------------------------------------------------------------------------
+# Atomic write
+# ---------------------------------------------------------------------------
+
+class TestAtomicWrite:
+ def test_save_uses_temp_file_and_replace(self, manager: TutorBotManager, monkeypatch):
+ """save_bot_config must write to a temp file then atomically replace.
+
+ We assert that:
+ 1. A ``.tmp`` file is created during the write.
+ 2. After the call, only the final ``config.yaml`` exists (the temp
+ file has been moved into place via Path.replace).
+ """
+ cfg = BotConfig(name="atomic", channels={"telegram": {"enabled": True}})
+
+ observed: dict[str, list[Path]] = {"tmp_writes": [], "replaces": []}
+ original_write_text = Path.write_text
+ original_replace = Path.replace
+
+ def tracked_write_text(self_path: Path, *args, **kwargs):
+ if self_path.suffix == ".tmp":
+ observed["tmp_writes"].append(Path(self_path))
+ return original_write_text(self_path, *args, **kwargs)
+
+ def tracked_replace(self_path: Path, target: Path):
+ observed["replaces"].append((Path(self_path), Path(target)))
+ return original_replace(self_path, target)
+
+ monkeypatch.setattr(Path, "write_text", tracked_write_text)
+ monkeypatch.setattr(Path, "replace", tracked_replace)
+
+ manager.save_bot_config("atomic-bot", cfg)
+
+ bot_dir = manager._bot_dir("atomic-bot")
+ final = bot_dir / "config.yaml"
+ tmp = bot_dir / "config.yaml.tmp"
+
+ assert final.exists()
+ assert not tmp.exists(), "Temp file must be moved away after save"
+ assert observed["tmp_writes"], "Expected a write to a .tmp file"
+ assert observed["replaces"], "Expected Path.replace to be called"
+
+ def test_save_does_not_corrupt_existing_on_failed_write(
+ self, manager: TutorBotManager, monkeypatch
+ ):
+ """If the write fails midway, the previous on-disk config must survive."""
+ good_cfg = BotConfig(name="orig", channels={"telegram": {"enabled": True}})
+ manager.save_bot_config("safe-bot", good_cfg)
+
+ original_write_text = Path.write_text
+
+ def boom(self_path: Path, *args, **kwargs):
+ if self_path.suffix == ".tmp":
+ raise OSError("disk full")
+ return original_write_text(self_path, *args, **kwargs)
+
+ monkeypatch.setattr(Path, "write_text", boom)
+
+ with pytest.raises(OSError):
+ manager.save_bot_config("safe-bot", BotConfig(name="new", channels={}))
+
+ # Original config must still be intact.
+ loaded = manager.load_bot_config("safe-bot")
+ assert loaded == good_cfg
+
+
+# ---------------------------------------------------------------------------
+# merge_bot_config
+# ---------------------------------------------------------------------------
+
+class TestMergeBotConfig:
+ def test_merge_with_no_existing_uses_defaults(self, manager: TutorBotManager):
+ merged = manager.merge_bot_config("brand-new", {"name": "X"})
+ assert merged.name == "X"
+ assert merged.description == ""
+ assert merged.channels == {}
+
+ def test_merge_keeps_existing_when_overrides_omit_field(self, manager: TutorBotManager):
+ manager.save_bot_config(
+ "bot-1",
+ BotConfig(name="Disk", description="dd", channels={"telegram": {}}),
+ )
+
+ merged = manager.merge_bot_config("bot-1", {"persona": "p"})
+ assert merged.name == "Disk"
+ assert merged.description == "dd"
+ assert merged.persona == "p"
+ assert merged.channels == {"telegram": {}}
+
+ def test_merge_treats_none_as_not_provided(self, manager: TutorBotManager):
+ manager.save_bot_config(
+ "bot-2",
+ BotConfig(name="Disk", description="dd"),
+ )
+
+ merged = manager.merge_bot_config(
+ "bot-2", {"description": None, "name": "New"}
+ )
+ assert merged.name == "New"
+ assert merged.description == "dd"
+
+ def test_merge_treats_empty_string_and_dict_as_explicit_clear(
+ self, manager: TutorBotManager
+ ):
+ manager.save_bot_config(
+ "bot-3",
+ BotConfig(
+ name="Disk",
+ description="dd",
+ channels={"telegram": {"enabled": True}},
+ ),
+ )
+
+ merged = manager.merge_bot_config(
+ "bot-3", {"description": "", "channels": {}}
+ )
+ assert merged.description == ""
+ assert merged.channels == {}
+
+ def test_merge_ignores_unknown_keys(self, manager: TutorBotManager):
+ merged = manager.merge_bot_config(
+ "bot-4", {"name": "X", "unknown_field": "boom"}
+ )
+ assert merged.name == "X"
+ assert not hasattr(merged, "unknown_field")
diff --git a/web/.env.local b/web/.env.local
index 0b6543af3..2b04f3785 100644
--- a/web/.env.local
+++ b/web/.env.local
@@ -1,11 +1,2 @@
-# ============================================
-# Auto-generated by start_web.py
-# ============================================
-# This file is automatically updated based on config/main.yaml
-# and environment variables (NEXT_PUBLIC_API_BASE, NEXT_PUBLIC_API_BASE_EXTERNAL)
-#
-# To configure for remote access, set in your .env file:
-# NEXT_PUBLIC_API_BASE=http://your-server-ip:8001
-# ============================================
-
+# Auto-generated by start_web.py — do not edit manually
NEXT_PUBLIC_API_BASE=http://localhost:8001
diff --git a/web/app/(utility)/knowledge/page.tsx b/web/app/(utility)/knowledge/page.tsx
index f35cb8a9d..099de534b 100644
--- a/web/app/(utility)/knowledge/page.tsx
+++ b/web/app/(utility)/knowledge/page.tsx
@@ -45,6 +45,10 @@ import {
updateNotebookEntry,
deleteNotebookEntry,
removeEntryFromCategory,
+ listNotebooks,
+ getNotebook,
+ createNotebook,
+ deleteNotebook,
type NotebookEntry,
type NotebookCategory,
} from "@/lib/notebook-api";
@@ -397,10 +401,10 @@ function KnowledgePageContent() {
setLoading(true);
setPageError(null);
try {
- const [kbs, providerData, cats] = await Promise.all([
+ const [kbs, providerData, nbs] = await Promise.all([
listKnowledgeBases(),
listRagProviders(),
- listCategories(),
+ listNotebooks(),
]);
setKnowledgeBases(kbs);
setProviders(
@@ -414,10 +418,14 @@ function KnowledgePageContent() {
},
],
);
- const nextNotebooks: NotebookInfo[] = cats.map((c) => ({
- id: String(c.id),
- name: c.name,
- record_count: c.entry_count ?? 0,
+ const nextNotebooks: NotebookInfo[] = nbs.map((nb) => ({
+ id: String(nb.id),
+ name: nb.name,
+ description: nb.description,
+ record_count: nb.record_count ?? 0,
+ color: nb.color,
+ icon: nb.icon,
+ updated_at: nb.updated_at,
}));
setNotebooks(nextNotebooks);
if (!selectedNotebookId && nextNotebooks.length > 0) {
@@ -648,36 +656,52 @@ function KnowledgePageContent() {
await loadAll();
};
- const createNotebook = async () => {
+ const handleCreateNotebook = async () => {
if (!newNotebookName.trim()) return;
- await createCategory(newNotebookName.trim());
+ await createNotebook({
+ name: newNotebookName.trim(),
+ description: newNotebookDescription.trim(),
+ });
setNewNotebookName("");
setNewNotebookDescription("");
await loadAll();
};
+ const handleDeleteNotebook = async (notebookId: string, name: string) => {
+ if (!window.confirm(t('Delete notebook "{{name}}"?', { name }))) return;
+ await deleteNotebook(notebookId);
+ if (selectedNotebookId === notebookId) {
+ setSelectedNotebookId(null);
+ setSelectedNotebook(null);
+ }
+ await loadAll();
+ };
+
const loadNotebookDetail = async (notebookId: string) => {
setSelectedNotebookId(notebookId);
setExpandedRecordId(null);
setLoadingNotebookDetail(true);
try {
const info = notebooks.find((n) => n.id === notebookId);
- const data = await listNotebookEntries({ category_id: Number(notebookId) });
- const records: NotebookRecord[] = (data.items || []).map((e) => ({
- id: String(e.id),
- type: e.question_type,
- title: e.question,
- summary: e.explanation,
- user_query: e.question,
- output: e.correct_answer,
- created_at: e.created_at,
+ const data = await getNotebook(notebookId);
+ const records: NotebookRecord[] = (data.records || []).map((rec) => ({
+ id: String(rec.id),
+ type: String(rec.type),
+ title: rec.title,
+ summary: rec.summary,
+ user_query: rec.user_query,
+ output: rec.output,
+ metadata: rec.metadata,
+ created_at: rec.created_at,
}));
setSelectedNotebook({
id: notebookId,
- name: info?.name ?? "",
- description: info?.description,
- record_count: data.total,
- color: info?.color,
+ name: data.name ?? info?.name ?? "",
+ description: data.description ?? info?.description,
+ record_count: records.length,
+ color: data.color ?? info?.color,
+ icon: data.icon ?? info?.icon,
+ updated_at: data.updated_at ?? info?.updated_at,
records,
});
} catch {
@@ -1152,7 +1176,7 @@ function KnowledgePageContent() {
className="rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--foreground)]/25"
/>
<button
- onClick={createNotebook}
+ onClick={() => void handleCreateNotebook()}
disabled={!newNotebookName.trim()}
className="rounded-lg bg-[var(--primary)] px-3.5 py-2 text-[13px] font-medium text-[var(--primary-foreground)] disabled:cursor-not-allowed disabled:opacity-40"
>
@@ -1175,36 +1199,52 @@ function KnowledgePageContent() {
{notebooks.map((notebook) => {
const active = selectedNotebookId === notebook.id;
return (
- <button
+ <div
key={notebook.id}
- onClick={() => void loadNotebookDetail(notebook.id)}
- className={`w-full rounded-xl border p-4 text-left transition-all ${
+ className={`group relative w-full rounded-xl border p-4 text-left transition-all ${
active
- ? "border-indigo-200 bg-indigo-50/70 shadow-[0_8px_24px_rgba(99,102,241,0.08)] dark:border-indigo-800 dark:bg-indigo-950/25"
- : "border-[var(--border)] bg-[var(--background)] hover:border-[var(--foreground)]/12 hover:bg-[var(--muted)]/18"
+ ? "border-[var(--primary)]/40 bg-[var(--primary)]/8 shadow-sm"
+ : "border-[var(--border)] bg-[var(--background)] hover:border-[var(--foreground)]/15 hover:bg-[var(--muted)]/30"
}`}
>
- <div className="flex items-start gap-3">
- <div
- className="mt-1 h-3 w-3 rounded-full"
- style={{ backgroundColor: notebook.color || "#6366f1" }}
- />
- <div className="min-w-0 flex-1">
- <div className="text-[14px] font-semibold text-[var(--foreground)]">
- {notebook.name}
- </div>
- {notebook.description && (
- <p className="mt-1 line-clamp-2 text-[12px] leading-relaxed text-[var(--muted-foreground)]">
- {notebook.description}
- </p>
- )}
- <div className="mt-3 flex items-center justify-between text-[11px] text-[var(--muted-foreground)]">
- <span>{notebook.record_count ?? 0} {t("records")}</span>
- <span>{notebook.updated_at ? formatTimestamp(notebook.updated_at) : ""}</span>
+ <button
+ type="button"
+ onClick={() => void loadNotebookDetail(notebook.id)}
+ className="block w-full text-left"
+ >
+ <div className="flex items-start gap-3">
+ <div
+ className="mt-1 h-3 w-3 rounded-full"
+ style={{ backgroundColor: notebook.color || "var(--primary)" }}
+ />
+ <div className="min-w-0 flex-1">
+ <div className="text-[14px] font-semibold text-[var(--foreground)]">
+ {notebook.name}
+ </div>
+ {notebook.description && (
+ <p className="mt-1 line-clamp-2 text-[12px] leading-relaxed text-[var(--muted-foreground)]">
+ {notebook.description}
+ </p>
+ )}
+ <div className="mt-3 flex items-center justify-between text-[11px] text-[var(--muted-foreground)]">
+ <span>{notebook.record_count ?? 0} {t("records")}</span>
+ <span>{notebook.updated_at ? formatTimestamp(notebook.updated_at) : ""}</span>
+ </div>
</div>
</div>
- </div>
- </button>
+ </button>
+ <button
+ type="button"
+ onClick={(event) => {
+ event.stopPropagation();
+ void handleDeleteNotebook(notebook.id, notebook.name);
+ }}
+ title={t("Delete")}
+ className="absolute right-2 top-2 rounded-md p-1.5 text-[var(--muted-foreground)] opacity-0 transition-opacity hover:bg-[var(--destructive)]/10 hover:text-[var(--destructive)] group-hover:opacity-100"
+ >
+ <Trash2 size={13} />
+ </button>
+ </div>
);
})}
@@ -1226,7 +1266,7 @@ function KnowledgePageContent() {
<div className="flex items-center gap-2.5">
<div
className="h-2.5 w-2.5 rounded-full"
- style={{ backgroundColor: selectedNotebook.color || "#6366f1" }}
+ style={{ backgroundColor: selectedNotebook.color || "var(--primary)" }}
/>
<h3 className="text-[15px] font-semibold text-[var(--foreground)]">
{selectedNotebook.name}
@@ -1294,7 +1334,7 @@ function KnowledgePageContent() {
{canOpenSession && (
<button
onClick={() => openNotebookRecord(record)}
- className="mb-3 inline-flex items-center gap-2 rounded-lg border border-[var(--border)] bg-[var(--background)] px-3.5 py-2 text-[12px] font-medium text-[var(--foreground)] transition-colors hover:border-indigo-300 hover:bg-indigo-50 hover:text-indigo-700 dark:hover:border-indigo-700 dark:hover:bg-indigo-950/30 dark:hover:text-indigo-300"
+ className="mb-3 inline-flex items-center gap-2 rounded-lg border border-[var(--border)] bg-[var(--background)] px-3.5 py-2 text-[12px] font-medium text-[var(--foreground)] transition-colors hover:border-[var(--primary)]/40 hover:bg-[var(--primary)]/8 hover:text-[var(--primary)]"
>
<ExternalLink size={13} />
{sessionLabel}
diff --git a/web/app/(workspace)/chat/[[...sessionId]]/page.tsx b/web/app/(workspace)/chat/[[...sessionId]]/page.tsx
index 9a10e123b..c28e62c58 100644
--- a/web/app/(workspace)/chat/[[...sessionId]]/page.tsx
+++ b/web/app/(workspace)/chat/[[...sessionId]]/page.tsx
@@ -223,7 +223,10 @@ export default function ChatPage() {
...DEFAULT_VISUALIZE_CONFIG,
});
const [researchConfig, setResearchConfig] = useState<DeepResearchFormConfig>(createEmptyResearchConfig());
- const [researchPanelCollapsed, setResearchPanelCollapsed] = useState(true);
+ // Unified collapse state for the capability-specific config panel
+ // (Quiz / Math Animator / Visualize / Deep Research). Default collapsed so
+ // a fresh Chat / Deep Solve session has the shortest possible composer.
+ const [panelCollapsed, setPanelCollapsed] = useState(true);
const [showSaveModal, setShowSaveModal] = useState(false);
const [showNotebookPicker, setShowNotebookPicker] = useState(false);
const [showHistoryPicker, setShowHistoryPicker] = useState(false);
@@ -282,38 +285,36 @@ export default function ChatPage() {
() => selectedHistorySessions.map((session) => session.sessionId),
[selectedHistorySessions],
);
+ const chatSaveMessages = useMemo(
+ () =>
+ state.messages.map((msg) => ({
+ role: msg.role,
+ content: msg.content,
+ capability: msg.capability,
+ })),
+ [state.messages],
+ );
const chatSavePayload = useMemo(() => {
if (!state.messages.length) return null;
const title =
state.messages.find((msg) => msg.role === "user")?.content.trim().slice(0, 80) || "Chat Session";
- const transcript = state.messages
- .map((msg) => {
- const role = msg.role === "user" ? "User" : msg.role === "assistant" ? "Assistant" : "System";
- return `## ${role}\n${msg.content}`;
- })
- .join("\n\n");
return {
recordType: "chat" as const,
title,
- userQuery: state.messages.filter((msg) => msg.role === "user").map((msg) => msg.content).join("\n\n"),
- output: transcript,
+ // The actual transcript / userQuery are rebuilt inside SaveToNotebookModal
+ // from the user's selected subset of messages. We still provide a
+ // sensible fallback for non-selection callers.
+ userQuery: "",
+ output: "",
metadata: {
source: "chat",
capability: state.activeCapability || "chat",
- message_count: state.messages.length,
ui_language: state.language,
session_id: state.sessionId,
+ total_message_count: state.messages.length,
},
};
}, [state.activeCapability, state.language, state.messages, state.sessionId]);
- const activeAssistantMessage = state.isStreaming ? state.messages[state.messages.length - 1] : null;
- const activeUserIndex = useMemo(() => {
- if (!state.isStreaming) return -1;
- for (let index = state.messages.length - 2; index >= 0; index -= 1) {
- if (state.messages[index]?.role === "user") return index;
- }
- return -1;
- }, [state.isStreaming, state.messages]);
const lastMessage = state.messages[state.messages.length - 1];
const {
containerRef: messagesContainerRef,
@@ -350,15 +351,40 @@ export default function ChatPage() {
(snapshot?: MessageRequestSnapshot, assistantMsg?: { content: string; events?: StreamEvent[] }) => {
if (!snapshot || !state.isStreaming) return;
const answerNowEvents = (assistantMsg?.events ?? []).map((event) => ({
- type: event.type, stage: event.stage, content: event.content, metadata: event.metadata ?? {},
+ type: event.type,
+ stage: event.stage,
+ content: event.content,
+ metadata: event.metadata ?? {},
}));
cancelStreamingTurn();
+ // Force the follow-up turn to the chat capability so the answer-now
+ // synthesizer (chat._stage_answer_now) handles it regardless of
+ // whether the original turn was deep_solve / deep_research / etc.
+ // The orchestrator also re-routes server-side as a defensive guard.
+ const answerNowSnapshot: MessageRequestSnapshot = {
+ ...snapshot,
+ capability: "chat",
+ config: {
+ ...(snapshot.config || {}),
+ answer_now_context: {
+ original_user_message: snapshot.content,
+ partial_response: assistantMsg?.content || "",
+ events: answerNowEvents,
+ },
+ },
+ };
window.setTimeout(() => {
sendMessage(
- snapshot.content, snapshot.attachments,
- { ...(snapshot.config || {}), answer_now_context: { original_user_message: snapshot.content, partial_response: assistantMsg?.content || "", events: answerNowEvents } },
- snapshot.notebookReferences, snapshot.historyReferences,
- { displayUserMessage: false, persistUserMessage: false, requestSnapshotOverride: snapshot },
+ answerNowSnapshot.content,
+ answerNowSnapshot.attachments,
+ answerNowSnapshot.config,
+ answerNowSnapshot.notebookReferences,
+ answerNowSnapshot.historyReferences,
+ {
+ displayUserMessage: false,
+ persistUserMessage: false,
+ requestSnapshotOverride: answerNowSnapshot,
+ },
);
shouldAutoScrollRef.current = true;
}, 0);
@@ -463,7 +489,10 @@ export default function ChatPage() {
: [...cap.defaultTools],
);
if (config.enabledTools.includes("rag") && config.knowledgeBase) setKBs([config.knowledgeBase]);
- setResearchPanelCollapsed(cap.value !== "deep_research");
+ // Default-expand the per-capability settings panel right after a
+ // capability switch so users immediately see the form. Sending a
+ // message later will auto-collapse it (see handleSend).
+ setPanelCollapsed(false);
setCapMenuOpen(false);
},
[capabilityConfigs, setCapability, setKBs, setTools],
@@ -563,7 +592,9 @@ export default function ChatPage() {
extraAttachments, config, notebookReferencesPayload, historyReferencesPayload,
);
shouldAutoScrollRef.current = true;
- if (isResearchMode) setResearchPanelCollapsed(true);
+ // Auto-collapse the per-capability settings panel after sending so the
+ // composer stays compact during conversation.
+ setPanelCollapsed(true);
setAttachments([]);
setSelectedNotebookRecords([]);
setSelectedHistorySessions([]);
@@ -594,7 +625,7 @@ export default function ChatPage() {
const handleRemoveNotebook = useCallback((notebookId: string) => {
setSelectedNotebookRecords((prev) => prev.filter((record) => record.notebookId !== notebookId));
}, []);
- const handleToggleResearchCollapsed = useCallback(() => { setResearchPanelCollapsed((prev) => !prev); }, []);
+ const handleTogglePanelCollapsed = useCallback(() => { setPanelCollapsed((prev) => !prev); }, []);
const handleCloseNotebookPicker = useCallback(() => { setShowNotebookPicker(false); }, []);
const handleApplyNotebookRecords = useCallback((records: SelectedRecord[]) => { setSelectedNotebookRecords(records); }, []);
const handleCloseHistoryPicker = useCallback(() => { setShowHistoryPicker(false); }, []);
@@ -607,6 +638,24 @@ export default function ChatPage() {
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">
+ <span className="text-[15px] font-semibold tracking-[-0.01em] text-[var(--foreground)]">{t(activeCap.label)}</span>
+ <div className="flex items-center gap-2">
+ <button
+ onClick={() => setShowSaveModal(true)}
+ disabled={!chatSavePayload}
+ className="rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)] disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:border-[var(--border)]/50 disabled:hover:text-[var(--muted-foreground)]"
+ >
+ {t("Save to Notebook")}
+ </button>
+ <button
+ onClick={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)]"
+ >
+ {t("New chat")}
+ </button>
+ </div>
+ </div>
<div className="mx-auto flex w-full max-w-[960px] flex-1 min-h-0 flex-col overflow-hidden px-6">
{!hasMessages ? (
@@ -625,37 +674,26 @@ export default function ChatPage() {
ref={messagesContainerRef}
data-chat-scroll-root="true"
onScroll={handleMessagesScroll}
- className={`mx-auto w-full flex-1 min-h-0 space-y-7 overflow-y-auto pt-6 pr-4 [scrollbar-gutter:stable] ${hasMessages ? "" : "pb-6"}`}
- style={hasMessages ? { paddingBottom: `${Math.max(composerHeight + 24, 120)}px` } : undefined}
+ className={`mx-auto w-full flex-1 min-h-0 space-y-7 overflow-y-auto pr-4 [scrollbar-gutter:stable] ${hasMessages ? "pt-0" : "pt-2 pb-6"}`}
+ style={
+ hasMessages
+ ? (() => {
+ const maskImage =
+ "linear-gradient(to bottom, transparent 0px, #000 32px, #000 calc(100% - 40px), transparent 100%)";
+ return {
+ paddingBottom: "4px",
+ WebkitMaskImage: maskImage,
+ maskImage,
+ };
+ })()
+ : undefined
+ }
>
- <div className="flex items-center justify-between pb-2">
- <span className="text-[13px] font-medium text-[var(--muted-foreground)]">{t(activeCap.label)}</span>
- <div className="flex items-center gap-2">
- {chatSavePayload && (
- <button
- onClick={() => setShowSaveModal(true)}
- 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)]"
- >
- {t("Save to Notebook")}
- </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)]"
- >
- {t("New chat")}
- </button>
- </div>
- </div>
-
<ChatMessageList
messages={state.messages}
isStreaming={state.isStreaming}
- activeUserIndex={activeUserIndex}
- activeAssistantMessage={activeAssistantMessage?.role === "assistant" ? activeAssistantMessage : null}
sessionId={state.sessionId}
language={state.language}
- onCancelStreaming={cancelStreamingTurn}
onAnswerNow={handleAnswerNow}
onCopyAssistantMessage={copyAssistantMessage}
onRetryMessage={handleRetryMessage}
@@ -700,7 +738,7 @@ export default function ChatPage() {
visualizeConfig={visualizeConfig}
researchConfig={researchConfig}
researchValidationErrors={researchValidation.errors}
- researchPanelCollapsed={researchPanelCollapsed}
+ panelCollapsed={panelCollapsed}
capabilities={CAPABILITIES}
researchSources={RESEARCH_SOURCES}
onSetCapMenuOpen={setCapMenuOpen}
@@ -721,12 +759,13 @@ export default function ChatPage() {
onDrop={handleDrop}
onPaste={handlePaste}
onSelectCapability={handleSelectCapability}
+ onCancelStreaming={cancelStreamingTurn}
onChangeQuizConfig={setQuizConfig}
onUploadQuizPdf={setQuizPdf}
onChangeMathAnimatorConfig={setMathAnimatorConfig}
onChangeVisualizeConfig={setVisualizeConfig}
onChangeResearchConfig={setResearchConfig}
- onToggleResearchCollapsed={handleToggleResearchCollapsed}
+ onTogglePanelCollapsed={handleTogglePanelCollapsed}
/>
</div>
<NotebookRecordPicker
@@ -742,6 +781,7 @@ export default function ChatPage() {
<SaveToNotebookModal
open={showSaveModal}
payload={chatSavePayload}
+ messages={chatSaveMessages}
onClose={handleCloseSaveModal}
/>
</div>
diff --git a/web/app/(workspace)/co-writer/page.tsx b/web/app/(workspace)/co-writer/page.tsx
index f670b5317..506402f15 100644
--- a/web/app/(workspace)/co-writer/page.tsx
+++ b/web/app/(workspace)/co-writer/page.tsx
@@ -69,6 +69,10 @@ interface KnowledgeBase {
const STORAGE_KEY = "deeptutor.co_writer.draft";
const HISTORY_KEY = "deeptutor.co_writer.history";
+const SPLIT_RATIO_KEY = "deeptutor.co_writer.split_ratio";
+const SYNC_SCROLL_KEY = "deeptutor.co_writer.sync_scroll";
+const MIN_PANEL_RATIO = 0.18;
+const MAX_PANEL_RATIO = 0.82;
const ACTION_LABELS: Record<EditAction, string> = {
rewrite: "Rewrite",
@@ -144,6 +148,10 @@ interface StreamEditResult {
export default function CoWriterPage() {
const { t } = useTranslation();
const textareaRef = useRef<HTMLTextAreaElement>(null);
+ const previewScrollRef = useRef<HTMLDivElement>(null);
+ const splitContainerRef = useRef<HTMLDivElement>(null);
+ const scrollSyncSourceRef = useRef<"editor" | "preview" | null>(null);
+ const scrollSyncResetTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const selectionPopoverRef = useRef<HTMLDivElement>(null);
const preserveSelectionTraceRef = useRef(false);
const selectionRequestAbortRef = useRef<AbortController | null>(null);
@@ -182,6 +190,11 @@ export default function CoWriterPage() {
const [editorCollapsed, setEditorCollapsed] = useState(false);
const [previewCollapsed, setPreviewCollapsed] = useState(false);
+ const [editorRatio, setEditorRatio] = useState(0.5);
+ const [isResizingSplit, setIsResizingSplit] = useState(false);
+ const [syncScrollEnabled, setSyncScrollEnabled] = useState(true);
+ const showEditor = !editorCollapsed;
+ const showPreview = !previewCollapsed;
const [showSaveModal, setShowSaveModal] = useState(false);
@@ -194,6 +207,21 @@ export default function CoWriterPage() {
const saved = window.localStorage.getItem(STORAGE_KEY);
setMarkdown(saved === null ? CO_WRITER_SAMPLE_TEMPLATE : saved);
setHasLoadedDraft(true);
+
+ const savedRatio = window.localStorage.getItem(SPLIT_RATIO_KEY);
+ if (savedRatio) {
+ const parsed = Number.parseFloat(savedRatio);
+ if (Number.isFinite(parsed)) {
+ setEditorRatio(
+ Math.min(MAX_PANEL_RATIO, Math.max(MIN_PANEL_RATIO, parsed)),
+ );
+ }
+ }
+
+ const savedSync = window.localStorage.getItem(SYNC_SCROLL_KEY);
+ if (savedSync !== null) {
+ setSyncScrollEnabled(savedSync !== "0");
+ }
}, []);
useEffect(() => {
@@ -201,6 +229,31 @@ export default function CoWriterPage() {
window.localStorage.setItem(STORAGE_KEY, markdown);
}, [hasLoadedDraft, markdown]);
+ useEffect(() => {
+ window.localStorage.setItem(SPLIT_RATIO_KEY, String(editorRatio));
+ }, [editorRatio]);
+
+ useEffect(() => {
+ window.localStorage.setItem(SYNC_SCROLL_KEY, syncScrollEnabled ? "1" : "0");
+ }, [syncScrollEnabled]);
+
+ useEffect(() => {
+ // Drop the cached editor line positions when the viewport changes width;
+ // wrapping behavior depends on it.
+ const handleResize = () => {
+ editorYCacheRef.current = null;
+ };
+ window.addEventListener("resize", handleResize);
+ return () => window.removeEventListener("resize", handleResize);
+ }, []);
+
+ // Editor inner width can change without a window resize (collapsing the
+ // preview pane, dragging the splitter, etc). Invalidate the y cache so the
+ // mirror remeasures with the new wrap width.
+ useEffect(() => {
+ editorYCacheRef.current = null;
+ }, [editorRatio, editorCollapsed, previewCollapsed]);
+
useEffect(() => {
(async () => {
try {
@@ -836,9 +889,6 @@ export default function CoWriterPage() {
[handleUndo, handleRedo],
);
- const showEditor = !editorCollapsed;
- const showPreview = !previewCollapsed;
-
useEffect(() => {
if (!selectionPopover.visible) return;
const handleViewportChange = () => updateSelectionPopover();
@@ -896,9 +946,375 @@ export default function CoWriterPage() {
useEffect(() => {
return () => {
selectionRequestAbortRef.current?.abort();
+ if (scrollSyncResetTimerRef.current) {
+ clearTimeout(scrollSyncResetTimerRef.current);
+ }
+ };
+ }, []);
+
+ const handleSplitterPointerDown = useCallback(
+ (event: React.PointerEvent<HTMLDivElement>) => {
+ if (!showEditor || !showPreview) return;
+ event.preventDefault();
+ setIsResizingSplit(true);
+ try {
+ (event.target as HTMLDivElement).setPointerCapture(event.pointerId);
+ } catch {
+ /* ignore */
+ }
+ },
+ [showEditor, showPreview],
+ );
+
+ useEffect(() => {
+ if (!isResizingSplit) return;
+ const handleMove = (event: PointerEvent) => {
+ const container = splitContainerRef.current;
+ if (!container) return;
+ const rect = container.getBoundingClientRect();
+ if (rect.width <= 0) return;
+ const ratio = (event.clientX - rect.left) / rect.width;
+ setEditorRatio(
+ Math.min(MAX_PANEL_RATIO, Math.max(MIN_PANEL_RATIO, ratio)),
+ );
+ };
+ const handleEnd = () => setIsResizingSplit(false);
+ window.addEventListener("pointermove", handleMove);
+ window.addEventListener("pointerup", handleEnd);
+ window.addEventListener("pointercancel", handleEnd);
+ return () => {
+ window.removeEventListener("pointermove", handleMove);
+ window.removeEventListener("pointerup", handleEnd);
+ window.removeEventListener("pointercancel", handleEnd);
};
+ }, [isResizingSplit]);
+
+ const releaseScrollSyncSource = useCallback(() => {
+ if (scrollSyncResetTimerRef.current) {
+ clearTimeout(scrollSyncResetTimerRef.current);
+ }
+ scrollSyncResetTimerRef.current = setTimeout(() => {
+ scrollSyncSourceRef.current = null;
+ }, 90);
+ }, []);
+
+ // ── Line-anchored scroll synchronization ──
+ //
+ // Each block element rendered in the preview carries a `data-source-line`
+ // attribute that points back at its starting line in the markdown source
+ // (provided by remark's AST position info). For the editor side we cannot
+ // assume `scrollTop / lineHeight = source line` because long lines wrap
+ // visually. Instead we build a hidden mirror that mimics the textarea's
+ // wrapping and read the real pixel y of every source line. With both sides
+ // expressed as pixel coordinates we can interpolate either direction with
+ // a single piecewise-linear map.
+
+ // Cache: rebuilding the mirror is moderately expensive, so cache by
+ // (markdown content, textarea inner width). Both invalidate the cache.
+ const editorYCacheRef = useRef<{
+ signature: string;
+ ys: Map<number, number>;
+ } | null>(null);
+
+ const measureEditorLineYs = useCallback((): Map<number, number> => {
+ const editor = textareaRef.current;
+ if (!editor) return new Map();
+ const value = editor.value;
+ const sourceLines = value.split("\n");
+ if (sourceLines.length === 0) return new Map();
+
+ const computed = window.getComputedStyle(editor);
+ const rect = editor.getBoundingClientRect();
+ const mirror = document.createElement("div");
+
+ const properties = [
+ "box-sizing",
+ "width",
+ "border-top-width",
+ "border-right-width",
+ "border-bottom-width",
+ "border-left-width",
+ "padding-top",
+ "padding-right",
+ "padding-bottom",
+ "padding-left",
+ "font-style",
+ "font-variant",
+ "font-weight",
+ "font-stretch",
+ "font-size",
+ "font-size-adjust",
+ "line-height",
+ "font-family",
+ "letter-spacing",
+ "text-align",
+ "text-transform",
+ "text-indent",
+ "tab-size",
+ ];
+ for (const property of properties) {
+ mirror.style.setProperty(property, computed.getPropertyValue(property));
+ }
+
+ mirror.style.position = "fixed";
+ mirror.style.top = `${rect.top}px`;
+ mirror.style.left = `${rect.left}px`;
+ mirror.style.height = "auto";
+ mirror.style.maxHeight = "none";
+ mirror.style.minHeight = "0";
+ mirror.style.whiteSpace = "pre-wrap";
+ mirror.style.overflowWrap = "break-word";
+ mirror.style.wordBreak = "normal";
+ mirror.style.visibility = "hidden";
+ mirror.style.pointerEvents = "none";
+ mirror.style.zIndex = "-1";
+
+ const spans: HTMLSpanElement[] = [];
+ for (let i = 0; i < sourceLines.length; i += 1) {
+ if (i > 0) mirror.appendChild(document.createTextNode("\n"));
+ const span = document.createElement("span");
+ // Empty lines need measurable content for offsetTop to be meaningful.
+ span.textContent =
+ sourceLines[i].length > 0 ? sourceLines[i] : "\u200B";
+ mirror.appendChild(span);
+ spans.push(span);
+ }
+
+ document.body.appendChild(mirror);
+
+ const result = new Map<number, number>();
+ // span.offsetTop is the y-position of the line within the mirror, which
+ // mirrors the textarea's scroll content. Setting `editor.scrollTop` to
+ // this value lifts that source line to the top of the visible viewport.
+ for (let i = 0; i < spans.length; i += 1) {
+ result.set(i + 1, spans[i].offsetTop);
+ }
+
+ document.body.removeChild(mirror);
+ return result;
+ }, []);
+
+ const getEditorLineYs = useCallback((): Map<number, number> => {
+ const editor = textareaRef.current;
+ if (!editor) return new Map();
+ const signature = `${editor.clientWidth}|${markdown}`;
+ const cached = editorYCacheRef.current;
+ if (cached && cached.signature === signature) return cached.ys;
+ const ys = measureEditorLineYs();
+ editorYCacheRef.current = { signature, ys };
+ return ys;
+ }, [markdown, measureEditorLineYs]);
+
+ const collectPreviewLineYs = useCallback((): Map<number, number> => {
+ const preview = previewScrollRef.current;
+ if (!preview) return new Map();
+ const nodes = preview.querySelectorAll<HTMLElement>("[data-source-line]");
+ if (nodes.length === 0) return new Map();
+ const previewRect = preview.getBoundingClientRect();
+ const baseTop = previewRect.top - preview.scrollTop;
+ const result = new Map<number, number>();
+ for (const el of Array.from(nodes)) {
+ const raw = el.getAttribute("data-source-line");
+ const line = raw ? Number.parseInt(raw, 10) : NaN;
+ if (!Number.isFinite(line)) continue;
+ // Keep the first occurrence; nested wrappers often repeat the same line.
+ if (result.has(line)) continue;
+ const rect = el.getBoundingClientRect();
+ result.set(line, rect.top - baseTop);
+ }
+ return result;
}, []);
+ const buildJointMarkers = useCallback((): Array<{
+ line: number;
+ editorY: number;
+ previewY: number;
+ }> => {
+ const editorYs = getEditorLineYs();
+ const previewYs = collectPreviewLineYs();
+ if (editorYs.size === 0 || previewYs.size === 0) return [];
+
+ const lines = Array.from(previewYs.keys())
+ .filter((line) => editorYs.has(line))
+ .sort((a, b) => a - b);
+
+ const editor = textareaRef.current;
+ const preview = previewScrollRef.current;
+ const markers: Array<{ line: number; editorY: number; previewY: number }> =
+ [];
+ for (const line of lines) {
+ const editorY = editorYs.get(line);
+ const previewY = previewYs.get(line);
+ if (typeof editorY !== "number" || typeof previewY !== "number") continue;
+ markers.push({ line, editorY, previewY });
+ }
+
+ // Anchor the very top so we don't snap to the first heading when the user
+ // is still above it.
+ if (markers.length === 0 || markers[0].editorY > 0 || markers[0].previewY > 0) {
+ markers.unshift({ line: 0, editorY: 0, previewY: 0 });
+ }
+
+ // Anchor the bottom so the bottom of the document matches.
+ if (editor && preview) {
+ const editorMax = Math.max(0, editor.scrollHeight - editor.clientHeight);
+ const previewMax = Math.max(0, preview.scrollHeight - preview.clientHeight);
+ const last = markers[markers.length - 1];
+ if (
+ editorMax > last.editorY + 1 ||
+ previewMax > last.previewY + 1
+ ) {
+ markers.push({
+ line: last.line + 1,
+ editorY: editorMax,
+ previewY: previewMax,
+ });
+ }
+ }
+
+ return markers;
+ }, [collectPreviewLineYs, getEditorLineYs]);
+
+ const interpolate = (
+ value: number,
+ fromA: number,
+ fromB: number,
+ toA: number,
+ toB: number,
+ ): number => {
+ if (fromA === fromB) return toA;
+ const ratio = (value - fromA) / (fromB - fromA);
+ return toA + (toB - toA) * ratio;
+ };
+
+ const handleEditorScrollSync = useCallback(() => {
+ updateSelectionPopover();
+ if (!syncScrollEnabled) return;
+ if (scrollSyncSourceRef.current === "preview") return;
+ const editor = textareaRef.current;
+ const preview = previewScrollRef.current;
+ if (!editor || !preview) return;
+ const markers = buildJointMarkers();
+ if (markers.length === 0) return;
+
+ const editorScroll = editor.scrollTop;
+ let lower = markers[0];
+ let upper = markers[markers.length - 1];
+ for (const marker of markers) {
+ if (marker.editorY <= editorScroll) lower = marker;
+ if (marker.editorY >= editorScroll) {
+ upper = marker;
+ break;
+ }
+ }
+
+ const target = interpolate(
+ editorScroll,
+ lower.editorY,
+ upper.editorY,
+ lower.previewY,
+ upper.previewY,
+ );
+
+ const max = preview.scrollHeight - preview.clientHeight;
+ const next = Math.max(0, Math.min(max, target));
+ if (Math.abs(next - preview.scrollTop) < 0.5) return;
+ scrollSyncSourceRef.current = "editor";
+ preview.scrollTop = next;
+ releaseScrollSyncSource();
+ }, [
+ buildJointMarkers,
+ releaseScrollSyncSource,
+ syncScrollEnabled,
+ updateSelectionPopover,
+ ]);
+
+ const handlePreviewScrollSync = useCallback(() => {
+ if (!syncScrollEnabled) return;
+ if (scrollSyncSourceRef.current === "editor") return;
+ const editor = textareaRef.current;
+ const preview = previewScrollRef.current;
+ if (!editor || !preview) return;
+ const markers = buildJointMarkers();
+ if (markers.length === 0) return;
+
+ const previewScroll = preview.scrollTop;
+ let lower = markers[0];
+ let upper = markers[markers.length - 1];
+ for (const marker of markers) {
+ if (marker.previewY <= previewScroll) lower = marker;
+ if (marker.previewY >= previewScroll) {
+ upper = marker;
+ break;
+ }
+ }
+
+ const target = interpolate(
+ previewScroll,
+ lower.previewY,
+ upper.previewY,
+ lower.editorY,
+ upper.editorY,
+ );
+
+ const max = editor.scrollHeight - editor.clientHeight;
+ const next = Math.max(0, Math.min(max, target));
+ if (Math.abs(next - editor.scrollTop) < 0.5) return;
+ scrollSyncSourceRef.current = "preview";
+ editor.scrollTop = next;
+ releaseScrollSyncSource();
+ }, [buildJointMarkers, releaseScrollSyncSource, syncScrollEnabled]);
+
+ // Mermaid diagrams, images, and KaTeX render asynchronously, so the preview's
+ // scrollHeight (and the y position of every marker after them) shifts well
+ // after the initial render. Without intervention, the user's last alignment
+ // becomes stale and the next scroll feels "jumpy" because all the markers
+ // moved underneath them. Whenever the preview's intrinsic height changes we
+ // re-run the editor→preview sync to put the preview back in lock-step with
+ // the editor's current scroll position.
+ const handleEditorScrollSyncRef = useRef(handleEditorScrollSync);
+ useEffect(() => {
+ handleEditorScrollSyncRef.current = handleEditorScrollSync;
+ }, [handleEditorScrollSync]);
+
+ useEffect(() => {
+ const preview = previewScrollRef.current;
+ if (!preview) return;
+ const inner = preview.firstElementChild as HTMLElement | null;
+ if (!inner) return;
+
+ let raf = 0;
+ const schedule = () => {
+ if (raf) cancelAnimationFrame(raf);
+ raf = requestAnimationFrame(() => {
+ raf = 0;
+ // Treat this as an editor-driven update; we want preview to follow
+ // wherever the editor cursor currently anchors us, not the other way
+ // around (which would feed back into editor scroll).
+ if (scrollSyncSourceRef.current) return;
+ handleEditorScrollSyncRef.current();
+ });
+ };
+
+ const observer = new ResizeObserver(schedule);
+ observer.observe(inner);
+
+ // Images load asynchronously and don't always trigger a ResizeObserver
+ // update on the parent, so we listen to load events directly too.
+ const onLoad = (event: Event) => {
+ const target = event.target as HTMLElement | null;
+ if (!target) return;
+ if (target.tagName === "IMG" || target.tagName === "IFRAME") schedule();
+ };
+ inner.addEventListener("load", onLoad, true);
+
+ return () => {
+ if (raf) cancelAnimationFrame(raf);
+ observer.disconnect();
+ inner.removeEventListener("load", onLoad, true);
+ };
+ }, [showPreview]);
+
return (
<div className="flex h-full min-h-full flex-col overflow-hidden bg-[var(--background)]">
{/* ── Top bar ── */}
@@ -911,31 +1327,31 @@ export default function CoWriterPage() {
{wordCount} {t("words")} &middot; {charCount} {t("chars")}
</span>
</div>
- <div className="flex items-center gap-1.5">
+ <div className="flex items-center gap-2">
<ToolbarIconBtn
title={t("Clear")}
onClick={clearDocument}
>
- <Eraser size={15} />
+ <Eraser size={17} strokeWidth={1.7} />
</ToolbarIconBtn>
<ToolbarIconBtn
title={t("Export Markdown")}
onClick={handleDownload}
>
- <Download size={15} />
+ <Download size={17} strokeWidth={1.7} />
</ToolbarIconBtn>
<ToolbarIconBtn
title={t("Load Example Template")}
onClick={loadExampleTemplate}
>
- <FileText size={15} />
+ <FileText size={17} strokeWidth={1.7} />
</ToolbarIconBtn>
<div className="relative">
<ToolbarIconBtn
title={t("Add to Notebook")}
onClick={() => setShowSaveModal(true)}
>
- <BookPlus size={15} />
+ <BookPlus size={17} strokeWidth={1.7} />
</ToolbarIconBtn>
</div>
<a
@@ -984,7 +1400,31 @@ export default function CoWriterPage() {
);
})}
- <div className="ml-auto flex shrink-0 items-center gap-1 pl-3 text-[10px] text-[var(--muted-foreground)]">
+ <div className="ml-auto flex shrink-0 items-center gap-1.5 pl-3 text-[10px] text-[var(--muted-foreground)]">
+ <button
+ type="button"
+ onClick={() => setSyncScrollEnabled((prev) => !prev)}
+ disabled={!showEditor || !showPreview}
+ title={
+ syncScrollEnabled
+ ? t("Scroll sync is on. Click to disable.")
+ : t("Scroll sync is off. Click to enable.")
+ }
+ className={`inline-flex items-center gap-1 rounded border px-1.5 py-0.5 text-[10px] font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-40 ${
+ syncScrollEnabled
+ ? "border-[var(--primary)]/40 bg-[var(--primary)]/10 text-[var(--primary)]"
+ : "border-[var(--border)] bg-transparent text-[var(--muted-foreground)] hover:bg-[var(--muted)]"
+ }`}
+ >
+ <span
+ aria-hidden="true"
+ className={`inline-block h-1.5 w-1.5 rounded-full ${
+ syncScrollEnabled ? "bg-[var(--primary)]" : "bg-[var(--muted-foreground)]/60"
+ }`}
+ />
+ {t("Sync Scroll")}
+ </button>
+ <span className="mx-0.5 h-3 w-px bg-[var(--border)]" aria-hidden="true" />
<span className="rounded bg-[var(--muted)] px-1.5 py-0.5">GFM</span>
<span className="rounded bg-[var(--muted)] px-1.5 py-0.5">
KaTeX
@@ -996,11 +1436,19 @@ export default function CoWriterPage() {
</div>
{/* ── Editor + Preview ── */}
- <div className="relative flex min-h-0 flex-1">
+ <div
+ ref={splitContainerRef}
+ className={`relative flex min-h-0 flex-1 ${
+ isResizingSplit ? "select-none" : ""
+ }`}
+ >
{/* Editor panel */}
{showEditor && (
<div
- className={`flex min-h-0 flex-col ${showPreview ? "w-1/2" : "w-full"} border-r border-[var(--border)]`}
+ className="flex min-h-0 flex-col"
+ style={{
+ width: showPreview ? `${editorRatio * 100}%` : "100%",
+ }}
>
<div className="flex shrink-0 items-center justify-between border-b border-[var(--border)] px-3 py-1">
<span className="text-xs font-medium text-[var(--muted-foreground)]">
@@ -1021,7 +1469,7 @@ export default function CoWriterPage() {
onSelect={updateSelectionPopover}
onKeyUp={updateSelectionPopover}
onMouseUp={updateSelectionPopover}
- onScroll={updateSelectionPopover}
+ onScroll={handleEditorScrollSync}
spellCheck={false}
className="min-h-0 flex-1 resize-none bg-transparent p-4 font-mono text-[13px] leading-relaxed text-[var(--foreground)] outline-none placeholder:text-[var(--muted-foreground)]"
placeholder={t("Start writing in Markdown...")}
@@ -1029,6 +1477,33 @@ export default function CoWriterPage() {
</div>
)}
+ {/* Draggable splitter (only when both panes are visible) */}
+ {showEditor && showPreview && (
+ <div
+ role="separator"
+ aria-orientation="vertical"
+ aria-label={t("Resize editor and preview")}
+ onPointerDown={handleSplitterPointerDown}
+ onDoubleClick={() => setEditorRatio(0.5)}
+ className={`group relative z-10 flex w-1 shrink-0 cursor-col-resize items-stretch border-x border-[var(--border)] transition-colors ${
+ isResizingSplit
+ ? "bg-[var(--primary)]/40"
+ : "bg-transparent hover:bg-[var(--primary)]/30"
+ }`}
+ title={t("Drag to resize, double-click to reset")}
+ >
+ {/* Wider invisible hit-area so the handle is easy to grab */}
+ <div className="absolute inset-y-0 -left-1.5 -right-1.5" />
+ <div
+ className={`pointer-events-none absolute left-1/2 top-1/2 h-10 w-[3px] -translate-x-1/2 -translate-y-1/2 rounded-full transition-opacity ${
+ isResizingSplit
+ ? "bg-[var(--primary)] opacity-100"
+ : "bg-[var(--muted-foreground)]/40 opacity-0 group-hover:opacity-100"
+ }`}
+ />
+ </div>
+ )}
+
{/* Collapse gutter / expand buttons */}
{editorCollapsed && (
<button
@@ -1053,7 +1528,10 @@ export default function CoWriterPage() {
{/* Preview panel */}
{showPreview && (
<div
- className={`flex min-h-0 flex-col ${showEditor ? "w-1/2" : "w-full"}`}
+ className="flex min-h-0 flex-col"
+ style={{
+ width: showEditor ? `${(1 - editorRatio) * 100}%` : "100%",
+ }}
>
<div className="flex shrink-0 items-center justify-between border-b border-[var(--border)] px-3 py-1">
<span className="text-xs font-medium text-[var(--muted-foreground)]">
@@ -1067,10 +1545,15 @@ export default function CoWriterPage() {
<ChevronRight size={14} />
</button>
</div>
- <div className="min-h-0 flex-1 overflow-y-auto p-5">
+ <div
+ ref={previewScrollRef}
+ onScroll={handlePreviewScrollSync}
+ className="min-h-0 flex-1 overflow-y-auto p-5"
+ >
<MarkdownRenderer
content={markdown || `_${t("Nothing to preview yet.")}_`}
variant="prose"
+ trackSourceLines
/>
</div>
</div>
@@ -1454,7 +1937,7 @@ function ToolbarIconBtn({
<button
title={title}
onClick={onClick}
- className="rounded p-1.5 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
+ className="inline-flex h-8 w-8 items-center justify-center rounded-md text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
>
{children}
</button>
diff --git a/web/app/(workspace)/guide/components/ChatPanel.tsx b/web/app/(workspace)/guide/components/ChatPanel.tsx
index ece17e8a1..100a085ac 100644
--- a/web/app/(workspace)/guide/components/ChatPanel.tsx
+++ b/web/app/(workspace)/guide/components/ChatPanel.tsx
@@ -51,14 +51,14 @@ export default function ChatPanel({
};
return (
- <div className="flex-1 bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 flex flex-col overflow-hidden">
- <div className="p-3 border-b border-slate-100 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-800/50 text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider flex items-center gap-2">
- <MessageSquare className="w-4 h-4" />
+ <div className="surface-card flex flex-1 flex-col overflow-hidden border border-[var(--border)] bg-[var(--card)] text-[var(--card-foreground)]">
+ <div className="flex items-center gap-2 border-b border-[var(--border)] bg-[var(--muted)]/35 p-3 text-xs font-bold uppercase tracking-wider text-[var(--muted-foreground)]">
+ <MessageSquare className="h-4 w-4" />
{t("Learning Assistant")}
</div>
{isLearning && currentKnowledgeTitle && (
- <div className="px-4 py-2 border-b border-slate-100 dark:border-slate-700 bg-indigo-50/60 text-xs text-indigo-700 dark:bg-indigo-950/30 dark:text-indigo-200">
+ <div className="border-b border-[var(--border)] bg-[var(--primary)]/8 px-4 py-2 text-xs text-[var(--primary)]">
{t("Current page")}: {currentKnowledgeIndex !== undefined ? currentKnowledgeIndex + 1 : ""}
{currentKnowledgeIndex !== undefined ? ". " : ""}
{currentKnowledgeTitle}
@@ -67,7 +67,7 @@ export default function ChatPanel({
<div
ref={chatContainerRef}
- className="flex-1 overflow-y-auto p-4 space-y-4 bg-slate-50/30 dark:bg-slate-800/30"
+ className="flex-1 space-y-4 overflow-y-auto bg-[var(--background)]/30 p-4"
>
{messages.map((msg) => (
<div
@@ -77,12 +77,12 @@ export default function ChatPanel({
<div
className={`max-w-[90%] rounded-2xl px-4 py-3 text-sm ${
msg.role === "user"
- ? "bg-indigo-600 text-white rounded-tr-none shadow-md shadow-indigo-500/20"
+ ? "rounded-tr-none bg-[var(--primary)] text-[var(--primary-foreground)] shadow-sm"
: msg.role === "system" && msg.content.includes("⏳")
- ? "bg-amber-50 border border-amber-200 text-amber-900 rounded-tl-none"
+ ? "rounded-tl-none border border-amber-300/50 bg-amber-500/10 text-amber-900 dark:text-amber-200"
: msg.role === "system"
- ? "bg-blue-50 border border-blue-200 text-blue-900 rounded-tl-none"
- : "bg-white border border-slate-200 text-slate-700 rounded-tl-none shadow-sm"
+ ? "rounded-tl-none border border-sky-300/50 bg-sky-500/10 text-sky-900 dark:text-sky-200"
+ : "rounded-tl-none border border-[var(--border)] bg-[var(--card)] text-[var(--foreground)] shadow-sm"
}`}
>
{typeof msg.knowledge_index === "number" && (
@@ -94,7 +94,7 @@ export default function ChatPanel({
<MarkdownRenderer
content={msg.content}
variant="compact"
- className="prose-slate text-sm"
+ className="text-sm"
/>
) : (
<p>{msg.content}</p>
@@ -105,7 +105,7 @@ export default function ChatPanel({
</div>
{isLearning && (
- <div className="p-3 bg-white dark:bg-slate-800 border-t border-slate-100 dark:border-slate-700">
+ <div className="border-t border-[var(--border)] bg-[var(--card)] p-3">
<div className="relative flex items-center gap-2">
<input
type="text"
@@ -116,17 +116,17 @@ export default function ChatPanel({
}
placeholder={t("Have any questions? Feel free to ask...")}
disabled={sendingMessage}
- className="flex-1 pl-4 pr-10 py-2.5 bg-slate-100 dark:bg-slate-700 border-transparent focus:bg-white dark:focus:bg-slate-600 focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500/20 rounded-xl text-sm text-slate-900 dark:text-slate-100 placeholder:text-slate-400 dark:placeholder:text-slate-500 transition-all outline-none disabled:opacity-50 disabled:cursor-not-allowed"
+ className="flex-1 rounded-xl border border-transparent bg-[var(--muted)]/60 py-2.5 pl-4 pr-10 text-sm text-[var(--foreground)] outline-none transition placeholder:text-[var(--muted-foreground)] focus:border-[var(--primary)]/50 focus:bg-[var(--card)] focus:ring-2 focus:ring-[var(--primary)]/15 disabled:cursor-not-allowed disabled:opacity-50"
/>
<button
onClick={handleSendMessage}
disabled={!inputMessage.trim() || sendingMessage}
- className="p-2.5 bg-indigo-600 text-white rounded-xl hover:bg-indigo-700 active:scale-95 transition-all disabled:opacity-50 disabled:cursor-not-allowed shadow-lg shadow-indigo-500/20"
+ className="btn-primary rounded-xl bg-[var(--primary)] p-2.5 text-[var(--primary-foreground)] transition-opacity hover:opacity-90 active:scale-95 disabled:cursor-not-allowed disabled:opacity-50"
>
{sendingMessage ? (
- <Loader2 className="w-4 h-4 animate-spin" />
+ <Loader2 className="h-4 w-4 animate-spin" />
) : (
- <Send className="w-4 h-4" />
+ <Send className="h-4 w-4" />
)}
</button>
</div>
diff --git a/web/app/(workspace)/guide/components/CompletionSummary.tsx b/web/app/(workspace)/guide/components/CompletionSummary.tsx
index 12a4be5bf..e11032dd1 100644
--- a/web/app/(workspace)/guide/components/CompletionSummary.tsx
+++ b/web/app/(workspace)/guide/components/CompletionSummary.tsx
@@ -13,19 +13,15 @@ export default function CompletionSummary({ summary }: CompletionSummaryProps) {
const { t } = useTranslation();
return (
- <div className="flex-1 bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 flex flex-col overflow-hidden relative">
- <div className="p-4 border-b border-slate-100 dark:border-slate-700 bg-gradient-to-r from-emerald-50 to-indigo-50 dark:from-emerald-900/20 dark:to-indigo-900/20 flex items-center justify-between shrink-0">
- <h2 className="font-bold text-slate-800 dark:text-slate-100 flex items-center gap-2">
- <CheckCircle2 className="w-5 h-5 text-emerald-600 dark:text-emerald-400" />
+ <div className="surface-card relative flex flex-1 flex-col overflow-hidden border border-[var(--border)] bg-[var(--card)] text-[var(--card-foreground)]">
+ <div className="flex shrink-0 items-center justify-between border-b border-[var(--border)] bg-gradient-to-r from-emerald-500/10 to-[var(--primary)]/10 p-4">
+ <h2 className="flex items-center gap-2 font-semibold text-[var(--foreground)]">
+ <CheckCircle2 className="h-5 w-5 text-emerald-600 dark:text-emerald-400" />
{t("Learning Summary")}
</h2>
</div>
- <div className="flex-1 overflow-y-auto p-8 bg-white dark:bg-slate-800">
- <MarkdownRenderer
- content={summary || ""}
- variant="prose"
- className="prose-slate dark:prose-invert"
- />
+ <div className="flex-1 overflow-y-auto bg-[var(--card)] p-8">
+ <MarkdownRenderer content={summary || ""} variant="prose" />
</div>
</div>
);
diff --git a/web/app/(workspace)/guide/components/DebugModal.tsx b/web/app/(workspace)/guide/components/DebugModal.tsx
index 82ea51cc6..83d38db21 100644
--- a/web/app/(workspace)/guide/components/DebugModal.tsx
+++ b/web/app/(workspace)/guide/components/DebugModal.tsx
@@ -40,23 +40,24 @@ export default function DebugModal({
};
return (
- <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 animate-in fade-in">
- <div className="bg-white dark:bg-slate-800 rounded-2xl shadow-2xl w-[500px] animate-in zoom-in-95">
- <div className="p-4 border-b border-slate-100 dark:border-slate-700 flex items-center justify-between">
- <h3 className="font-bold text-slate-900 dark:text-slate-100 flex items-center gap-2">
- <Bug className="w-5 h-5 text-amber-600 dark:text-amber-400" />
+ <div className="fixed inset-0 z-[80] flex items-center justify-center bg-[var(--background)]/65 p-4 backdrop-blur-md">
+ <div className="surface-card w-[500px] max-w-full overflow-hidden rounded-2xl border border-[var(--border)] bg-[var(--card)] text-[var(--card-foreground)] shadow-[0_22px_70px_rgba(0,0,0,0.18)]">
+ <div className="flex items-center justify-between border-b border-[var(--border)] p-4">
+ <h3 className="flex items-center gap-2 font-semibold text-[var(--foreground)]">
+ <Bug className="h-5 w-5 text-amber-600 dark:text-amber-400" />
{t("Fix HTML Issue")}
</h3>
<button
onClick={handleClose}
- className="p-1 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg"
+ className="rounded-lg p-1.5 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
+ aria-label={t("Close")}
>
- <X className="w-5 h-5 text-slate-500 dark:text-slate-400" />
+ <X className="h-5 w-5" />
</button>
</div>
- <div className="p-6 space-y-4">
+ <div className="space-y-4 p-6">
<div>
- <label className="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-2">
+ <label className="mb-2 block text-xs font-bold uppercase tracking-wider text-[var(--muted-foreground)]">
{t("Issue Description")}
</label>
<textarea
@@ -66,30 +67,30 @@ export default function DebugModal({
"Describe the HTML issue, e.g.: button not clickable, style display error, interaction not working...",
)}
rows={6}
- className="w-full px-4 py-2 border border-slate-200 dark:border-slate-600 bg-white dark:bg-slate-700 text-slate-900 dark:text-slate-100 rounded-xl focus:ring-2 focus:ring-amber-500/20 focus:border-amber-500 outline-none resize-none"
+ className="w-full resize-none rounded-xl border border-[var(--border)] bg-[var(--card)] px-4 py-2 text-[var(--foreground)] outline-none transition placeholder:text-[var(--muted-foreground)] focus:border-amber-500/60 focus:ring-2 focus:ring-amber-500/15"
/>
</div>
</div>
- <div className="p-4 border-t border-slate-100 dark:border-slate-700 flex justify-end gap-2">
+ <div className="flex justify-end gap-2 border-t border-[var(--border)] p-4">
<button
onClick={handleClose}
- className="px-4 py-2 text-slate-600 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg transition-colors"
+ className="rounded-lg px-4 py-2 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
>
{t("Cancel")}
</button>
<button
onClick={handleFix}
disabled={!description.trim() || fixing}
- className="px-4 py-2 bg-amber-600 text-white rounded-lg hover:bg-amber-700 transition-colors disabled:opacity-50 flex items-center gap-2"
+ className="flex items-center gap-2 rounded-lg bg-amber-600 px-4 py-2 text-white transition-colors hover:bg-amber-700 disabled:opacity-50 dark:bg-amber-500 dark:hover:bg-amber-400"
>
{fixing ? (
<>
- <Loader2 className="w-4 h-4 animate-spin" />
+ <Loader2 className="h-4 w-4 animate-spin" />
{t("Fixing...")}
</>
) : (
<>
- <Bug className="w-4 h-4" />
+ <Bug className="h-4 w-4" />
{t("Fix")}
</>
)}
diff --git a/web/app/(workspace)/guide/components/HTMLViewer.tsx b/web/app/(workspace)/guide/components/HTMLViewer.tsx
index 9e05cae09..90021cdce 100644
--- a/web/app/(workspace)/guide/components/HTMLViewer.tsx
+++ b/web/app/(workspace)/guide/components/HTMLViewer.tsx
@@ -158,9 +158,9 @@ export default function HTMLViewer({
if (!html) {
return (
- <div className="flex-1 flex flex-col items-center justify-center bg-white dark:bg-slate-800 rounded-b-2xl border border-t-0 border-slate-200 dark:border-slate-700">
- <Loader2 className="w-12 h-12 text-indigo-400 dark:text-indigo-500 animate-spin mb-4" />
- <p className="text-slate-500 dark:text-slate-400">
+ <div className="flex flex-1 flex-col items-center justify-center rounded-b-2xl border border-t-0 border-[var(--border)] bg-[var(--card)]">
+ <Loader2 className="mb-4 h-12 w-12 animate-spin text-[var(--primary)]" />
+ <p className="text-[var(--muted-foreground)]">
{loadingMessage || t("Loading learning content...")}
</p>
</div>
@@ -168,13 +168,13 @@ export default function HTMLViewer({
}
return (
- <div className="flex-1 bg-white dark:bg-slate-800 rounded-b-2xl shadow-sm border border-t-0 border-slate-200 dark:border-slate-700 flex flex-col overflow-hidden relative">
+ <div className="surface-card relative flex flex-1 flex-col overflow-hidden rounded-b-2xl rounded-t-none border border-t-0 border-[var(--border)] bg-[var(--card)]">
<button
onClick={onOpenDebugModal}
- className="absolute top-4 right-4 z-10 p-2 bg-slate-100 dark:bg-slate-700 hover:bg-slate-200 dark:hover:bg-slate-600 rounded-lg transition-colors shadow-sm"
+ className="absolute right-4 top-4 z-10 rounded-lg border border-[var(--border)] bg-[var(--card)] p-2 text-[var(--muted-foreground)] shadow-sm transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
title={t("Fix HTML")}
>
- <Bug className="w-4 h-4 text-slate-600 dark:text-slate-300" />
+ <Bug className="h-4 w-4" />
</button>
<iframe
diff --git a/web/app/(workspace)/guide/components/KnowledgeTabBar.tsx b/web/app/(workspace)/guide/components/KnowledgeTabBar.tsx
index 957fbbb0b..7c6c50be9 100644
--- a/web/app/(workspace)/guide/components/KnowledgeTabBar.tsx
+++ b/web/app/(workspace)/guide/components/KnowledgeTabBar.tsx
@@ -59,20 +59,20 @@ export default function KnowledgeTabBar({
const renderStatusIcon = (index: number) => {
const status = sessionState.page_statuses[index];
if (status === "ready")
- return <CheckCircle2 className="w-3.5 h-3.5 text-emerald-500" />;
+ return <CheckCircle2 className="h-3.5 w-3.5 text-emerald-500" />;
if (status === "generating")
- return <Loader2 className="w-3.5 h-3.5 text-indigo-500 animate-spin" />;
+ return <Loader2 className="h-3.5 w-3.5 animate-spin text-[var(--primary)]" />;
if (status === "failed")
- return <XCircle className="w-3.5 h-3.5 text-rose-500" />;
- return <AlertCircle className="w-3.5 h-3.5 text-slate-400" />;
+ return <XCircle className="h-3.5 w-3.5 text-rose-500" />;
+ return <AlertCircle className="h-3.5 w-3.5 text-[var(--muted-foreground)]" />;
};
return (
- <div className="bg-white dark:bg-slate-800 rounded-t-2xl border border-b-0 border-slate-200 dark:border-slate-700 flex flex-col shrink-0">
- <div className="flex items-center gap-2 px-3 pt-2 pb-1">
+ <div className="flex shrink-0 flex-col rounded-t-2xl border border-b-0 border-[var(--border)] bg-[var(--card)]">
+ <div className="flex items-center gap-2 px-3 pb-1 pt-2">
<div
ref={scrollRef}
- className="flex-1 flex items-center gap-1 overflow-x-auto scrollbar-hide"
+ className="scrollbar-hide flex flex-1 items-center gap-1 overflow-x-auto"
>
{sessionState.knowledge_points.map((knowledge, index) => {
const isCurrent = sessionState.current_index === index;
@@ -93,12 +93,12 @@ export default function KnowledgeTabBar({
}}
disabled={!isReady && !isFailed}
title={knowledge.knowledge_title}
- className={`shrink-0 inline-flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-xs font-medium transition whitespace-nowrap ${
+ className={`inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-lg px-2.5 py-1.5 text-xs font-medium transition-colors ${
isCurrent && !isCompleted
- ? "bg-indigo-100 text-indigo-700 dark:bg-indigo-900/40 dark:text-indigo-200"
+ ? "bg-[var(--primary)]/12 text-[var(--primary)]"
: isReady
- ? "bg-slate-100 text-slate-700 hover:bg-slate-200 dark:bg-slate-700 dark:text-slate-200 dark:hover:bg-slate-600"
- : "bg-slate-50 text-slate-400 dark:bg-slate-800 dark:text-slate-500 cursor-default"
+ ? "bg-[var(--muted)] text-[var(--foreground)] hover:bg-[var(--muted)]/80"
+ : "cursor-default bg-[var(--muted)]/40 text-[var(--muted-foreground)]"
}`}
>
{renderStatusIcon(index)}
@@ -110,29 +110,29 @@ export default function KnowledgeTabBar({
<button
ref={isCompleted ? activeRef : null}
onClick={onShowSummary}
- className={`shrink-0 inline-flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-xs font-medium transition whitespace-nowrap ${
+ className={`inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-lg px-2.5 py-1.5 text-xs font-medium transition-colors ${
isCompleted
- ? "bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-200"
- : "bg-slate-100 text-slate-700 hover:bg-slate-200 dark:bg-slate-700 dark:text-slate-200 dark:hover:bg-slate-600"
+ ? "bg-emerald-500/15 text-emerald-700 dark:text-emerald-300"
+ : "bg-[var(--muted)] text-[var(--foreground)] hover:bg-[var(--muted)]/80"
}`}
>
- <CheckCircle2 className="w-3.5 h-3.5 text-emerald-500" />
+ <CheckCircle2 className="h-3.5 w-3.5 text-emerald-500" />
<span>{t("Summary")}</span>
</button>
)}
</div>
- <div className="shrink-0 flex items-center gap-1.5 pl-2 border-l border-slate-200 dark:border-slate-700">
+ <div className="flex shrink-0 items-center gap-1.5 border-l border-[var(--border)] pl-2">
{canStart && (
<button
onClick={onStartLearning}
disabled={isLoading}
- className="inline-flex items-center gap-1 rounded-lg bg-indigo-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-indigo-700 disabled:opacity-50 transition"
+ className="btn-primary inline-flex items-center gap-1 rounded-lg bg-[var(--primary)] px-3 py-1.5 text-xs font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90 disabled:opacity-50"
>
{isLoading ? (
- <Loader2 className="w-3.5 h-3.5 animate-spin" />
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
- <Play className="w-3.5 h-3.5" />
+ <Play className="h-3.5 w-3.5" />
)}
{t("Start")}
</button>
@@ -142,12 +142,12 @@ export default function KnowledgeTabBar({
<button
onClick={onCompleteLearning}
disabled={isLoading || !allPagesReady}
- className="inline-flex items-center gap-1 rounded-lg bg-purple-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-purple-700 disabled:opacity-50 transition"
+ className="inline-flex items-center gap-1 rounded-lg bg-emerald-600 px-3 py-1.5 text-xs font-medium text-white transition-colors hover:bg-emerald-700 disabled:opacity-50 dark:bg-emerald-500 dark:hover:bg-emerald-400"
>
{isLoading ? (
- <Loader2 className="w-3.5 h-3.5 animate-spin" />
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
- <CheckCircle2 className="w-3.5 h-3.5" />
+ <CheckCircle2 className="h-3.5 w-3.5" />
)}
{t("Complete")}
</button>
@@ -155,16 +155,17 @@ export default function KnowledgeTabBar({
<button
onClick={onResetSession}
- className="inline-flex items-center gap-1 rounded-lg bg-slate-200 px-2.5 py-1.5 text-xs font-medium text-slate-700 hover:bg-slate-300 dark:bg-slate-700 dark:text-slate-200 dark:hover:bg-slate-600 transition"
+ className="inline-flex items-center gap-1 rounded-lg bg-[var(--muted)] px-2.5 py-1.5 text-xs font-medium text-[var(--foreground)] transition-colors hover:bg-[var(--muted)]/70"
+ title={t("Reset session")}
>
- <RotateCcw className="w-3.5 h-3.5" />
+ <RotateCcw className="h-3.5 w-3.5" />
</button>
</div>
</div>
- <div className="h-1 bg-slate-100 dark:bg-slate-700 mx-3 mb-1 rounded-full overflow-hidden">
+ <div className="mx-3 mb-1 h-1 overflow-hidden rounded-full bg-[var(--muted)]">
<div
- className="h-full bg-gradient-to-r from-indigo-500 to-purple-500 rounded-full transition-all duration-500"
+ className="h-full rounded-full bg-[var(--primary)] transition-all duration-500"
style={{
width: `${totalCount > 0 ? (readyCount / totalCount) * 100 : 0}%`,
}}
diff --git a/web/app/(workspace)/guide/components/NotebookSelector.tsx b/web/app/(workspace)/guide/components/NotebookSelector.tsx
index 2544c16ed..f46a90b5b 100644
--- a/web/app/(workspace)/guide/components/NotebookSelector.tsx
+++ b/web/app/(workspace)/guide/components/NotebookSelector.tsx
@@ -5,6 +5,7 @@ import {
ChevronRight,
ChevronDown,
Check,
+ NotebookPen,
} from "lucide-react";
import {
Notebook,
@@ -54,29 +55,34 @@ export default function NotebookSelector({
const { t } = useTranslation();
return (
- <div className="flex flex-col overflow-hidden rounded-[18px] border border-slate-200 bg-white shadow-sm dark:border-slate-800 dark:bg-slate-900">
- <div className="flex items-center justify-between border-b border-slate-100 bg-white px-4 py-4 dark:border-slate-800 dark:bg-slate-900">
- <h2 className="flex items-center gap-2 font-bold text-slate-900 dark:text-slate-100">
+ <div className="flex flex-col overflow-hidden rounded-2xl border border-[var(--border)] bg-[var(--card)] shadow-sm">
+ <div className="flex items-center justify-between border-b border-[var(--border)] bg-[var(--card)] px-4 py-3.5">
+ <h2 className="flex items-center gap-2 text-[14px] font-semibold text-[var(--foreground)]">
+ <NotebookPen className="h-3.5 w-3.5 text-[var(--muted-foreground)]" />
{t("Select Source (Cross-Notebook)")}
</h2>
{selectedRecords.size > 0 && (
<button
onClick={onClearAll}
- className="text-xs text-slate-500 dark:text-slate-400 hover:text-red-600 dark:hover:text-red-400"
+ className="rounded-md px-2 py-1 text-xs text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--destructive)]"
>
{t("Clear")} ({selectedRecords.size})
</button>
)}
</div>
- <div className="flex-1 overflow-y-auto max-h-[460px] px-2 py-2">
+ <div className="max-h-[460px] flex-1 overflow-y-auto px-2 py-2">
{loadingNotebooks ? (
- <div className="flex items-center justify-center py-8">
- <Loader2 className="h-5 w-5 animate-spin text-slate-400" />
+ <div className="flex items-center justify-center py-10">
+ <Loader2 className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" />
</div>
) : notebooks.length === 0 ? (
- <div className="p-4 text-center text-sm text-slate-400 dark:text-slate-500">
- {t("No notebooks with records found")}
+ <div className="flex flex-col items-center gap-2 px-4 py-10 text-center text-sm text-[var(--muted-foreground)]">
+ <NotebookPen className="h-5 w-5 text-[var(--muted-foreground)]/60" />
+ <span>{t("No notebooks with records found")}</span>
+ <span className="text-[11px] text-[var(--muted-foreground)]/80">
+ {t("Save a chat or guided learning result first to populate a notebook.")}
+ </span>
</div>
) : (
<div className="space-y-2">
@@ -91,51 +97,56 @@ export default function NotebookSelector({
return (
<div
key={notebook.id}
- className="overflow-hidden rounded-xl border border-slate-200 bg-white dark:border-slate-800 dark:bg-slate-900"
+ className="overflow-hidden rounded-xl border border-[var(--border)] bg-[var(--background)]/60"
>
{/* Notebook Header */}
- <div
- className="flex cursor-pointer items-center gap-2 px-3 py-3 transition-colors hover:bg-slate-50 dark:hover:bg-slate-800/70"
+ <button
+ type="button"
+ className="flex w-full cursor-pointer items-center gap-2 px-3 py-2.5 text-left transition-colors hover:bg-[var(--muted)]/50"
onClick={() => onToggleExpanded(notebook.id)}
>
{isExpanded ? (
- <ChevronDown className="w-4 h-4 text-slate-400 dark:text-slate-500" />
+ <ChevronDown className="h-3.5 w-3.5 text-[var(--muted-foreground)]" />
) : (
- <ChevronRight className="w-4 h-4 text-slate-400 dark:text-slate-500" />
+ <ChevronRight className="h-3.5 w-3.5 text-[var(--muted-foreground)]" />
)}
- <span className="flex-1 text-sm font-medium text-slate-700 dark:text-slate-200 truncate">
+ <span
+ className="h-2 w-2 shrink-0 rounded-full"
+ style={{ backgroundColor: notebook.color || "var(--primary)" }}
+ />
+ <span className="flex-1 truncate text-[13px] font-medium text-[var(--foreground)]">
{notebook.name}
</span>
- <span className="text-xs text-slate-400 dark:text-slate-500">
+ <span className="text-[11px] tabular-nums text-[var(--muted-foreground)]">
{selectedFromThis > 0 && (
- <span className="font-medium text-slate-700 dark:text-slate-300">
+ <span className="font-medium text-[var(--primary)]">
{selectedFromThis}/
</span>
)}
{notebook.record_count}
</span>
- </div>
+ </button>
{/* Records List */}
{isExpanded && (
- <div className="bg-slate-50/70 pb-3 pl-6 pr-3 dark:bg-slate-950/30">
+ <div className="border-t border-[var(--border)] bg-[var(--background)]/30 px-3 pb-3 pt-2">
{isLoadingRecords ? (
<div className="flex items-center justify-center py-4">
- <Loader2 className="h-4 w-4 animate-spin text-slate-400" />
+ <Loader2 className="h-4 w-4 animate-spin text-[var(--muted-foreground)]" />
</div>
) : records.length === 0 ? (
- <div className="py-2 text-xs text-slate-400 dark:text-slate-500 text-center">
+ <div className="py-3 text-center text-[12px] text-[var(--muted-foreground)]">
{t("No records")}
</div>
) : (
<>
- <div className="flex gap-2 mb-2">
+ <div className="mb-2 flex gap-3 text-[11px]">
<button
onClick={(e) => {
e.stopPropagation();
onSelectAll(notebook.id, notebook.name);
}}
- className="text-xs text-slate-600 hover:text-slate-800 dark:text-slate-400 dark:hover:text-slate-200"
+ className="text-[var(--primary)] transition-colors hover:opacity-80"
>
{t("Select All")}
</button>
@@ -144,59 +155,64 @@ export default function NotebookSelector({
e.stopPropagation();
onDeselectAll(notebook.id);
}}
- className="text-xs text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-300"
+ className="text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"
>
{t("Deselect")}
</button>
</div>
- <div className="space-y-2">
- {records.map((record) => (
- <div
- key={record.id}
- onClick={(e) => {
- e.stopPropagation();
- onToggleRecord(
- record,
- notebook.id,
- notebook.name,
- );
- }}
- className={`cursor-pointer rounded-lg border p-3 transition-all ${
- selectedRecords.has(record.id)
- ? "border-slate-300 bg-slate-50 dark:border-slate-700 dark:bg-slate-800/60"
- : "border-transparent hover:border-slate-200 hover:bg-white dark:hover:border-slate-700 dark:hover:bg-slate-800/75"
- }`}
- >
- <div className="flex items-center gap-2">
- <div
- className={`w-4 h-4 rounded border flex items-center justify-center shrink-0 ${
- selectedRecords.has(record.id)
- ? "border-slate-700 bg-slate-700 text-white dark:border-slate-200 dark:bg-slate-200 dark:text-slate-900"
- : "border-slate-300 dark:border-slate-500"
- }`}
- >
- {selectedRecords.has(record.id) && (
- <Check className="w-2.5 h-2.5" />
- )}
- </div>
- <div className="flex-1 min-w-0">
- <span
- className={`rounded border px-1.5 py-0.5 text-[10px] font-bold uppercase ${getTypeColor(record.type)}`}
+ <div className="space-y-1.5">
+ {records.map((record) => {
+ const isSelected = selectedRecords.has(record.id);
+ return (
+ <div
+ key={record.id}
+ onClick={(e) => {
+ e.stopPropagation();
+ onToggleRecord(
+ record,
+ notebook.id,
+ notebook.name,
+ );
+ }}
+ className={`cursor-pointer rounded-lg border p-2.5 transition-all ${
+ isSelected
+ ? "border-[var(--primary)]/40 bg-[var(--primary)]/8"
+ : "border-transparent hover:border-[var(--border)] hover:bg-[var(--muted)]/40"
+ }`}
+ >
+ <div className="flex items-start gap-2">
+ <div
+ className={`mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded border transition-colors ${
+ isSelected
+ ? "border-[var(--primary)] bg-[var(--primary)] text-[var(--primary-foreground)]"
+ : "border-[var(--border)]"
+ }`}
>
- {record.type}
- </span>
- <span className="ml-2 truncate text-xs text-slate-700 dark:text-slate-200">
- {record.title}
- </span>
- {record.summary && (
- <p className="mt-2 line-clamp-2 text-[11px] leading-5 text-slate-500 dark:text-slate-400">
- {record.summary}
- </p>
- )}
+ {isSelected && (
+ <Check className="h-2.5 w-2.5" />
+ )}
+ </div>
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-2">
+ <span
+ className={`shrink-0 rounded border px-1.5 py-0.5 text-[10px] font-bold uppercase ${getTypeColor(record.type)}`}
+ >
+ {record.type}
+ </span>
+ <span className="truncate text-[12px] text-[var(--foreground)]">
+ {record.title}
+ </span>
+ </div>
+ {record.summary && (
+ <p className="mt-1.5 line-clamp-2 text-[11px] leading-5 text-[var(--muted-foreground)]">
+ {record.summary}
+ </p>
+ )}
+ </div>
</div>
</div>
- </div>
- ))}
+ );
+ })}
</div>
</>
)}
@@ -209,16 +225,16 @@ export default function NotebookSelector({
)}
</div>
- {/* Generate Button */}
- <div className="border-t border-slate-100 bg-white p-4 dark:border-slate-800 dark:bg-slate-900">
+ {/* Generate / Apply Button */}
+ <div className="border-t border-[var(--border)] bg-[var(--card)] p-4">
<button
onClick={onCreateSession}
disabled={isLoading || selectedRecords.size === 0}
- className="flex w-full items-center justify-center gap-2 rounded-xl bg-[var(--primary)] px-4 py-2.5 font-medium text-[var(--primary-foreground)] transition disabled:cursor-not-allowed disabled:opacity-50"
+ className="btn-primary flex w-full items-center justify-center gap-2 rounded-xl bg-[var(--primary)] px-4 py-2.5 text-[13px] font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-40"
>
{isLoading ? (
<>
- <Loader2 className="w-4 h-4 animate-spin" />
+ <Loader2 className="h-4 w-4 animate-spin" />
{t("Generating...")}
</>
) : (
diff --git a/web/app/(workspace)/guide/components/ProgressPanel.tsx b/web/app/(workspace)/guide/components/ProgressPanel.tsx
index a0016349d..bb6d3d896 100644
--- a/web/app/(workspace)/guide/components/ProgressPanel.tsx
+++ b/web/app/(workspace)/guide/components/ProgressPanel.tsx
@@ -45,40 +45,40 @@ export default function ProgressPanel({
const status = sessionState.page_statuses[knowledgeIndex];
if (status === "ready") {
- return <CheckCircle2 className="w-4 h-4 text-emerald-500" />;
+ return <CheckCircle2 className="h-4 w-4 text-emerald-500" />;
}
if (status === "generating") {
- return <Loader2 className="w-4 h-4 text-indigo-500 animate-spin" />;
+ return <Loader2 className="h-4 w-4 animate-spin text-[var(--primary)]" />;
}
if (status === "failed") {
- return <XCircle className="w-4 h-4 text-rose-500" />;
+ return <XCircle className="h-4 w-4 text-rose-500" />;
}
- return <AlertCircle className="w-4 h-4 text-slate-400" />;
+ return <AlertCircle className="h-4 w-4 text-[var(--muted-foreground)]" />;
};
return (
- <div className="bg-white dark:bg-slate-800 p-4 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700">
- <div className="flex items-center justify-between mb-2 gap-3">
- <span className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider">
+ <div className="surface-card border border-[var(--border)] bg-[var(--card)] p-4 text-[var(--card-foreground)]">
+ <div className="mb-2 flex items-center justify-between gap-3">
+ <span className="text-xs font-semibold uppercase tracking-wider text-[var(--muted-foreground)]">
{t("Learning Progress")}
</span>
- <span className="text-xs text-slate-400 dark:text-slate-500">
+ <span className="text-xs text-[var(--muted-foreground)]">
{readyCount}/{totalCount} {t("pages ready")}
</span>
</div>
- <div className="h-2 bg-slate-100 dark:bg-slate-700 rounded-full overflow-hidden mb-4">
+ <div className="mb-4 h-2 overflow-hidden rounded-full bg-[var(--muted)]">
<div
- className="h-full bg-gradient-to-r from-indigo-500 to-purple-500 rounded-full transition-all duration-500"
+ className="h-full rounded-full bg-[var(--primary)] transition-all duration-500"
style={{ width: `${sessionState.progress}%` }}
/>
</div>
{totalCount > 0 && (
- <p className="text-xs text-slate-400 dark:text-slate-500 mb-4">
+ <p className="mb-4 text-xs text-[var(--muted-foreground)]">
{t("Open any page once it is ready. Early stages are prioritized.")}
</p>
)}
- <div className="space-y-2 mb-4">
+ <div className="mb-4 space-y-2">
{sessionState.knowledge_points.map((knowledge, index) => {
const status = sessionState.page_statuses[index] || "pending";
const isCurrent = sessionState.current_index === index;
@@ -88,10 +88,10 @@ export default function ProgressPanel({
return (
<div
key={`${knowledge.knowledge_title}-${index}`}
- className={`rounded-xl border px-3 py-3 transition ${
+ className={`rounded-xl border px-3 py-3 transition-colors ${
isCurrent
- ? "border-indigo-300 bg-indigo-50 dark:border-indigo-600 dark:bg-indigo-950/30"
- : "border-slate-200 bg-slate-50/70 dark:border-slate-700 dark:bg-slate-900/50"
+ ? "border-[var(--primary)]/40 bg-[var(--primary)]/8"
+ : "border-[var(--border)] bg-[var(--muted)]/30"
}`}
>
<div className="flex items-start justify-between gap-3">
@@ -99,12 +99,12 @@ export default function ProgressPanel({
onClick={() => onNavigate(index)}
className="flex-1 text-left"
>
- <div className="flex items-center gap-2 text-sm font-medium text-slate-800 dark:text-slate-100">
+ <div className="flex items-center gap-2 text-sm font-medium text-[var(--foreground)]">
{renderStatusIcon(index)}
<span>{index + 1}.</span>
<span className="line-clamp-2">{knowledge.knowledge_title}</span>
</div>
- <p className="mt-1 text-xs text-slate-500 dark:text-slate-400">
+ <p className="mt-1 text-xs text-[var(--muted-foreground)]">
{status === "ready"
? t("Ready to open")
: status === "generating"
@@ -118,18 +118,18 @@ export default function ProgressPanel({
{isFailed && (
<button
onClick={() => onRetryPage(index)}
- className="inline-flex items-center gap-1 rounded-lg border border-rose-200 px-2 py-1 text-xs text-rose-600 hover:bg-rose-50 dark:border-rose-800 dark:text-rose-300 dark:hover:bg-rose-950/30"
+ className="inline-flex items-center gap-1 rounded-lg border border-rose-300/50 bg-rose-500/8 px-2 py-1 text-xs text-rose-600 hover:bg-rose-500/15 dark:text-rose-300"
>
- <RotateCcw className="w-3 h-3" />
+ <RotateCcw className="h-3 w-3" />
{t("Retry")}
</button>
)}
{isReady && (
<button
onClick={() => onNavigate(index)}
- className="inline-flex items-center gap-1 rounded-lg border border-emerald-200 px-2 py-1 text-xs text-emerald-600 hover:bg-emerald-50 dark:border-emerald-800 dark:text-emerald-300 dark:hover:bg-emerald-950/30"
+ className="inline-flex items-center gap-1 rounded-lg border border-emerald-300/50 bg-emerald-500/8 px-2 py-1 text-xs text-emerald-600 hover:bg-emerald-500/15 dark:text-emerald-300"
>
- <Sparkles className="w-3 h-3" />
+ <Sparkles className="h-3 w-3" />
{t("Open")}
</button>
)}
@@ -144,16 +144,16 @@ export default function ProgressPanel({
<button
onClick={onStartLearning}
disabled={isLoading}
- className="flex-1 px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2 text-sm font-medium"
+ className="btn-primary flex flex-1 items-center justify-center gap-2 rounded-lg bg-[var(--primary)] px-4 py-2 text-sm font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-50"
>
{isLoading ? (
<>
- <Loader2 className="w-4 h-4 animate-spin" />
+ <Loader2 className="h-4 w-4 animate-spin" />
{t("Starting...")}
</>
) : (
<>
- <Play className="w-4 h-4" />
+ <Play className="h-4 w-4" />
{t("Start Learning")}
</>
)}
@@ -163,9 +163,9 @@ export default function ProgressPanel({
{!canStart && (
<button
onClick={onResetSession}
- className="flex-1 px-4 py-2 bg-slate-200 text-slate-800 rounded-lg hover:bg-slate-300 transition-colors flex items-center justify-center gap-2 text-sm font-medium dark:bg-slate-700 dark:text-slate-100 dark:hover:bg-slate-600"
+ className="flex flex-1 items-center justify-center gap-2 rounded-lg bg-[var(--muted)] px-4 py-2 text-sm font-medium text-[var(--foreground)] transition-colors hover:bg-[var(--muted)]/70"
>
- <RotateCcw className="w-4 h-4" />
+ <RotateCcw className="h-4 w-4" />
{t("New Session")}
</button>
)}
@@ -174,16 +174,16 @@ export default function ProgressPanel({
<button
onClick={onCompleteLearning}
disabled={isLoading || !allPagesReady}
- className="flex-1 px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2 text-sm font-medium"
+ className="flex flex-1 items-center justify-center gap-2 rounded-lg bg-emerald-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-emerald-700 disabled:cursor-not-allowed disabled:opacity-50 dark:bg-emerald-500 dark:hover:bg-emerald-400"
>
{isLoading ? (
<>
- <Loader2 className="w-4 h-4 animate-spin" />
+ <Loader2 className="h-4 w-4 animate-spin" />
{t("Generating Summary...")}
</>
) : (
<>
- <CheckCircle2 className="w-4 h-4" />
+ <CheckCircle2 className="h-4 w-4" />
{t("Complete Learning")}
</>
)}
diff --git a/web/app/(workspace)/guide/components/SessionHistoryList.tsx b/web/app/(workspace)/guide/components/SessionHistoryList.tsx
index 400756fde..c4d85fad0 100644
--- a/web/app/(workspace)/guide/components/SessionHistoryList.tsx
+++ b/web/app/(workspace)/guide/components/SessionHistoryList.tsx
@@ -21,23 +21,23 @@ function StatusBadge({ status }: { status: string }) {
const { t } = useTranslation();
if (status === "completed") {
return (
- <span className="inline-flex items-center gap-1 rounded-full bg-emerald-100 px-2 py-0.5 text-[11px] font-semibold text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300">
- <CheckCircle2 className="w-3 h-3" />
+ <span className="inline-flex items-center gap-1 rounded-full bg-emerald-500/15 px-2 py-0.5 text-[11px] font-semibold text-emerald-700 dark:text-emerald-300">
+ <CheckCircle2 className="h-3 w-3" />
{t("Completed")}
</span>
);
}
if (status === "learning") {
return (
- <span className="inline-flex items-center gap-1 rounded-full bg-blue-100 px-2 py-0.5 text-[11px] font-semibold text-blue-700 dark:bg-blue-900/40 dark:text-blue-300">
- <BookOpen className="w-3 h-3" />
+ <span className="inline-flex items-center gap-1 rounded-full bg-[var(--primary)]/12 px-2 py-0.5 text-[11px] font-semibold text-[var(--primary)]">
+ <BookOpen className="h-3 w-3" />
{t("In Progress")}
</span>
);
}
return (
- <span className="inline-flex items-center gap-1 rounded-full bg-slate-100 px-2 py-0.5 text-[11px] font-semibold text-slate-600 dark:bg-slate-700 dark:text-slate-300">
- <FileText className="w-3 h-3" />
+ <span className="inline-flex items-center gap-1 rounded-full bg-[var(--muted)] px-2 py-0.5 text-[11px] font-semibold text-[var(--muted-foreground)]">
+ <FileText className="h-3 w-3" />
{t("Planned")}
</span>
);
@@ -52,8 +52,8 @@ export default function SessionHistoryList({
if (loading) {
return (
- <div className="flex-1 flex flex-col items-center justify-center text-slate-400 dark:text-slate-500 p-8">
- <Loader2 className="w-8 h-8 animate-spin mb-3" />
+ <div className="flex flex-1 flex-col items-center justify-center p-8 text-[var(--muted-foreground)]">
+ <Loader2 className="mb-3 h-8 w-8 animate-spin" />
<p className="text-sm">{t("Loading history...")}</p>
</div>
);
@@ -61,12 +61,12 @@ export default function SessionHistoryList({
if (sessions.length === 0) {
return (
- <div className="flex-1 flex flex-col items-center justify-center text-slate-300 dark:text-slate-600 p-8">
- <GraduationCap className="w-20 h-20 mb-4" />
- <h3 className="text-base font-medium text-slate-500 dark:text-slate-400 mb-1">
+ <div className="flex flex-1 flex-col items-center justify-center p-8 text-[var(--muted-foreground)]">
+ <GraduationCap className="mb-4 h-20 w-20 text-[var(--muted-foreground)]/40" />
+ <h3 className="mb-1 text-base font-medium text-[var(--foreground)]">
{t("No learning history yet")}
</h3>
- <p className="text-sm text-slate-400 dark:text-slate-500 text-center max-w-sm">
+ <p className="max-w-sm text-center text-sm">
{t(
"Describe what you want to learn on the left, and your guided learning sessions will appear here.",
)}
@@ -77,34 +77,34 @@ export default function SessionHistoryList({
return (
<div className="flex-1 overflow-y-auto p-4">
- <h3 className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-3">
+ <h3 className="mb-3 text-xs font-semibold uppercase tracking-wider text-[var(--muted-foreground)]">
{t("Learning History")}
</h3>
- <div className="grid gap-3 grid-cols-1 sm:grid-cols-2">
+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
{sessions.map((session) => (
<button
key={session.session_id}
onClick={() => onLoadSession(session.session_id)}
- className="text-left rounded-xl border border-slate-200 bg-white p-4 shadow-sm hover:shadow-md hover:border-indigo-200 transition dark:border-slate-700 dark:bg-slate-800 dark:hover:border-indigo-700"
+ className="rounded-xl border border-[var(--border)] bg-[var(--card)] p-4 text-left shadow-sm transition-all hover:-translate-y-0.5 hover:border-[var(--primary)]/40 hover:shadow-md"
>
- <p className="text-sm font-medium text-slate-800 dark:text-slate-100 line-clamp-2 mb-2">
+ <p className="mb-2 line-clamp-2 text-sm font-medium text-[var(--foreground)]">
{session.topic || t("Untitled")}
</p>
- <div className="flex items-center gap-2 mb-2">
+ <div className="mb-2 flex items-center gap-2">
<StatusBadge status={session.status} />
- <span className="text-[10px] text-slate-400 dark:text-slate-500 flex items-center gap-0.5">
- <Clock className="w-3 h-3" />
+ <span className="flex items-center gap-0.5 text-[10px] text-[var(--muted-foreground)]">
+ <Clock className="h-3 w-3" />
{new Date(session.created_at * 1000).toLocaleDateString()}
</span>
</div>
<div className="flex items-center gap-2">
- <div className="flex-1 h-1.5 bg-slate-100 dark:bg-slate-700 rounded-full overflow-hidden">
+ <div className="h-1.5 flex-1 overflow-hidden rounded-full bg-[var(--muted)]">
<div
- className="h-full bg-gradient-to-r from-indigo-500 to-purple-500 rounded-full"
+ className="h-full rounded-full bg-[var(--primary)] transition-all"
style={{ width: `${session.progress}%` }}
/>
</div>
- <span className="text-[10px] text-slate-400 dark:text-slate-500 shrink-0">
+ <span className="shrink-0 text-[10px] text-[var(--muted-foreground)]">
{session.ready_count}/{session.total_points}
</span>
</div>
diff --git a/web/app/(workspace)/guide/components/SessionSwitcher.tsx b/web/app/(workspace)/guide/components/SessionSwitcher.tsx
index 166dbba95..e2ed786ca 100644
--- a/web/app/(workspace)/guide/components/SessionSwitcher.tsx
+++ b/web/app/(workspace)/guide/components/SessionSwitcher.tsx
@@ -25,23 +25,23 @@ function StatusBadge({ status }: { status: string }) {
const { t } = useTranslation();
if (status === "completed") {
return (
- <span className="inline-flex items-center gap-1 rounded-full bg-emerald-100 px-2 py-0.5 text-[10px] font-semibold text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300">
- <CheckCircle2 className="w-3 h-3" />
+ <span className="inline-flex items-center gap-1 rounded-full bg-emerald-500/15 px-2 py-0.5 text-[10px] font-semibold text-emerald-700 dark:text-emerald-300">
+ <CheckCircle2 className="h-3 w-3" />
{t("Completed")}
</span>
);
}
if (status === "learning") {
return (
- <span className="inline-flex items-center gap-1 rounded-full bg-blue-100 px-2 py-0.5 text-[10px] font-semibold text-blue-700 dark:bg-blue-900/40 dark:text-blue-300">
- <BookOpen className="w-3 h-3" />
+ <span className="inline-flex items-center gap-1 rounded-full bg-[var(--primary)]/12 px-2 py-0.5 text-[10px] font-semibold text-[var(--primary)]">
+ <BookOpen className="h-3 w-3" />
{t("In Progress")}
</span>
);
}
return (
- <span className="inline-flex items-center gap-1 rounded-full bg-slate-100 px-2 py-0.5 text-[10px] font-semibold text-slate-600 dark:bg-slate-700 dark:text-slate-300">
- <FileText className="w-3 h-3" />
+ <span className="inline-flex items-center gap-1 rounded-full bg-[var(--muted)] px-2 py-0.5 text-[10px] font-semibold text-[var(--muted-foreground)]">
+ <FileText className="h-3 w-3" />
{t("Planned")}
</span>
);
@@ -80,21 +80,21 @@ export default function SessionSwitcher({
<div ref={containerRef} className="relative shrink-0">
<button
onClick={() => setOpen(!open)}
- className="w-full flex items-center gap-2 rounded-xl border border-slate-200 bg-white px-3 py-2 text-left transition hover:bg-slate-50 dark:border-slate-700 dark:bg-slate-800 dark:hover:bg-slate-750"
+ className="flex w-full items-center gap-2 rounded-xl border border-[var(--border)] bg-[var(--card)] px-3 py-2 text-left transition-colors hover:bg-[var(--muted)]/40"
>
- <div className="flex-1 min-w-0">
- <p className="text-sm font-medium text-slate-800 dark:text-slate-100 truncate">
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-sm font-medium text-[var(--foreground)]">
{currentTopic || t("Untitled Session")}
</p>
<StatusBadge status={currentStatus} />
</div>
<ChevronDown
- className={`w-4 h-4 text-slate-400 shrink-0 transition-transform ${open ? "rotate-180" : ""}`}
+ className={`h-4 w-4 shrink-0 text-[var(--muted-foreground)] transition-transform ${open ? "rotate-180" : ""}`}
/>
</button>
{open && (
- <div className="absolute left-0 right-0 top-full mt-1 z-30 rounded-xl border border-slate-200 bg-white shadow-lg dark:border-slate-700 dark:bg-slate-800 max-h-64 overflow-y-auto">
+ <div className="absolute left-0 right-0 top-full z-30 mt-1 max-h-64 overflow-y-auto rounded-xl border border-[var(--border)] bg-[var(--popover)] text-[var(--popover-foreground)] shadow-lg">
{otherSessions.length > 0 && (
<div className="py-1">
{otherSessions.map((session) => (
@@ -104,16 +104,16 @@ export default function SessionSwitcher({
onLoadSession(session.session_id);
setOpen(false);
}}
- className="w-full flex items-center gap-2 px-3 py-2 text-left hover:bg-slate-50 dark:hover:bg-slate-700/50 transition"
+ className="flex w-full items-center gap-2 px-3 py-2 text-left transition-colors hover:bg-[var(--muted)]/60"
>
- <div className="flex-1 min-w-0">
- <p className="text-xs font-medium text-slate-700 dark:text-slate-200 truncate">
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-xs font-medium text-[var(--foreground)]">
{session.topic || t("Untitled")}
</p>
- <div className="flex items-center gap-2 mt-0.5">
+ <div className="mt-0.5 flex items-center gap-2">
<StatusBadge status={session.status} />
- <span className="text-[10px] text-slate-400 flex items-center gap-0.5">
- <Clock className="w-3 h-3" />
+ <span className="flex items-center gap-0.5 text-[10px] text-[var(--muted-foreground)]">
+ <Clock className="h-3 w-3" />
{new Date(session.created_at * 1000).toLocaleDateString()}
</span>
</div>
@@ -122,15 +122,15 @@ export default function SessionSwitcher({
))}
</div>
)}
- <div className="border-t border-slate-200 dark:border-slate-700 p-2">
+ <div className="border-t border-[var(--border)] p-2">
<button
onClick={() => {
onNewSession();
setOpen(false);
}}
- className="w-full flex items-center justify-center gap-1.5 rounded-lg bg-indigo-50 px-3 py-2 text-xs font-medium text-indigo-700 hover:bg-indigo-100 dark:bg-indigo-900/30 dark:text-indigo-300 dark:hover:bg-indigo-900/50 transition"
+ className="flex w-full items-center justify-center gap-1.5 rounded-lg bg-[var(--primary)]/10 px-3 py-2 text-xs font-medium text-[var(--primary)] transition-colors hover:bg-[var(--primary)]/18"
>
- <Plus className="w-3.5 h-3.5" />
+ <Plus className="h-3.5 w-3.5" />
{t("New Session")}
</button>
</div>
diff --git a/web/app/(workspace)/guide/hooks/useNotebookSelection.ts b/web/app/(workspace)/guide/hooks/useNotebookSelection.ts
index 4e1d6a9ea..eae25e87d 100644
--- a/web/app/(workspace)/guide/hooks/useNotebookSelection.ts
+++ b/web/app/(workspace)/guide/hooks/useNotebookSelection.ts
@@ -1,9 +1,13 @@
import { useState, useCallback } from "react";
-import { listCategories, listNotebookEntries } from "@/lib/notebook-api";
+import { listNotebooks, getNotebook } from "@/lib/notebook-api";
import { Notebook, NotebookRecord, SelectedRecord } from "../types";
/**
- * Hook for managing notebook and record selection
+ * Hook for managing notebook and record selection.
+ *
+ * Backed by the real notebook system (`/api/v1/notebook/*`) so that records
+ * saved via Save-to-Notebook from any surface are immediately discoverable
+ * here as references.
*/
export function useNotebookSelection() {
const [notebooks, setNotebooks] = useState<Notebook[]>([]);
@@ -22,23 +26,25 @@ export function useNotebookSelection() {
);
const fetchNotebooks = useCallback(async () => {
+ setLoadingNotebooks(true);
try {
- const categories = await listCategories();
- const notebooksWithRecords = categories
- .filter((cat) => (cat.entry_count ?? 0) > 0)
+ const data = await listNotebooks();
+ const items = data
+ .filter((nb) => (nb.record_count ?? 0) > 0)
.map(
- (cat): Notebook => ({
- id: String(cat.id),
- name: cat.name,
- description: "",
- record_count: cat.entry_count ?? 0,
- color: "",
+ (nb): Notebook => ({
+ id: String(nb.id),
+ name: nb.name,
+ description: nb.description ?? "",
+ record_count: nb.record_count ?? 0,
+ color: nb.color ?? "",
}),
);
- setNotebooks(notebooksWithRecords);
- setLoadingNotebooks(false);
+ setNotebooks(items);
} catch (err) {
console.error("Failed to fetch notebooks:", err);
+ setNotebooks([]);
+ } finally {
setLoadingNotebooks(false);
}
}, []);
@@ -53,15 +59,15 @@ export function useNotebookSelection() {
return newSet;
});
try {
- const data = await listNotebookEntries({ category_id: Number(notebookId) });
- const records = (data.items || []).map(
- (entry): NotebookRecord => ({
- id: String(entry.id),
- title: entry.question,
- summary: entry.explanation,
- user_query: entry.question,
- output: entry.correct_answer,
- type: entry.question_type,
+ const detail = await getNotebook(notebookId);
+ const records = (detail.records || []).map(
+ (rec): NotebookRecord => ({
+ id: String(rec.id),
+ title: rec.title,
+ summary: rec.summary,
+ user_query: rec.user_query,
+ output: rec.output,
+ type: String(rec.type),
}),
);
setNotebookRecordsMap((prev) =>
diff --git a/web/app/(workspace)/guide/page.tsx b/web/app/(workspace)/guide/page.tsx
index 0777d49e4..d6309c2b1 100644
--- a/web/app/(workspace)/guide/page.tsx
+++ b/web/app/(workspace)/guide/page.tsx
@@ -171,20 +171,20 @@ export default function GuidePage() {
}}
>
{isIdle ? (
- <div className="bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 flex flex-col overflow-hidden">
- <div className="p-3 border-b border-slate-100 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-800/50">
- <h2 className="font-bold text-slate-900 dark:text-slate-100 flex items-center gap-2">
- <Sparkles className="w-5 h-5 text-indigo-600 dark:text-indigo-400" />
+ <div className="surface-card flex flex-col overflow-hidden border border-[var(--border)] bg-[var(--card)] text-[var(--card-foreground)]">
+ <div className="border-b border-[var(--border)] bg-[var(--muted)]/35 p-3">
+ <h2 className="flex items-center gap-2 font-semibold text-[var(--foreground)]">
+ <Sparkles className="h-5 w-5 text-[var(--primary)]" />
{t("Describe what you want to learn")}
</h2>
- <p className="mt-2 text-sm text-slate-500 dark:text-slate-400">
+ <p className="mt-2 text-sm text-[var(--muted-foreground)]">
{t(
"Write a short learning request, and the system will design a progressive guided learning plan for you.",
)}
</p>
</div>
- <div className="p-4 space-y-4">
+ <div className="space-y-4 p-4">
<textarea
value={topicInput}
onChange={(e) => setTopicInput(e.target.value)}
@@ -192,35 +192,45 @@ export default function GuidePage() {
"For example: Teach me linear algebra from the basics, with intuition, key formulas, and common mistakes.",
)}
rows={8}
- className="w-full resize-none rounded-xl border border-slate-200 bg-white px-4 py-3 text-sm text-slate-700 outline-none transition focus:border-indigo-400 focus:ring-2 focus:ring-indigo-100 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-100 dark:focus:ring-indigo-900/40"
+ className="w-full resize-none rounded-xl border border-[var(--border)] bg-[var(--card)] px-4 py-3 text-sm text-[var(--foreground)] outline-none transition placeholder:text-[var(--muted-foreground)] focus:border-[var(--primary)]/50 focus:ring-2 focus:ring-[var(--primary)]/15"
/>
- <div className="rounded-xl border border-slate-200 bg-slate-50/70 p-4 dark:border-slate-700 dark:bg-slate-900/50">
- <div className="flex items-center justify-between gap-3">
- <div>
- <div className="text-sm font-medium text-slate-800 dark:text-slate-100">
- {t("Notebook Context")}
- </div>
- <p className="mt-1 text-xs text-slate-500 dark:text-slate-400">
- {t("Optionally ground the learning plan with saved notebook records.")}
- </p>
+ <div className="rounded-xl border border-[var(--border)] bg-[var(--muted)]/30 p-3.5">
+ <div className="flex items-center justify-between gap-2">
+ <div className="inline-flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.14em] text-[var(--primary)]">
+ <BookOpen className="h-3 w-3" />
+ {t("Notebook Context")}
</div>
- <button
- onClick={() => setShowNotebookPicker(true)}
- className="inline-flex items-center gap-2 rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs font-medium text-slate-700 transition hover:bg-slate-100 dark:border-slate-700 dark:bg-slate-950 dark:text-slate-200 dark:hover:bg-slate-800"
- >
- <BookOpen className="h-4 w-4" />
- {t("Select Records")}
- </button>
+ <span className="rounded-full bg-[var(--muted)] px-2 py-0.5 text-[9px] font-medium uppercase tracking-wider text-[var(--muted-foreground)]">
+ {t("Optional")}
+ </span>
</div>
+ <p className="mt-1.5 text-xs leading-relaxed text-[var(--muted-foreground)]">
+ {t("Ground the plan with saved notebook records.")}
+ </p>
+ <button
+ onClick={() => setShowNotebookPicker(true)}
+ className="mt-3 inline-flex w-full items-center justify-center gap-2 whitespace-nowrap rounded-lg border border-dashed border-[var(--border)] bg-[var(--card)] px-3 py-2 text-xs font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--primary)]/50 hover:bg-[var(--primary)]/8 hover:text-[var(--primary)]"
+ >
+ <BookOpen className="h-3.5 w-3.5" />
+ {selectedNotebookRecords.length > 0
+ ? t("Update selection ({n})", {
+ n: selectedNotebookRecords.length,
+ })
+ : t("Select records")}
+ </button>
{notebookReferenceGroups.length > 0 && (
- <div className="mt-3 flex flex-wrap gap-2">
+ <div className="mt-2.5 flex flex-wrap gap-1.5">
{notebookReferenceGroups.map((group) => (
<span
key={group.notebookId}
- className="inline-flex items-center gap-2 rounded-full border border-slate-200 bg-white px-3 py-1 text-[11px] text-slate-700 dark:border-slate-700 dark:bg-slate-950 dark:text-slate-200"
+ className="inline-flex max-w-full items-center gap-1.5 truncate rounded-full border border-[var(--border)] bg-[var(--card)] px-2.5 py-0.5 text-[11px] text-[var(--foreground)]"
+ title={`${group.notebookName} (${group.count})`}
>
- {group.notebookName} ({group.count})
+ <span className="truncate">{group.notebookName}</span>
+ <span className="shrink-0 text-[var(--muted-foreground)]">
+ {group.count}
+ </span>
</span>
))}
</div>
@@ -230,12 +240,12 @@ export default function GuidePage() {
<button
onClick={handleCreateSession}
disabled={isLoading || !topicInput.trim()}
- className="inline-flex items-center gap-2 rounded-xl bg-indigo-600 px-4 py-2.5 text-sm font-medium text-white transition hover:bg-indigo-500 disabled:cursor-not-allowed disabled:opacity-60"
+ className="btn-primary inline-flex items-center gap-2 rounded-xl bg-[var(--primary)] px-4 py-2.5 text-sm font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-50"
>
{isLoading ? (
- <Loader2 className="w-4 h-4 animate-spin" />
+ <Loader2 className="h-4 w-4 animate-spin" />
) : (
- <Sparkles className="w-4 h-4" />
+ <Sparkles className="h-4 w-4" />
)}
{t("Generate learning plan")}
</button>
@@ -246,7 +256,7 @@ export default function GuidePage() {
<div className="flex items-center justify-end">
<button
onClick={() => setShowSaveModal(true)}
- className="inline-flex items-center gap-2 rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm font-medium text-slate-700 transition hover:bg-slate-50 dark:border-slate-700 dark:bg-slate-800 dark:text-slate-200 dark:hover:bg-slate-700"
+ className="inline-flex items-center gap-2 rounded-xl border border-[var(--border)] bg-[var(--card)] px-3 py-2 text-sm font-medium text-[var(--foreground)] transition-colors hover:border-[var(--primary)]/40 hover:bg-[var(--primary)]/8 hover:text-[var(--primary)]"
>
<BookOpen className="h-4 w-4" />
{t("Add to Notebook")}
@@ -290,21 +300,21 @@ export default function GuidePage() {
<div className="absolute top-4 left-4 z-20 flex gap-2">
<button
onClick={() => setSidebarCollapsed(!sidebarCollapsed)}
- className="p-2 bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-600 rounded-lg shadow-sm hover:bg-slate-50 dark:hover:bg-slate-700 transition-all"
+ className="rounded-lg border border-[var(--border)] bg-[var(--card)] p-2 text-[var(--muted-foreground)] shadow-sm transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
title={
sidebarCollapsed ? t("Expand sidebar") : t("Collapse sidebar")
}
>
{sidebarCollapsed ? (
- <ChevronRight className="w-4 h-4 text-slate-600 dark:text-slate-300" />
+ <ChevronRight className="h-4 w-4" />
) : (
- <ChevronLeft className="w-4 h-4 text-slate-600 dark:text-slate-300" />
+ <ChevronLeft className="h-4 w-4" />
)}
</button>
{!sidebarCollapsed && (
<button
onClick={() => setSidebarWide(!sidebarWide)}
- className="p-2 bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-600 rounded-lg shadow-sm hover:bg-slate-50 dark:hover:bg-slate-700 transition-all"
+ className="rounded-lg border border-[var(--border)] bg-[var(--card)] p-2 text-[var(--muted-foreground)] shadow-sm transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
title={
sidebarWide
? t("Switch to narrow sidebar (1:3)")
@@ -312,7 +322,7 @@ export default function GuidePage() {
}
>
<ArrowRight
- className={`w-4 h-4 text-slate-600 dark:text-slate-300 transition-transform ${sidebarWide ? "rotate-180" : ""}`}
+ className={`h-4 w-4 transition-transform ${sidebarWide ? "rotate-180" : ""}`}
/>
</button>
)}
@@ -320,7 +330,7 @@ export default function GuidePage() {
)}
{isIdle ? (
- <div className="flex-1 bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 flex flex-col overflow-hidden">
+ <div className="surface-card flex flex-1 flex-col overflow-hidden border border-[var(--border)] bg-[var(--card)] text-[var(--card-foreground)]">
<SessionHistoryList
sessions={sessions}
loading={historyLoading}
@@ -388,11 +398,9 @@ export default function GuidePage() {
onOpenDebugModal={() => setShowDebugModal(true)}
/>
) : (
- <div className="h-full bg-white dark:bg-slate-800 rounded-b-2xl border border-t-0 border-slate-200 dark:border-slate-700 flex flex-col items-center justify-center text-slate-300 dark:text-slate-600 p-8">
- <Loader2 className="w-12 h-12 text-indigo-400 dark:text-indigo-500 animate-spin mb-4" />
- <p className="text-slate-500 dark:text-slate-400">
- {loadingMessage || t("Loading learning content...")}
- </p>
+ <div className="flex h-full flex-col items-center justify-center rounded-b-2xl border border-t-0 border-[var(--border)] bg-[var(--card)] p-8 text-[var(--muted-foreground)]">
+ <Loader2 className="mb-4 h-12 w-12 animate-spin text-[var(--primary)]" />
+ <p>{loadingMessage || t("Loading learning content...")}</p>
</div>
)}
</div>
diff --git a/web/app/globals.css b/web/app/globals.css
index e7daf9673..6433130c6 100644
--- a/web/app/globals.css
+++ b/web/app/globals.css
@@ -5,24 +5,24 @@
@layer base {
:root {
--background: #FAF9F6;
- --foreground: #2D2B28;
+ --foreground: #1F1D1B;
--card: #FFFFFF;
- --card-foreground: #2D2B28;
+ --card-foreground: #1F1D1B;
--popover: #FFFFFF;
- --popover-foreground: #2D2B28;
- --primary: #C35A2C;
+ --popover-foreground: #1F1D1B;
+ --primary: #B0501E;
--primary-foreground: #FFFFFF;
- --secondary: #F0EDE7;
- --secondary-foreground: #2D2B28;
- --muted: #F0EDE7;
- --muted-foreground: #8B8580;
- --accent: #F0EDE7;
- --accent-foreground: #2D2B28;
- --destructive: #D44A3C;
+ --secondary: #ECE7DD;
+ --secondary-foreground: #1F1D1B;
+ --muted: #ECE7DD;
+ --muted-foreground: #6B655F;
+ --accent: #ECE7DD;
+ --accent-foreground: #1F1D1B;
+ --destructive: #C53A2C;
--destructive-foreground: #FFFFFF;
- --border: #E8E4DE;
- --input: #E8E4DE;
- --ring: #C35A2C;
+ --border: #DBD4C8;
+ --input: #DBD4C8;
+ --ring: #B0501E;
}
.dark {
@@ -48,25 +48,25 @@
}
.theme-snow {
- --background: #FFFFFF;
- --foreground: #1E293B;
+ --background: #F8FAFC;
+ --foreground: #0F172A;
--card: #FFFFFF;
- --card-foreground: #1E293B;
+ --card-foreground: #0F172A;
--popover: #FFFFFF;
- --popover-foreground: #1E293B;
- --primary: #C35A2C;
+ --popover-foreground: #0F172A;
+ --primary: #B0501E;
--primary-foreground: #FFFFFF;
- --secondary: #F1F5F9;
- --secondary-foreground: #1E293B;
- --muted: #F1F5F9;
- --muted-foreground: #94A3B8;
- --accent: #F1F5F9;
- --accent-foreground: #1E293B;
- --destructive: #DC2626;
+ --secondary: #E8EEF5;
+ --secondary-foreground: #0F172A;
+ --muted: #E8EEF5;
+ --muted-foreground: #5A6B82;
+ --accent: #E8EEF5;
+ --accent-foreground: #0F172A;
+ --destructive: #C7281F;
--destructive-foreground: #FFFFFF;
- --border: #E2E8F0;
- --input: #E2E8F0;
- --ring: #C35A2C;
+ --border: #CBD5E1;
+ --input: #CBD5E1;
+ --ring: #B0501E;
}
.theme-glass {
diff --git a/web/components/chat/HistorySessionPicker.tsx b/web/components/chat/HistorySessionPicker.tsx
index 09e6a20b4..cb7cf7c7a 100644
--- a/web/components/chat/HistorySessionPicker.tsx
+++ b/web/components/chat/HistorySessionPicker.tsx
@@ -1,7 +1,7 @@
"use client";
import { useEffect, useMemo, useState } from "react";
-import { Check, Loader2, MessageSquare, Search, X } from "lucide-react";
+import { Check, History as HistoryIcon, Loader2, MessageSquare, Search, X } from "lucide-react";
import { useTranslation } from "react-i18next";
import { listSessions, type SessionSummary } from "@/lib/session-api";
@@ -16,9 +16,15 @@ interface HistorySessionPickerProps {
onApply: (sessions: SelectedHistorySession[]) => void;
}
-function formatTimestamp(value?: number) {
- if (!value) return "";
- return new Date(value).toLocaleString();
+/**
+ * Format a backend session timestamp (stored as float seconds via time.time())
+ * into a localized string. Returns an empty string when the timestamp is
+ * missing or non-positive so we don't render nonsensical 1970 dates.
+ */
+function formatSessionTimestamp(value?: number): string {
+ if (!value || value <= 0) return "";
+ // Backend stores REAL seconds. JS Date expects milliseconds.
+ return new Date(value * 1000).toLocaleString();
}
export default function HistorySessionPicker({
@@ -39,7 +45,7 @@ export default function HistorySessionPicker({
const load = async () => {
setLoading(true);
try {
- const data = await listSessions(200, 0);
+ const data = await listSessions(200, 0, { force: true });
if (!mounted) return;
setSessions(data);
} catch {
@@ -87,87 +93,101 @@ export default function HistorySessionPicker({
if (!open) return null;
return (
- <div className="fixed inset-0 z-[85] flex items-center justify-center bg-slate-950/55 p-4 backdrop-blur-md">
- <div className="w-full max-w-4xl overflow-hidden rounded-[22px] border border-slate-200 bg-white shadow-[0_22px_70px_rgba(15,23,42,0.24)] dark:border-slate-800 dark:bg-slate-900">
- <div className="flex items-center justify-between border-b border-slate-200 px-5 py-4 dark:border-slate-700">
- <div>
- <div className="text-[16px] font-semibold text-slate-900 dark:text-slate-100">
- {t("Select History Sessions")}
+ <div className="fixed inset-0 z-[85] flex items-center justify-center bg-[var(--background)]/65 p-4 backdrop-blur-md">
+ <div className="surface-card w-full max-w-4xl overflow-hidden rounded-2xl border border-[var(--border)] bg-[var(--card)] text-[var(--card-foreground)] shadow-[0_22px_70px_rgba(0,0,0,0.18)]">
+ <div className="flex items-start justify-between gap-3 border-b border-[var(--border)] px-5 py-4">
+ <div className="min-w-0">
+ <div className="mb-1 inline-flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.14em] text-[var(--primary)]">
+ <HistoryIcon className="h-3 w-3" />
+ {t("Chat History Reference")}
</div>
- <div className="mt-1 text-[12px] text-slate-500 dark:text-slate-400">
+ <h2 className="text-lg font-semibold text-[var(--foreground)]">
+ {t("Select History Sessions")}
+ </h2>
+ <p className="mt-0.5 text-sm text-[var(--muted-foreground)]">
{t("Choose one or more past conversations to analyze before this turn.")}
- </div>
+ </p>
</div>
<button
onClick={onClose}
- className="rounded-lg p-2 text-slate-500 transition hover:bg-slate-100 hover:text-slate-700 dark:hover:bg-slate-800 dark:hover:text-slate-200"
+ className="rounded-lg p-2 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
+ aria-label={t("Close")}
>
<X size={18} />
</button>
</div>
- <div className="bg-slate-50/70 p-5 dark:bg-slate-950/40">
- <div className="mb-4 flex items-center gap-3">
+ <div className="bg-[var(--background)]/40 p-5">
+ <div className="mb-4 flex items-center gap-2">
<div className="relative flex-1">
- <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
+ <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-[var(--muted-foreground)]" />
<input
value={query}
onChange={(event) => setQuery(event.target.value)}
placeholder={t("Search sessions by title or last message")}
- className="w-full rounded-xl border border-slate-200 bg-white py-2.5 pl-9 pr-3 text-[13px] text-slate-900 outline-none transition focus:border-indigo-300 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-100"
+ className="w-full rounded-xl border border-[var(--border)] bg-[var(--card)] py-2.5 pl-9 pr-3 text-[13px] text-[var(--foreground)] outline-none transition focus:border-[var(--primary)]/50 focus:ring-2 focus:ring-[var(--primary)]/15"
/>
</div>
<button
onClick={() => setSelectedIds([])}
- className="rounded-xl border border-slate-200 bg-white px-3 py-2.5 text-[12px] font-medium text-slate-600 transition hover:bg-slate-100 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-300 dark:hover:bg-slate-800"
+ className="rounded-xl border border-[var(--border)] bg-[var(--card)] px-3 py-2.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
>
- Clear
+ {t("Clear")}
</button>
</div>
- <div className="max-h-[56vh] overflow-y-auto rounded-[18px] border border-slate-200 bg-white dark:border-slate-800 dark:bg-slate-900">
+ <div className="max-h-[56vh] overflow-y-auto rounded-2xl border border-[var(--border)] bg-[var(--card)]">
{loading ? (
<div className="flex min-h-[280px] items-center justify-center">
- <Loader2 className="h-5 w-5 animate-spin text-slate-400" />
+ <Loader2 className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" />
</div>
) : filteredSessions.length ? (
- <div className="divide-y divide-slate-200 dark:divide-slate-800">
+ <div className="divide-y divide-[var(--border)]">
{filteredSessions.map((session) => {
const id = session.session_id || session.id;
const selected = selectedIds.includes(id);
+ const timestamp = formatSessionTimestamp(
+ session.updated_at || session.created_at,
+ );
return (
<button
key={id}
onClick={() => toggleSession(session)}
- className="flex w-full items-start gap-3 px-4 py-3 text-left transition hover:bg-slate-50 dark:hover:bg-slate-800/60"
+ className={`flex w-full items-start gap-3 px-4 py-3 text-left transition-colors ${
+ selected
+ ? "bg-[var(--primary)]/8"
+ : "hover:bg-[var(--muted)]/40"
+ }`}
>
<div
- className={`mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-md border ${
+ className={`mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-md border transition-colors ${
selected
- ? "border-indigo-500 bg-indigo-500 text-white"
- : "border-slate-300 text-transparent dark:border-slate-600"
+ ? "border-[var(--primary)] bg-[var(--primary)] text-[var(--primary-foreground)]"
+ : "border-[var(--border)] text-transparent"
}`}
>
<Check size={12} />
</div>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
- <span className="inline-flex items-center gap-1 rounded-md bg-sky-100 px-2 py-0.5 text-[11px] font-medium text-sky-700 dark:bg-sky-900/30 dark:text-sky-300">
+ <span className="inline-flex items-center gap-1 rounded-md bg-[var(--muted)] px-2 py-0.5 text-[11px] font-medium text-[var(--muted-foreground)]">
<MessageSquare size={11} />
{t("History")}
</span>
- <span className="truncate text-[14px] font-medium text-slate-900 dark:text-slate-100">
- {session.title || "Untitled session"}
+ <span className="truncate text-[14px] font-medium text-[var(--foreground)]">
+ {session.title || t("Untitled session")}
</span>
</div>
{session.last_message ? (
- <p className="mt-1 line-clamp-2 text-[12px] leading-5 text-slate-500 dark:text-slate-400">
+ <p className="mt-1 line-clamp-2 text-[12px] leading-5 text-[var(--muted-foreground)]">
{session.last_message}
</p>
) : null}
- <div className="mt-2 flex items-center gap-3 text-[11px] text-slate-400 dark:text-slate-500">
- <span>{session.message_count ?? 0} messages</span>
- <span>{formatTimestamp(session.updated_at)}</span>
+ <div className="mt-2 flex items-center gap-3 text-[11px] text-[var(--muted-foreground)]/85">
+ <span>
+ {(session.message_count ?? 0)} {t("messages")}
+ </span>
+ {timestamp && <span>{timestamp}</span>}
</div>
</div>
</button>
@@ -175,22 +195,24 @@ export default function HistorySessionPicker({
})}
</div>
) : (
- <div className="px-6 py-14 text-center text-[13px] text-slate-500 dark:text-slate-400">
+ <div className="px-6 py-14 text-center text-[13px] text-[var(--muted-foreground)]">
{t("No matching sessions found.")}
</div>
)}
</div>
- <div className="mt-4 flex items-center justify-between">
- <div className="text-[12px] text-slate-500 dark:text-slate-400">
- {selectedIds.length} session{selectedIds.length === 1 ? "" : "s"} selected
+ <div className="mt-4 flex items-center justify-between gap-3">
+ <div className="text-[12px] text-[var(--muted-foreground)]">
+ {selectedIds.length === 1
+ ? t("1 session selected")
+ : t("{n} sessions selected", { n: selectedIds.length })}
</div>
<button
onClick={handleApply}
disabled={!selectedIds.length}
- className="rounded-xl bg-[var(--primary)] px-4 py-2.5 text-[13px] font-medium text-[var(--primary-foreground)] transition disabled:cursor-not-allowed disabled:opacity-40"
+ className="btn-primary rounded-xl bg-[var(--primary)] px-4 py-2.5 text-[13px] font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-40"
>
- Use Selected Sessions ({selectedIds.length})
+ {t("Use Selected Sessions ({n})", { n: selectedIds.length })}
</button>
</div>
</div>
diff --git a/web/components/chat/home/ChatComposer.tsx b/web/components/chat/home/ChatComposer.tsx
index e304cfb2a..e97ea5182 100644
--- a/web/components/chat/home/ChatComposer.tsx
+++ b/web/components/chat/home/ChatComposer.tsx
@@ -9,10 +9,11 @@ import {
BookOpen,
ChevronDown,
FilePlus2,
- Loader2,
+ Layers,
MessageSquare,
Paperclip,
Sparkles,
+ Square,
X,
type LucideIcon,
} from "lucide-react";
@@ -117,7 +118,7 @@ export default memo(function ChatComposer({
visualizeConfig,
researchConfig,
researchValidationErrors,
- researchPanelCollapsed,
+ panelCollapsed,
capabilities,
researchSources,
onSetCapMenuOpen,
@@ -138,12 +139,13 @@ export default memo(function ChatComposer({
onDrop,
onPaste,
onSelectCapability,
+ onCancelStreaming,
onChangeQuizConfig,
onUploadQuizPdf,
onChangeMathAnimatorConfig,
onChangeVisualizeConfig,
onChangeResearchConfig,
- onToggleResearchCollapsed,
+ onTogglePanelCollapsed,
}: {
composerRef: RefObject<HTMLDivElement | null>;
capMenuRef: RefObject<HTMLDivElement | null>;
@@ -179,7 +181,7 @@ export default memo(function ChatComposer({
visualizeConfig: VisualizeFormConfig;
researchConfig: DeepResearchFormConfig;
researchValidationErrors: Record<string, string>;
- researchPanelCollapsed: boolean;
+ panelCollapsed: boolean;
capabilities: CapabilityDef[];
researchSources: ResearchSourceDef[];
onSetCapMenuOpen: (open: boolean | ((prev: boolean) => boolean)) => void;
@@ -200,12 +202,13 @@ export default memo(function ChatComposer({
onDrop: (event: React.DragEvent) => void;
onPaste: (event: React.ClipboardEvent) => void;
onSelectCapability: (value: string) => void;
+ onCancelStreaming: () => void;
onChangeQuizConfig: (next: DeepQuestionFormConfig) => void;
onUploadQuizPdf: (file: File | null) => void;
onChangeMathAnimatorConfig: (next: MathAnimatorFormConfig) => void;
onChangeVisualizeConfig: (next: VisualizeFormConfig) => void;
onChangeResearchConfig: (next: DeepResearchFormConfig) => void;
- onToggleResearchCollapsed: () => void;
+ onTogglePanelCollapsed: () => void;
}) {
const { t } = useTranslation();
const CapIcon = activeCap.icon;
@@ -278,7 +281,7 @@ export default memo(function ChatComposer({
return (
<div
ref={composerRef}
- className={`relative z-20 mx-auto w-full shrink-0 pb-5 ${hasMessages ? "pt-4" : ""}`}
+ className={`relative z-20 mx-auto w-full shrink-0 pb-5 ${hasMessages ? "pt-1" : ""}`}
>
{hasMessages && (
<div className="pointer-events-none absolute inset-x-0 top-0 h-6 bg-gradient-to-b from-transparent to-[var(--background)]/72" />
@@ -429,24 +432,55 @@ export default memo(function ChatComposer({
<div className="flex min-w-0 flex-1 items-center gap-1">
{isResearchMode ? (
- researchSources.map((source) => {
- const active = researchConfig.sources.includes(source.name);
- const Icon = source.icon;
- return (
- <button
- key={source.name}
- onClick={() => onToggleResearchSource(source.name)}
- className={`inline-flex shrink-0 items-center gap-1 rounded-full border px-2 py-[3px] text-[10px] font-medium transition-all ${
- active
- ? "border-[var(--primary)]/25 bg-[var(--primary)]/8 text-[var(--primary)]"
- : "border-[var(--border)]/30 text-[var(--muted-foreground)]/60 hover:border-[var(--border)]/50 hover:text-[var(--foreground)]"
- }`}
+ <div className="relative flex items-center gap-0.5">
+ <button
+ ref={toolBtnRef}
+ onClick={() => onSetToolMenuOpen((v) => !v)}
+ className="inline-flex shrink-0 items-center gap-1 py-1 px-1.5 text-[11px] font-medium text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"
+ >
+ <Layers size={12} strokeWidth={1.7} />
+ {t("Sources")}
+ <ChevronDown size={10} className={`transition-transform ${toolMenuOpen ? "rotate-180" : ""}`} />
+ </button>
+ {researchConfig.sources.length > 0 && (
+ <div className="flex items-center gap-[3px] overflow-hidden">
+ {researchSources
+ .filter((rs) => researchConfig.sources.includes(rs.name))
+ .map((rs, i) => (
+ <span key={rs.name} className="shrink-0 text-[10px] text-[var(--muted-foreground)]/35">
+ {i > 0 && <span className="text-[12px] leading-none">·</span>}
+ {t(rs.label)}
+ </span>
+ ))}
+ </div>
+ )}
+ {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"
>
- <Icon size={11} strokeWidth={1.7} />
- {t(source.label)}
- </button>
- );
- })
+ {researchSources.map((source) => {
+ const active = researchConfig.sources.includes(source.name);
+ const Icon = source.icon;
+ return (
+ <button
+ key={source.name}
+ onClick={() => onToggleResearchSource(source.name)}
+ className={`flex w-full items-center gap-2.5 px-3 py-1.5 text-left text-[12px] transition-colors ${
+ active
+ ? "text-[var(--primary)]"
+ : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
+ } hover:bg-[var(--muted)]/40`}
+ >
+ <Icon size={13} strokeWidth={1.7} />
+ <span className="flex-1 font-medium">{t(source.label)}</span>
+ {active && <div className="h-1.5 w-1.5 rounded-full bg-[var(--primary)]" />}
+ </button>
+ );
+ })}
+ </div>
+ )}
+ </div>
) : visibleTools.length > 0 ? (
<div className="relative flex items-center gap-0.5">
<button
@@ -567,18 +601,38 @@ export default memo(function ChatComposer({
))}
</select>
- <button
- onClick={doSend}
- disabled={!canSend}
- className="rounded-full bg-[var(--primary)] p-[7px] text-white shadow-[0_4px_12px_rgba(195,90,44,0.15)] transition-[transform,opacity,box-shadow] hover:shadow-[0_6px_16px_rgba(195,90,44,0.22)] disabled:opacity-25 disabled:shadow-none"
- aria-label={t("Send")}
- >
- {isStreaming ? (
- <Loader2 size={15} className="animate-spin" />
- ) : (
+ {isStreaming ? (
+ <button
+ type="button"
+ onClick={onCancelStreaming}
+ className="group relative inline-flex h-[29px] w-[29px] shrink-0 items-center justify-center rounded-full bg-[var(--primary)] text-white shadow-[0_4px_12px_rgba(195,90,44,0.18)] transition-[background-color,box-shadow] hover:bg-[var(--primary)]/90 hover:shadow-[0_6px_16px_rgba(195,90,44,0.28)]"
+ aria-label={t("Stop generating")}
+ title={t("Stop generating")}
+ >
+ {/* A faint ring slowly rotates around the rim while
+ streaming, signalling "still working — click to
+ cancel". The white square sits front-and-center so
+ the click target is always obvious. */}
+ <span
+ className="pointer-events-none absolute inset-0 rounded-full border-[1.5px] border-white/30 border-t-white/85 animate-spin opacity-90 transition-opacity group-hover:opacity-40"
+ />
+ <Square
+ size={9}
+ strokeWidth={2.6}
+ className="relative z-10 fill-current"
+ />
+ </button>
+ ) : (
+ <button
+ type="button"
+ onClick={doSend}
+ disabled={!canSend}
+ className="rounded-full bg-[var(--primary)] p-[7px] text-white shadow-[0_4px_12px_rgba(195,90,44,0.15)] transition-[transform,opacity,box-shadow] hover:shadow-[0_6px_16px_rgba(195,90,44,0.22)] disabled:opacity-25 disabled:shadow-none"
+ aria-label={t("Send")}
+ >
<ArrowUp size={15} strokeWidth={2.5} />
- )}
- </button>
+ </button>
+ )}
</div>
</div>
</div>
@@ -591,24 +645,30 @@ export default memo(function ChatComposer({
onChange={onChangeQuizConfig}
uploadedPdf={quizPdf}
onUploadPdf={onUploadQuizPdf}
+ collapsed={panelCollapsed}
+ onToggleCollapsed={onTogglePanelCollapsed}
/>
) : isMathAnimatorMode ? (
<MathAnimatorConfigPanel
value={mathAnimatorConfig}
onChange={onChangeMathAnimatorConfig}
+ collapsed={panelCollapsed}
+ onToggleCollapsed={onTogglePanelCollapsed}
/>
) : isVisualizeMode ? (
<VisualizeConfigPanel
value={visualizeConfig}
onChange={onChangeVisualizeConfig}
+ collapsed={panelCollapsed}
+ onToggleCollapsed={onTogglePanelCollapsed}
/>
) : (
<ResearchConfigPanel
value={researchConfig}
errors={researchValidationErrors}
- collapsed={researchPanelCollapsed}
+ collapsed={panelCollapsed}
onChange={onChangeResearchConfig}
- onToggleCollapsed={onToggleResearchCollapsed}
+ onToggleCollapsed={onTogglePanelCollapsed}
/>
)}
</div>
diff --git a/web/components/chat/home/ChatMessages.tsx b/web/components/chat/home/ChatMessages.tsx
index 42dbbf020..ffa13de92 100644
--- a/web/components/chat/home/ChatMessages.tsx
+++ b/web/components/chat/home/ChatMessages.tsx
@@ -1,7 +1,7 @@
"use client";
import dynamic from "next/dynamic";
-import { memo, useMemo } from "react";
+import { memo, useCallback, useMemo, useState } from "react";
import Image from "next/image";
import {
BookOpen,
@@ -9,7 +9,6 @@ import {
Copy,
MessageSquare,
RotateCcw,
- Square,
X,
Zap,
type LucideIcon,
@@ -75,6 +74,7 @@ const AssistantMessage = memo(function AssistantMessage({
sessionId,
language,
onConfirmOutline,
+ onAnswerNow,
}: {
msg: { content: string; capability?: string; events?: StreamEvent[] };
isStreaming?: boolean;
@@ -82,6 +82,7 @@ const AssistantMessage = memo(function AssistantMessage({
sessionId?: string | null;
language?: string;
onConfirmOutline?: (outline: Array<{ title: string; overview: string }>, topic: string, researchConfig?: Record<string, unknown> | null) => void;
+ onAnswerNow?: () => void;
}) {
const events = useMemo(() => msg.events ?? [], [msg.events]);
const hasCallTrace = useMemo(
@@ -124,6 +125,7 @@ const AssistantMessage = memo(function AssistantMessage({
{hasCallTrace ? (
<CallTracePanel events={events} isStreaming={isStreaming} />
) : null}
+ {isStreaming && onAnswerNow ? <AnswerNowRow onAnswerNow={onAnswerNow} /> : null}
{outlinePreview && outlinePreview.sub_topics.length > 0 ? (
<ResearchOutlineEditor
outline={outlinePreview.sub_topics}
@@ -146,6 +148,53 @@ const AssistantMessage = memo(function AssistantMessage({
AssistantMessage.displayName = "AssistantMessage";
+/**
+ * Inline "Answer now" affordance shown alongside the active assistant turn.
+ * Lives outside the trace panel so it is visible as soon as the turn starts
+ * — i.e. even before any tool / reasoning trace has been emitted, which is
+ * the common case for the very first user message.
+ */
+const AnswerNowRow = memo(function AnswerNowRow({
+ onAnswerNow,
+}: {
+ onAnswerNow: () => void;
+}) {
+ const { t } = useTranslation();
+ // Local single-shot guard: once the user has fired "answer now" we lock
+ // the button so a second click can't queue a duplicate cancel + restart
+ // race against the in-flight synthesis turn. The next assistant turn
+ // mounts a fresh ``AnswerNowRow`` with its own state, so this naturally
+ // resets per turn without any external bookkeeping.
+ const [triggered, setTriggered] = useState(false);
+ const handleClick = useCallback(() => {
+ if (triggered) return;
+ setTriggered(true);
+ onAnswerNow();
+ }, [triggered, onAnswerNow]);
+
+ return (
+ <div className="mt-1.5 mb-3 flex items-center">
+ <button
+ type="button"
+ onClick={handleClick}
+ disabled={triggered}
+ title={t("Skip reasoning and answer now")}
+ aria-disabled={triggered}
+ className="group inline-flex items-center gap-1.5 rounded-md border border-[var(--border)]/60 bg-[var(--card)]/60 px-2.5 py-1 text-[11.5px] font-medium text-[var(--muted-foreground)] shadow-sm transition-colors hover:border-[var(--primary)]/40 hover:bg-[var(--primary)]/5 hover:text-[var(--primary)] disabled:cursor-not-allowed disabled:opacity-60 disabled:hover:border-[var(--border)]/60 disabled:hover:bg-[var(--card)]/60 disabled:hover:text-[var(--muted-foreground)]"
+ >
+ <Zap
+ size={12}
+ strokeWidth={1.8}
+ className="shrink-0 transition-colors group-hover:text-[var(--primary)] group-disabled:group-hover:text-[var(--muted-foreground)]"
+ />
+ <span>{triggered ? t("Answering…") : t("Answer now")}</span>
+ </button>
+ </div>
+ );
+});
+
+AnswerNowRow.displayName = "AnswerNowRow";
+
function CostFooter({ cost, tokens, calls }: { cost: number; tokens: number; calls: number }) {
const formatCost = (usd: number) => {
if (usd < 0.01) return `$${usd.toFixed(4)}`;
@@ -194,20 +243,9 @@ function RoughActionButton({
const UserMessage = memo(function UserMessage({
msg,
index,
- showInlineControls,
- onCancelStreaming,
- onAnswerNow,
- activeAssistantMessage,
}: {
msg: ChatMessageItem;
index: number;
- showInlineControls: boolean;
- onCancelStreaming: () => void;
- onAnswerNow: (
- snapshot?: MessageRequestSnapshot,
- assistantMsg?: { content: string; events?: StreamEvent[] },
- ) => void;
- activeAssistantMessage: ChatMessageItem | null;
}) {
const { t } = useTranslation();
if (msg.content.startsWith("[Quiz Performance]")) return null;
@@ -269,30 +307,6 @@ const UserMessage = memo(function UserMessage({
})()}
<div>{msg.content}</div>
</div>
- {showInlineControls ? (
- <div className="flex justify-end gap-2">
- <RoughActionButton
- icon={Square}
- label="Stop"
- onClick={onCancelStreaming}
- />
- <RoughActionButton
- icon={Zap}
- label="Answer now"
- onClick={() =>
- onAnswerNow(
- msg.requestSnapshot,
- activeAssistantMessage?.role === "assistant"
- ? {
- content: activeAssistantMessage.content,
- events: activeAssistantMessage.events,
- }
- : undefined,
- )
- }
- />
- </div>
- ) : null}
</div>
</div>
);
@@ -359,11 +373,8 @@ ReferenceChips.displayName = "ReferenceChips";
export const ChatMessageList = memo(function ChatMessageList({
messages,
isStreaming,
- activeUserIndex,
- activeAssistantMessage,
sessionId,
language,
- onCancelStreaming,
onAnswerNow,
onCopyAssistantMessage,
onRetryMessage,
@@ -371,11 +382,8 @@ export const ChatMessageList = memo(function ChatMessageList({
}: {
messages: ChatMessageItem[];
isStreaming: boolean;
- activeUserIndex: number;
- activeAssistantMessage: ChatMessageItem | null;
sessionId?: string | null;
language?: string;
- onCancelStreaming: () => void;
onAnswerNow: (
snapshot?: MessageRequestSnapshot,
assistantMsg?: { content: string; events?: StreamEvent[] },
@@ -412,39 +420,40 @@ export const ChatMessageList = memo(function ChatMessageList({
}, [messages, isStreaming]);
const messageRows = useMemo(() => {
- return messages.map((msg, index) => {
- if (msg.role === "user") {
- return { msg, pairedUserMessage: null as ChatMessageItem | null };
- }
- const pairedUserMessage =
- [...messages.slice(0, index)].reverse().find((previous) => previous.role === "user") ?? null;
- return { msg, pairedUserMessage };
- });
+ // System messages are backend grounding (e.g. quiz follow-up context) and
+ // must never be rendered as a chat bubble. Filter them out defensively in
+ // addition to the hydration-time filter in UnifiedChatContext.
+ return messages
+ .map((msg, index) => ({ msg, originalIndex: index }))
+ .filter(({ msg }) => msg.role !== "system")
+ .map(({ msg, originalIndex }) => {
+ if (msg.role === "user") {
+ return { msg, originalIndex, pairedUserMessage: null as ChatMessageItem | null };
+ }
+ const pairedUserMessage =
+ [...messages.slice(0, originalIndex)]
+ .reverse()
+ .find((previous) => previous.role === "user") ?? null;
+ return { msg, originalIndex, pairedUserMessage };
+ });
}, [messages]);
return (
<>
- {messageRows.map(({ msg, pairedUserMessage }, i) => {
+ {messageRows.map(({ msg, originalIndex, pairedUserMessage }) => {
+ const i = originalIndex;
if (msg.role === "user") {
- const showInlineControls =
- i === activeUserIndex &&
- (!msg.capability || msg.capability === "chat") &&
- Boolean(msg.requestSnapshot) &&
- activeAssistantMessage?.role === "assistant";
return (
<UserMessage
key={`${msg.role}-${i}`}
msg={msg}
index={i}
- showInlineControls={showInlineControls}
- onCancelStreaming={onCancelStreaming}
- onAnswerNow={onAnswerNow}
- activeAssistantMessage={activeAssistantMessage}
/>
);
}
- const msgDone = !isStreaming || i !== messages.length - 1;
+ const isActiveAssistant = isStreaming && i === messages.length - 1;
+ const msgDone = !isActiveAssistant;
const showActions =
msgDone && hasVisibleMarkdownContent(msg.content);
const showRetry =
@@ -452,6 +461,18 @@ export const ChatMessageList = memo(function ChatMessageList({
(!pairedUserMessage?.capability || pairedUserMessage?.capability === "chat") &&
Boolean(pairedUserMessage?.requestSnapshot);
+ // The "Answer now" affordance lives inside the trace panel for the
+ // currently-streaming assistant turn. We hand the panel a thin
+ // closure so it does not need to know about MessageRequestSnapshot.
+ const handleTraceAnswerNow =
+ isActiveAssistant && pairedUserMessage?.requestSnapshot
+ ? () =>
+ onAnswerNow(pairedUserMessage.requestSnapshot, {
+ content: msg.content,
+ events: msg.events,
+ })
+ : undefined;
+
const costSummary = (() => {
if (!msgDone) return null;
const resultEv = msg.events?.find((e) => e.type === "result");
@@ -466,11 +487,12 @@ export const ChatMessageList = memo(function ChatMessageList({
<div key={`${msg.role}-${i}`} className="w-full">
<AssistantMessage
msg={msg}
- isStreaming={isStreaming && i === messages.length - 1}
+ isStreaming={isActiveAssistant}
outlineStatus={outlineStatusByIndex.get(i)}
sessionId={sessionId}
language={language}
onConfirmOutline={onConfirmOutline}
+ onAnswerNow={handleTraceAnswerNow}
/>
{(showActions || costSummary) && (
<div className="mt-2 flex items-center">
diff --git a/web/components/chat/home/composer-field.tsx b/web/components/chat/home/composer-field.tsx
index 59521ba38..f01ca3b29 100644
--- a/web/components/chat/home/composer-field.tsx
+++ b/web/components/chat/home/composer-field.tsx
@@ -1,4 +1,6 @@
import type { ReactNode } from "react";
+import { ChevronDown } from "lucide-react";
+import { useTranslation } from "react-i18next";
export const INPUT_CLS =
"h-[30px] rounded-lg border border-[var(--border)]/30 bg-[var(--background)]/50 px-2.5 text-[12px] text-[var(--foreground)] outline-none transition-colors hover:border-[var(--border)]/50 focus:border-[var(--primary)]/35 placeholder:text-[var(--muted-foreground)]/40";
@@ -21,3 +23,48 @@ export function Field({
</label>
);
}
+
+/**
+ * Shared header used by every capability-specific config panel
+ * (Quiz / Math Animator / Visualize / Deep Research).
+ *
+ * The body is hidden when `collapsed` is true; a one-line summary is shown
+ * next to the chevron so the user can verify the current settings without
+ * expanding the panel.
+ */
+export function CollapsibleConfigSection({
+ collapsed,
+ summary,
+ onToggleCollapsed,
+ bodyClassName,
+ children,
+}: {
+ collapsed: boolean;
+ summary?: string;
+ onToggleCollapsed: () => void;
+ bodyClassName?: string;
+ children: ReactNode;
+}) {
+ const { t } = useTranslation();
+ return (
+ <div>
+ <button
+ type="button"
+ onClick={onToggleCollapsed}
+ className="flex w-full items-center gap-1.5 px-3.5 py-1.5 text-left transition-colors hover:opacity-80"
+ >
+ <ChevronDown
+ size={10}
+ className={`shrink-0 text-[var(--muted-foreground)]/40 transition-transform ${collapsed ? "-rotate-90" : ""}`}
+ />
+ <span className="text-[10px] font-medium text-[var(--muted-foreground)]/55">{t("Settings")}</span>
+ {collapsed && summary && (
+ <span className="min-w-0 truncate text-[10px] text-[var(--muted-foreground)]/30">— {summary}</span>
+ )}
+ </button>
+ {!collapsed && (
+ <div className={bodyClassName ?? "px-3.5 pb-2.5"}>{children}</div>
+ )}
+ </div>
+ );
+}
diff --git a/web/components/common/MarkdownRenderer.tsx b/web/components/common/MarkdownRenderer.tsx
index ca77d274f..3a5067f83 100644
--- a/web/components/common/MarkdownRenderer.tsx
+++ b/web/components/common/MarkdownRenderer.tsx
@@ -15,6 +15,12 @@ export interface MarkdownRendererProps {
enableCode?: boolean;
enableMermaid?: boolean;
allowHtml?: boolean;
+ /**
+ * When true, top-level block elements receive a `data-source-line` attribute
+ * pointing at their starting line in the original markdown source. Useful for
+ * editor/preview scroll synchronization.
+ */
+ trackSourceLines?: boolean;
}
function detectMathContent(content: string): boolean {
@@ -31,7 +37,10 @@ function detectCodeContent(content: string): boolean {
}
function detectMermaidContent(content: string): boolean {
- return /```mermaid/i.test(content);
+ // editor.md style ```flow / ```seq / ```sequence fences are converted to
+ // mermaid by processMarkdownContent, so they need to enable the mermaid path
+ // as well. Otherwise the converted blocks fall through to the code renderer.
+ return /```(?:mermaid|flow|seq|sequence)\b/i.test(content);
}
function detectHtmlContent(content: string): boolean {
@@ -46,6 +55,7 @@ export default function MarkdownRenderer({
enableCode,
enableMermaid,
allowHtml,
+ trackSourceLines,
}: MarkdownRendererProps) {
const resolvedEnableMath = enableMath ?? detectMathContent(content);
const resolvedEnableCode = enableCode ?? detectCodeContent(content);
@@ -53,7 +63,11 @@ export default function MarkdownRenderer({
const resolvedAllowHtml = allowHtml ?? detectHtmlContent(content);
const shouldUseRich =
variant !== "trace" &&
- (resolvedEnableMath || resolvedEnableCode || resolvedEnableMermaid || resolvedAllowHtml);
+ (trackSourceLines ||
+ resolvedEnableMath ||
+ resolvedEnableCode ||
+ resolvedEnableMermaid ||
+ resolvedAllowHtml);
if (!shouldUseRich) {
return <SimpleMarkdownRenderer content={content} className={className} variant={variant} />;
@@ -68,6 +82,7 @@ export default function MarkdownRenderer({
enableCode={resolvedEnableCode}
enableMermaid={resolvedEnableMermaid}
allowHtml={resolvedAllowHtml}
+ trackSourceLines={trackSourceLines}
/>
);
}
diff --git a/web/components/common/RichCodeBlock.tsx b/web/components/common/RichCodeBlock.tsx
index 09e91a25d..cd3e1e94d 100644
--- a/web/components/common/RichCodeBlock.tsx
+++ b/web/components/common/RichCodeBlock.tsx
@@ -6,6 +6,8 @@ import { oneDark } from "react-syntax-highlighter/dist/esm/styles/prism";
const MONOSPACE =
'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace';
+const PLAIN_LANGS = new Set(["", "text", "txt", "plain", "plaintext", "none"]);
+
export default function RichCodeBlock({
raw,
lang,
@@ -15,35 +17,54 @@ export default function RichCodeBlock({
lang: string;
className?: string;
}) {
+ const normalizedLang = (lang || "").toLowerCase();
+ const isPlain = PLAIN_LANGS.has(normalizedLang);
+
return (
<div
className={`md-code-block overflow-hidden rounded-xl border border-[var(--border)] bg-[#1f2937] ${
className || ""
}`}
>
- <div className="border-b border-white/10 px-3 py-2 text-[11px] font-medium uppercase tracking-wider text-[#9ca3af]">
- {lang}
- </div>
- <SyntaxHighlighter
- language={lang}
- style={oneDark}
- PreTag="pre"
- customStyle={{
- margin: 0,
- borderRadius: 0,
- background: "#1f2937",
- padding: "1rem",
- fontSize: "0.875rem",
- lineHeight: "1.7",
- }}
- codeTagProps={{
- className: "md-code-block__code",
- style: { fontFamily: MONOSPACE },
- }}
- wrapLongLines={false}
- >
- {raw}
- </SyntaxHighlighter>
+ {!isPlain ? (
+ <div className="border-b border-white/10 px-3 py-2 text-[11px] font-medium uppercase tracking-wider text-[#9ca3af]">
+ {normalizedLang}
+ </div>
+ ) : null}
+ {isPlain ? (
+ // Skip the highlighter entirely for unlabeled / plain blocks so we
+ // don't trigger Prism "unknown language" warnings and keep a tidy
+ // monospace presentation that matches the highlighted variant.
+ <pre
+ className="overflow-x-auto p-4 text-sm leading-[1.7] text-[#e5e7eb]"
+ style={{ margin: 0, fontFamily: MONOSPACE }}
+ >
+ <code className="md-code-block__code" style={{ fontFamily: MONOSPACE }}>
+ {raw}
+ </code>
+ </pre>
+ ) : (
+ <SyntaxHighlighter
+ language={normalizedLang}
+ style={oneDark}
+ PreTag="pre"
+ customStyle={{
+ margin: 0,
+ borderRadius: 0,
+ background: "#1f2937",
+ padding: "1rem",
+ fontSize: "0.875rem",
+ lineHeight: "1.7",
+ }}
+ codeTagProps={{
+ className: "md-code-block__code",
+ style: { fontFamily: MONOSPACE },
+ }}
+ wrapLongLines={false}
+ >
+ {raw}
+ </SyntaxHighlighter>
+ )}
</div>
);
}
diff --git a/web/components/common/RichMarkdownRenderer.tsx b/web/components/common/RichMarkdownRenderer.tsx
index 65abc3188..30d4ec790 100644
--- a/web/components/common/RichMarkdownRenderer.tsx
+++ b/web/components/common/RichMarkdownRenderer.tsx
@@ -87,6 +87,14 @@ function stripLeadingHashes(children: React.ReactNode): React.ReactNode {
return children;
}
+function sourceLineAttr(node: any): { "data-source-line"?: number } {
+ const line = node?.position?.start?.line;
+ if (typeof line === "number" && Number.isFinite(line)) {
+ return { "data-source-line": line };
+ }
+ return {};
+}
+
export default function RichMarkdownRenderer({
content,
className = "",
@@ -95,8 +103,18 @@ export default function RichMarkdownRenderer({
enableCode = false,
enableMermaid = false,
allowHtml = false,
+ trackSourceLines = false,
}: MarkdownRendererProps) {
- const normalizedContent = useMemo(() => normalizeMarkdownForDisplay(content), [content]);
+ // When `trackSourceLines` is on the consumer wants `data-source-line`
+ // attributes that map back to the *original* markdown lines (e.g. for
+ // editor/preview scroll sync). `normalizeMarkdownForDisplay` strips empty
+ // blocks, collapses runs of blank lines, etc, all of which shift line
+ // numbers and break that contract. In that mode we forward the raw text
+ // straight to react-markdown so AST positions stay faithful.
+ const normalizedContent = useMemo(
+ () => (trackSourceLines ? content : normalizeMarkdownForDisplay(content)),
+ [content, trackSourceLines],
+ );
const [plugins, setPlugins] = useState<PluginBundle>({});
const isTrace = variant === "trace";
const gap = isTrace ? "my-1" : variant === "compact" ? "my-2" : "my-4";
@@ -138,8 +156,16 @@ export default function RichMarkdownRenderer({
}, [allowHtml, enableMath]);
const processedContent = useMemo(() => {
+ // `processMarkdownContent` aggressively rewrites the source: it expands
+ // `[TOC]`, converts `flow`/`seq` fences into multi-line mermaid blocks,
+ // turns `\(...\)` / `\[...\]` into multi-line `$$...$$`, and collapses
+ // runs of blank lines. Every one of those transformations changes line
+ // numbers, which would invalidate the source line attributes we expose
+ // for scroll sync. So when `trackSourceLines` is on we render the raw
+ // markdown verbatim and rely on standard fences (` ```mermaid `, `$$`).
+ if (trackSourceLines) return normalizedContent;
return enableMath || enableMermaid ? processMarkdownContent(normalizedContent) : normalizedContent;
- }, [enableMath, enableMermaid, normalizedContent]);
+ }, [enableMath, enableMermaid, normalizedContent, trackSourceLines]);
const traceComponents: Record<string, React.ComponentType<any>> = {
p: ({ node, ...props }: any) => <p className="mb-1.5 last:mb-0" {...props} />,
@@ -206,6 +232,8 @@ export default function RichMarkdownRenderer({
hasRenderableChildren(children) ? <span>{children}</span> : null,
};
+ const lineAttr = (node: any) => (trackSourceLines ? sourceLineAttr(node) : {});
+
const headingComponents = {
h1: ({ node, children, className: headingClassName, ...props }: any) => {
const clean = stripLeadingHashes(children);
@@ -215,6 +243,7 @@ export default function RichMarkdownRenderer({
className={`scroll-mt-20 font-sans text-2xl font-bold tracking-tight ${textColor} ${
variant === "compact" ? "mt-5 mb-2" : "mt-8 mb-4"
} ${headingClassName || ""}`}
+ {...lineAttr(node)}
{...props}
>
{clean}
@@ -229,6 +258,7 @@ export default function RichMarkdownRenderer({
className={`scroll-mt-20 font-sans text-xl font-semibold tracking-tight ${textColor} ${
variant === "compact" ? "mt-4 mb-2" : "mt-7 mb-3"
} ${headingClassName || ""}`}
+ {...lineAttr(node)}
{...props}
>
{clean}
@@ -243,6 +273,7 @@ export default function RichMarkdownRenderer({
className={`scroll-mt-20 font-sans text-lg font-semibold tracking-tight ${textColor} ${
variant === "compact" ? "mt-4 mb-1.5" : "mt-6 mb-2.5"
} ${headingClassName || ""}`}
+ {...lineAttr(node)}
{...props}
>
{clean}
@@ -257,6 +288,7 @@ export default function RichMarkdownRenderer({
className={`scroll-mt-20 font-sans text-base font-semibold ${textColor} ${
variant === "compact" ? "mt-3 mb-1.5" : "mt-5 mb-2"
} ${headingClassName || ""}`}
+ {...lineAttr(node)}
{...props}
>
{clean}
@@ -271,6 +303,7 @@ export default function RichMarkdownRenderer({
className={`scroll-mt-20 font-sans text-sm font-semibold ${textColor} ${
variant === "compact" ? "mt-3 mb-1.5" : "mt-4 mb-2"
} ${headingClassName || ""}`}
+ {...lineAttr(node)}
{...props}
>
{clean}
@@ -285,6 +318,7 @@ export default function RichMarkdownRenderer({
className={`scroll-mt-20 font-sans text-sm font-semibold uppercase tracking-wide text-[var(--muted-foreground)] ${
variant === "compact" ? "mt-3 mb-1.5" : "mt-4 mb-2"
} ${headingClassName || ""}`}
+ {...lineAttr(node)}
{...props}
>
{clean}
@@ -295,9 +329,15 @@ export default function RichMarkdownRenderer({
const normalComponents: Record<string, React.ComponentType<any>> = {
...headingComponents,
+ p: ({ node, ...props }: any) => <p {...lineAttr(node)} {...props} />,
+ ul: ({ node, ...props }: any) => <ul {...lineAttr(node)} {...props} />,
+ ol: ({ node, ...props }: any) => <ol {...lineAttr(node)} {...props} />,
table: ({ node, children, ...props }: any) =>
hasRenderableChildren(children) ? (
- <div className={`overflow-x-auto rounded-lg border border-[var(--border)] shadow-sm ${gap}`}>
+ <div
+ className={`overflow-x-auto rounded-lg border border-[var(--border)] shadow-sm ${gap}`}
+ {...lineAttr(node)}
+ >
<table className="min-w-full divide-y divide-[var(--border)] text-sm" {...props}>
{children}
</table>
@@ -327,21 +367,39 @@ export default function RichMarkdownRenderer({
const raw = String(children).replace(/\n$/, "");
const langMatch = /language-([A-Za-z0-9_+#.-]+)/.exec(blockClassName || "");
const lang = langMatch?.[1]?.toLowerCase() || "";
+ const isMultiline = raw.includes("\n");
+ const lineProps = isMultiline ? lineAttr(node) : {};
if (lang === "mermaid" && enableMermaid) {
- return <LazyMermaid chart={raw} className={gap} />;
+ return (
+ <div {...lineProps}>
+ <LazyMermaid chart={raw} className={gap} />
+ </div>
+ );
+ }
+
+ // Route every multi-line block through the rich code block so the
+ // indented (no-language) variant still gets a polished, consistent
+ // theme instead of the washed-out fallback panel.
+ if (isMultiline && enableCode) {
+ return (
+ <div {...lineProps}>
+ <LazyCodeBlock raw={raw} lang={lang || "text"} className={gap} />
+ </div>
+ );
}
if (lang && enableCode) {
return <LazyCodeBlock raw={raw} lang={lang} className={gap} />;
}
- if (raw.includes("\n")) {
+ if (isMultiline) {
return (
<div
- className={`md-code-block ${gap} overflow-hidden rounded-xl border border-[var(--border)] bg-[#292524]`}
+ className={`md-code-block ${gap} overflow-hidden rounded-xl border border-[var(--border)] bg-[#1f2937]`}
+ {...lineProps}
>
- <pre className="overflow-x-auto p-4 text-sm leading-relaxed text-[#D6D3D1]">
+ <pre className="overflow-x-auto p-4 text-sm leading-relaxed text-[#e5e7eb]">
<code {...props}>{raw}</code>
</pre>
</div>
@@ -420,17 +478,19 @@ export default function RichMarkdownRenderer({
alt={alt || ""}
loading="lazy"
className={`${gap} inline-block max-w-full rounded-lg border border-[var(--border)]`}
+ {...lineAttr(node)}
{...props}
/>
),
blockquote: ({ node, ...props }: any) => (
<blockquote
className={`${gap} border-l-[3px] border-[var(--muted-foreground)] pl-4 italic text-[var(--muted-foreground)] [&>p]:mb-1`}
+ {...lineAttr(node)}
{...props}
/>
),
hr: ({ node, ...props }: any) => (
- <hr className={`${gap} h-px border-none bg-[var(--border)]`} {...props} />
+ <hr className={`${gap} h-px border-none bg-[var(--border)]`} {...lineAttr(node)} {...props} />
),
input: ({ node, type, checked, ...props }: any) =>
type === "checkbox" ? (
@@ -471,7 +531,7 @@ export default function RichMarkdownRenderer({
const components = useMemo(
() => (isTrace ? traceComponents : normalComponents),
// eslint-disable-next-line react-hooks/exhaustive-deps -- components only change with variant/feature flags
- [isTrace, variant, enableMermaid, enableCode],
+ [isTrace, variant, enableMermaid, enableCode, trackSourceLines],
);
const rootClasses = isTrace
diff --git a/web/components/math-animator/MathAnimatorConfigPanel.tsx b/web/components/math-animator/MathAnimatorConfigPanel.tsx
index ac190a263..11dae0be2 100644
--- a/web/components/math-animator/MathAnimatorConfigPanel.tsx
+++ b/web/components/math-animator/MathAnimatorConfigPanel.tsx
@@ -1,17 +1,28 @@
"use client";
import { useTranslation } from "react-i18next";
-import type { MathAnimatorFormConfig } from "@/lib/math-animator-types";
-import { Field, INPUT_CLS } from "@/components/chat/home/composer-field";
+import {
+ summarizeMathAnimatorConfig,
+ type MathAnimatorFormConfig,
+} from "@/lib/math-animator-types";
+import {
+ CollapsibleConfigSection,
+ Field,
+ INPUT_CLS,
+} from "@/components/chat/home/composer-field";
interface MathAnimatorConfigPanelProps {
value: MathAnimatorFormConfig;
onChange: (next: MathAnimatorFormConfig) => void;
+ collapsed: boolean;
+ onToggleCollapsed: () => void;
}
export default function MathAnimatorConfigPanel({
value,
onChange,
+ collapsed,
+ onToggleCollapsed,
}: MathAnimatorConfigPanelProps) {
const { t } = useTranslation();
const update = <K extends keyof MathAnimatorFormConfig>(
@@ -20,7 +31,12 @@ export default function MathAnimatorConfigPanel({
) => onChange({ ...value, [key]: val });
return (
- <div className="flex flex-wrap items-end gap-x-3 gap-y-2 px-3.5 py-2.5">
+ <CollapsibleConfigSection
+ collapsed={collapsed}
+ summary={summarizeMathAnimatorConfig(value)}
+ onToggleCollapsed={onToggleCollapsed}
+ bodyClassName="flex flex-wrap items-end gap-x-3 gap-y-2 px-3.5 pb-2.5"
+ >
<Field label="Output" width="w-[100px]">
<select
value={value.output_mode}
@@ -53,7 +69,7 @@ export default function MathAnimatorConfigPanel({
className={`${INPUT_CLS} w-full`}
/>
</Field>
- </div>
+ </CollapsibleConfigSection>
);
}
diff --git a/web/components/notebook/NotebookRecordPicker.tsx b/web/components/notebook/NotebookRecordPicker.tsx
index 4e2e715ef..f8e5dbb2e 100644
--- a/web/components/notebook/NotebookRecordPicker.tsx
+++ b/web/components/notebook/NotebookRecordPicker.tsx
@@ -1,7 +1,7 @@
"use client";
import { useEffect } from "react";
-import { X } from "lucide-react";
+import { Layers, X } from "lucide-react";
import { useTranslation } from "react-i18next";
import NotebookSelector from "@/app/(workspace)/guide/components/NotebookSelector";
import { useNotebookSelection } from "@/app/(workspace)/guide/hooks/useNotebookSelection";
@@ -44,25 +44,30 @@ export default function NotebookRecordPicker({
if (!open) return null;
return (
- <div className="fixed inset-0 z-[85] flex items-center justify-center bg-slate-950/55 p-4 backdrop-blur-md">
- <div className="w-full max-w-4xl overflow-hidden rounded-[22px] border border-slate-200 bg-white shadow-[0_22px_70px_rgba(15,23,42,0.24)] dark:border-slate-800 dark:bg-slate-900">
- <div className="flex items-center justify-between border-b border-slate-200 px-5 py-4 dark:border-slate-700">
- <div>
- <h2 className="text-lg font-semibold text-slate-900 dark:text-slate-100">
+ <div className="fixed inset-0 z-[85] flex items-center justify-center bg-[var(--background)]/65 p-4 backdrop-blur-md">
+ <div className="surface-card w-full max-w-4xl overflow-hidden rounded-2xl border border-[var(--border)] bg-[var(--card)] text-[var(--card-foreground)] shadow-[0_22px_70px_rgba(0,0,0,0.18)]">
+ <div className="flex items-start justify-between gap-3 border-b border-[var(--border)] px-5 py-4">
+ <div className="min-w-0">
+ <div className="mb-1 inline-flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.14em] text-[var(--primary)]">
+ <Layers className="h-3 w-3" />
+ {t("Notebook Reference")}
+ </div>
+ <h2 className="text-lg font-semibold text-[var(--foreground)]">
{t("Select Notebook Records")}
</h2>
- <p className="mt-1 text-sm text-slate-500 dark:text-slate-400">
+ <p className="mt-0.5 text-sm text-[var(--muted-foreground)]">
{t("Choose records across one or more notebooks to ground the next request.")}
</p>
</div>
<button
onClick={onClose}
- className="rounded-lg p-2 text-slate-500 transition hover:bg-slate-100 hover:text-slate-700 dark:hover:bg-slate-800 dark:hover:text-slate-200"
+ className="rounded-lg p-2 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
+ aria-label={t("Close")}
>
<X className="h-4 w-4" />
</button>
</div>
- <div className="bg-slate-50/70 p-5 dark:bg-slate-950/40">
+ <div className="bg-[var(--background)]/40 p-5">
<NotebookSelector
notebooks={notebooks}
expandedNotebooks={expandedNotebooks}
diff --git a/web/components/notebook/SaveToNotebookModal.tsx b/web/components/notebook/SaveToNotebookModal.tsx
index 9201cbd70..aa1b9b844 100644
--- a/web/components/notebook/SaveToNotebookModal.tsx
+++ b/web/components/notebook/SaveToNotebookModal.tsx
@@ -1,9 +1,13 @@
"use client";
import { useEffect, useMemo, useRef, useState } from "react";
-import { Loader2, X } from "lucide-react";
+import { Check, Loader2, MessageSquare, NotebookPen, Sparkles, User, X } from "lucide-react";
import { useTranslation } from "react-i18next";
import { apiUrl } from "@/lib/api";
+import {
+ listNotebooks,
+ type NotebookSummary as RealNotebookSummary,
+} from "@/lib/notebook-api";
type RecordType =
| "solve"
@@ -13,13 +17,6 @@ type RecordType =
| "chat"
| "guided_learning";
-interface NotebookSummary {
- id: string;
- name: string;
- color?: string;
- description?: string;
-}
-
export interface NotebookSavePayload {
recordType: RecordType;
title: string;
@@ -29,9 +26,23 @@ export interface NotebookSavePayload {
kbName?: string | null;
}
+export interface NotebookSaveMessage {
+ role: "user" | "assistant" | "system";
+ content: string;
+ capability?: string;
+}
+
interface SaveToNotebookModalProps {
open: boolean;
payload: NotebookSavePayload | null;
+ /**
+ * Optional list of chat messages. When provided, the modal switches to
+ * "selection mode" and lets the user pick which messages to include in the
+ * saved notebook record. The transcript / userQuery in the final request
+ * are rebuilt from the selected subset, while other fields (recordType,
+ * metadata, kbName) come from `payload`.
+ */
+ messages?: NotebookSaveMessage[] | null;
onClose: () => void;
onSaved?: (result: { summary: string }) => void;
}
@@ -56,43 +67,140 @@ function parseSseEvents(buffer: string): Array<{ payload: Record<string, unknown
return events;
}
+function roleLabelKey(role: NotebookSaveMessage["role"]): string {
+ if (role === "user") return "User";
+ if (role === "assistant") return "Assistant";
+ return "System";
+}
+
+function buildTranscript(messages: NotebookSaveMessage[]): string {
+ return messages
+ .map((msg) => {
+ const role = msg.role === "user" ? "User" : msg.role === "assistant" ? "Assistant" : "System";
+ return `## ${role}\n${msg.content}`;
+ })
+ .join("\n\n");
+}
+
+function buildUserQuery(messages: NotebookSaveMessage[]): string {
+ return messages
+ .filter((msg) => msg.role === "user")
+ .map((msg) => msg.content)
+ .join("\n\n");
+}
+
+function deriveTitle(messages: NotebookSaveMessage[], fallback: string): string {
+ const firstUser = messages.find((msg) => msg.role === "user");
+ const candidate = firstUser?.content.trim();
+ if (!candidate) return fallback;
+ return candidate.slice(0, 80);
+}
+
+/**
+ * Compute the indexes of the most recent N "turns". A turn is loosely
+ * defined as a user message plus any assistant/system messages that follow
+ * it until the next user message. When N exceeds the available turn count
+ * we just return all message indexes.
+ */
+function indexesForLastTurns(
+ messages: NotebookSaveMessage[],
+ turnCount: number,
+): number[] {
+ if (messages.length === 0 || turnCount <= 0) return [];
+ const userPositions: number[] = [];
+ messages.forEach((msg, idx) => {
+ if (msg.role === "user") userPositions.push(idx);
+ });
+ if (userPositions.length === 0) {
+ return messages.map((_, idx) => idx);
+ }
+ const startUserIdx = Math.max(0, userPositions.length - turnCount);
+ const startMessageIdx = userPositions[startUserIdx];
+ const result: number[] = [];
+ for (let i = startMessageIdx; i < messages.length; i += 1) result.push(i);
+ return result;
+}
+
export default function SaveToNotebookModal({
open,
payload,
+ messages,
onClose,
onSaved,
}: SaveToNotebookModalProps) {
const { t } = useTranslation();
- const [notebooks, setNotebooks] = useState<NotebookSummary[]>([]);
+ const [notebooks, setNotebooks] = useState<RealNotebookSummary[]>([]);
const [selectedIds, setSelectedIds] = useState<string[]>([]);
const [title, setTitle] = useState("");
+ const [titleEdited, setTitleEdited] = useState(false);
const [summaryPreview, setSummaryPreview] = useState("");
const [isLoading, setIsLoading] = useState(false);
+ const [isLoadingNotebooks, setIsLoadingNotebooks] = useState(false);
const [error, setError] = useState("");
+ const [selectedMessageIdx, setSelectedMessageIdx] = useState<Set<number>>(new Set());
const abortRef = useRef<AbortController | null>(null);
+ const hasMessageSelection = Array.isArray(messages) && messages.length > 0;
+
useEffect(() => {
if (!open) {
abortRef.current?.abort();
return;
}
- setTitle(payload?.title || "");
setSummaryPreview("");
setError("");
setSelectedIds([]);
+ setTitleEdited(false);
+ if (hasMessageSelection && messages) {
+ setSelectedMessageIdx(new Set(messages.map((_, idx) => idx)));
+ setTitle(deriveTitle(messages, payload?.title || ""));
+ } else {
+ setSelectedMessageIdx(new Set());
+ setTitle(payload?.title || "");
+ }
+ setIsLoadingNotebooks(true);
void (async () => {
try {
- const res = await fetch(apiUrl("/api/v1/notebook/list"), { cache: "no-store" });
- if (!res.ok) throw new Error("Failed to fetch notebooks");
- const data = (await res.json()) as {
- notebooks: Array<{ id: string; name: string; color?: string; description?: string }>;
- };
- setNotebooks(data.notebooks.map((nb) => ({ id: nb.id, name: nb.name, color: nb.color, description: nb.description })));
+ const list = await listNotebooks();
+ setNotebooks(list);
} catch {
setNotebooks([]);
+ } finally {
+ setIsLoadingNotebooks(false);
}
})();
- }, [open, payload]);
+ }, [open, payload, messages, hasMessageSelection]);
+
+ const orderedSelectedMessages = useMemo<NotebookSaveMessage[]>(() => {
+ if (!hasMessageSelection || !messages) return [];
+ const indexes = Array.from(selectedMessageIdx).sort((a, b) => a - b);
+ return indexes
+ .map((idx) => messages[idx])
+ .filter((msg): msg is NotebookSaveMessage => Boolean(msg));
+ }, [hasMessageSelection, messages, selectedMessageIdx]);
+
+ // When the user hasn't manually edited the title yet, keep it in sync
+ // with the first selected user message so it stays meaningful as the
+ // selection changes.
+ useEffect(() => {
+ if (!open || !hasMessageSelection || titleEdited) return;
+ const next = deriveTitle(orderedSelectedMessages, payload?.title || "");
+ setTitle(next);
+ }, [open, hasMessageSelection, titleEdited, orderedSelectedMessages, payload?.title]);
+
+ const effectiveOutput = useMemo(() => {
+ if (hasMessageSelection) {
+ return buildTranscript(orderedSelectedMessages);
+ }
+ return payload?.output || "";
+ }, [hasMessageSelection, orderedSelectedMessages, payload?.output]);
+
+ const effectiveUserQuery = useMemo(() => {
+ if (hasMessageSelection) {
+ return buildUserQuery(orderedSelectedMessages);
+ }
+ return payload?.userQuery || "";
+ }, [hasMessageSelection, orderedSelectedMessages, payload?.userQuery]);
const canSave = useMemo(
() =>
@@ -100,9 +208,17 @@ export default function SaveToNotebookModal({
payload &&
title.trim() &&
selectedIds.length > 0 &&
- payload.output.trim(),
+ effectiveOutput.trim() &&
+ (!hasMessageSelection || orderedSelectedMessages.length > 0),
),
- [payload, selectedIds.length, title],
+ [
+ payload,
+ title,
+ selectedIds.length,
+ effectiveOutput,
+ hasMessageSelection,
+ orderedSelectedMessages.length,
+ ],
);
const toggleNotebook = (id: string) => {
@@ -111,6 +227,32 @@ export default function SaveToNotebookModal({
);
};
+ const toggleMessage = (idx: number) => {
+ setSelectedMessageIdx((prev) => {
+ const next = new Set(prev);
+ if (next.has(idx)) {
+ next.delete(idx);
+ } else {
+ next.add(idx);
+ }
+ return next;
+ });
+ };
+
+ const selectAllMessages = () => {
+ if (!messages) return;
+ setSelectedMessageIdx(new Set(messages.map((_, idx) => idx)));
+ };
+
+ const clearMessages = () => {
+ setSelectedMessageIdx(new Set());
+ };
+
+ const selectLastTurns = (turnCount: number) => {
+ if (!messages) return;
+ setSelectedMessageIdx(new Set(indexesForLastTurns(messages, turnCount)));
+ };
+
const handleSave = async () => {
if (!payload || !canSave) return;
abortRef.current?.abort();
@@ -120,6 +262,15 @@ export default function SaveToNotebookModal({
setError("");
setSummaryPreview("");
+ const metadata: Record<string, unknown> = { ...(payload.metadata || {}) };
+ if (hasMessageSelection && messages) {
+ metadata.message_count = orderedSelectedMessages.length;
+ metadata.total_message_count = messages.length;
+ metadata.selected_message_indexes = Array.from(selectedMessageIdx).sort(
+ (a, b) => a - b,
+ );
+ }
+
try {
const response = await fetch(apiUrl("/api/v1/notebook/add_record_with_summary"), {
method: "POST",
@@ -128,9 +279,9 @@ export default function SaveToNotebookModal({
notebook_ids: selectedIds,
record_type: payload.recordType,
title: title.trim(),
- user_query: payload.userQuery,
- output: payload.output,
- metadata: payload.metadata || {},
+ user_query: effectiveUserQuery,
+ output: effectiveOutput,
+ metadata,
kb_name: payload.kbName || null,
}),
signal: controller.signal,
@@ -184,56 +335,171 @@ export default function SaveToNotebookModal({
if (!open || !payload) return null;
+ const totalMessages = messages?.length ?? 0;
+ const selectedMessageCount = selectedMessageIdx.size;
+ const allMessagesSelected = totalMessages > 0 && selectedMessageCount === totalMessages;
+
return (
- <div className="fixed inset-0 z-[80] flex items-center justify-center bg-slate-950/55 p-4 backdrop-blur-md">
- <div className="w-full max-w-2xl rounded-[22px] border border-slate-200 bg-white shadow-[0_22px_70px_rgba(15,23,42,0.24)] dark:border-slate-800 dark:bg-slate-900">
- <div className="flex items-center justify-between border-b border-slate-200 px-5 py-4 dark:border-slate-700">
- <div>
- <div className="mb-1 text-[11px] font-semibold uppercase tracking-[0.12em] text-indigo-500">
+ <div className="fixed inset-0 z-[80] flex items-center justify-center bg-[var(--background)]/65 p-4 backdrop-blur-md">
+ <div className="surface-card flex max-h-[90vh] w-full max-w-2xl flex-col overflow-hidden rounded-2xl border border-[var(--border)] bg-[var(--card)] text-[var(--card-foreground)] shadow-[0_22px_70px_rgba(0,0,0,0.18)]">
+ <div className="flex items-start justify-between gap-3 border-b border-[var(--border)] px-5 py-4">
+ <div className="min-w-0">
+ <div className="mb-1 text-[11px] font-semibold uppercase tracking-[0.14em] text-[var(--primary)]">
{t("Notebook Output")}
</div>
- <h2 className="text-lg font-semibold text-slate-900 dark:text-slate-100">
+ <h2 className="text-lg font-semibold text-[var(--foreground)]">
{t("Save to Notebook")}
</h2>
- <p className="text-sm text-slate-500 dark:text-slate-400">
- {t("Select one or more notebooks. A summary will be generated automatically.")}
+ <p className="mt-0.5 text-sm text-[var(--muted-foreground)]">
+ {hasMessageSelection
+ ? t(
+ "Choose which messages to include, pick one or more notebooks, and a summary will be generated automatically.",
+ )
+ : t("Select one or more notebooks. A summary will be generated automatically.")}
</p>
</div>
<button
onClick={onClose}
- className="rounded-lg p-2 text-slate-500 transition hover:bg-slate-100 hover:text-slate-700 dark:hover:bg-slate-800 dark:hover:text-slate-200"
+ className="rounded-lg p-2 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
+ aria-label={t("Close")}
>
<X className="h-4 w-4" />
</button>
</div>
- <div className="space-y-5 bg-slate-50/70 px-5 py-5 dark:bg-slate-950/35">
+ <div className="flex-1 space-y-5 overflow-y-auto bg-[var(--background)]/40 px-5 py-5">
<div>
- <label className="mb-2 block text-sm font-medium text-slate-700 dark:text-slate-200">
+ <label className="mb-2 block text-sm font-medium text-[var(--foreground)]">
{t("Title")}
</label>
<input
value={title}
- onChange={(e) => setTitle(e.target.value)}
- className="w-full rounded-xl border border-slate-200 bg-white px-4 py-2.5 text-sm outline-none focus:border-indigo-400 focus:ring-2 focus:ring-indigo-100 dark:border-slate-700 dark:bg-slate-950 dark:text-slate-100 dark:focus:ring-indigo-900/40"
+ onChange={(e) => {
+ setTitle(e.target.value);
+ setTitleEdited(true);
+ }}
+ className="w-full rounded-xl border border-[var(--border)] bg-[var(--card)] px-4 py-2.5 text-sm text-[var(--foreground)] outline-none transition focus:border-[var(--primary)]/60 focus:ring-2 focus:ring-[var(--primary)]/15"
/>
</div>
+ {hasMessageSelection && messages && (
+ <div>
+ <div className="mb-2 flex items-center justify-between gap-2">
+ <label className="block text-sm font-medium text-[var(--foreground)]">
+ {t("Messages to include")}
+ </label>
+ <span className="text-xs text-[var(--muted-foreground)]">
+ {t("{{selected}} of {{total}} selected", {
+ selected: selectedMessageCount,
+ total: totalMessages,
+ })}
+ </span>
+ </div>
+ <div className="mb-2 flex flex-wrap items-center gap-1.5">
+ <button
+ type="button"
+ onClick={selectAllMessages}
+ disabled={allMessagesSelected}
+ className="rounded-md border border-[var(--border)] bg-[var(--card)] px-2.5 py-1 text-[11px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--primary)]/40 hover:text-[var(--foreground)] disabled:cursor-not-allowed disabled:opacity-50"
+ >
+ {t("Select all")}
+ </button>
+ <button
+ type="button"
+ onClick={clearMessages}
+ disabled={selectedMessageCount === 0}
+ className="rounded-md border border-[var(--border)] bg-[var(--card)] px-2.5 py-1 text-[11px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--primary)]/40 hover:text-[var(--foreground)] disabled:cursor-not-allowed disabled:opacity-50"
+ >
+ {t("Clear")}
+ </button>
+ <button
+ type="button"
+ onClick={() => selectLastTurns(1)}
+ className="rounded-md border border-[var(--border)] bg-[var(--card)] px-2.5 py-1 text-[11px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--primary)]/40 hover:text-[var(--foreground)]"
+ >
+ {t("Last turn")}
+ </button>
+ <button
+ type="button"
+ onClick={() => selectLastTurns(3)}
+ className="rounded-md border border-[var(--border)] bg-[var(--card)] px-2.5 py-1 text-[11px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--primary)]/40 hover:text-[var(--foreground)]"
+ >
+ {t("Last 3 turns")}
+ </button>
+ </div>
+ <div className="max-h-72 space-y-1.5 overflow-y-auto rounded-xl border border-[var(--border)] bg-[var(--card)] p-2">
+ {messages.map((msg, idx) => {
+ const selected = selectedMessageIdx.has(idx);
+ const Icon = msg.role === "user" ? User : msg.role === "assistant" ? Sparkles : MessageSquare;
+ const preview = msg.content.replace(/\s+/g, " ").trim();
+ const empty = preview.length === 0;
+ return (
+ <button
+ key={idx}
+ type="button"
+ onClick={() => toggleMessage(idx)}
+ className={`flex w-full items-start gap-3 rounded-lg border px-3 py-2 text-left transition ${
+ selected
+ ? "border-[var(--primary)]/40 bg-[var(--primary)]/8"
+ : "border-transparent hover:border-[var(--border)] hover:bg-[var(--muted)]/40"
+ }`}
+ >
+ <span
+ className={`mt-0.5 flex h-[18px] w-[18px] shrink-0 items-center justify-center rounded-md border transition-colors ${
+ selected
+ ? "border-[var(--primary)] bg-[var(--primary)] text-[var(--primary-foreground)]"
+ : "border-[var(--border)] text-transparent"
+ }`}
+ >
+ <Check className="h-3 w-3" />
+ </span>
+ <div className="min-w-0 flex-1">
+ <div className="mb-0.5 flex items-center gap-1.5 text-[11px] font-medium text-[var(--muted-foreground)]">
+ <Icon className="h-3 w-3" />
+ <span>{t(roleLabelKey(msg.role))}</span>
+ <span className="text-[var(--muted-foreground)]/60">·</span>
+ <span>#{idx + 1}</span>
+ </div>
+ <p
+ className={`line-clamp-2 text-xs leading-5 ${
+ empty
+ ? "italic text-[var(--muted-foreground)]/70"
+ : "text-[var(--foreground)]/85"
+ }`}
+ >
+ {empty ? t("(empty message)") : preview}
+ </p>
+ </div>
+ </button>
+ );
+ })}
+ </div>
+ </div>
+ )}
+
<div>
<div className="mb-2 flex items-center justify-between">
- <label className="block text-sm font-medium text-slate-700 dark:text-slate-200">
+ <label className="block text-sm font-medium text-[var(--foreground)]">
{t("Notebooks")}
</label>
{selectedIds.length > 0 && (
- <span className="text-xs text-slate-500 dark:text-slate-400">
- {selectedIds.length} selected
+ <span className="text-xs text-[var(--muted-foreground)]">
+ {selectedIds.length} {t("selected")}
</span>
)}
</div>
- <div className="max-h-64 space-y-2 overflow-y-auto rounded-xl border border-slate-200 bg-white p-2 dark:border-slate-800 dark:bg-slate-900">
- {notebooks.length === 0 ? (
- <div className="px-3 py-6 text-center text-sm text-slate-400 dark:text-slate-500">
- {t("No notebooks found.")}
+ <div className="max-h-64 space-y-2 overflow-y-auto rounded-xl border border-[var(--border)] bg-[var(--card)] p-2">
+ {isLoadingNotebooks ? (
+ <div className="flex items-center justify-center px-3 py-8">
+ <Loader2 className="h-4 w-4 animate-spin text-[var(--muted-foreground)]" />
+ </div>
+ ) : notebooks.length === 0 ? (
+ <div className="flex flex-col items-center gap-2 px-3 py-6 text-center text-sm text-[var(--muted-foreground)]">
+ <NotebookPen className="h-5 w-5 text-[var(--muted-foreground)]/60" />
+ <span>{t("No notebooks found.")}</span>
+ <span className="text-[11px] text-[var(--muted-foreground)]/80">
+ {t("Create one from the Knowledge → Notebooks page.")}
+ </span>
</div>
) : (
notebooks.map((notebook) => {
@@ -244,23 +510,38 @@ export default function SaveToNotebookModal({
onClick={() => toggleNotebook(notebook.id)}
className={`flex w-full items-start gap-3 rounded-lg border px-3 py-2.5 text-left transition ${
selected
- ? "border-indigo-200 bg-indigo-50 dark:border-indigo-800 dark:bg-indigo-950/25"
- : "border-transparent hover:border-slate-200 hover:bg-slate-50 dark:hover:border-slate-700 dark:hover:bg-slate-800/70"
+ ? "border-[var(--primary)]/40 bg-[var(--primary)]/8"
+ : "border-transparent hover:border-[var(--border)] hover:bg-[var(--muted)]/40"
}`}
>
<div
- className="mt-1 h-3 w-3 rounded-full"
- style={{ backgroundColor: notebook.color || "#6366f1" }}
+ className="mt-1 h-3 w-3 shrink-0 rounded-full"
+ style={{ backgroundColor: notebook.color || "var(--primary)" }}
/>
<div className="min-w-0 flex-1">
- <div className="text-sm font-medium text-slate-800 dark:text-slate-100">
- {notebook.name}
+ <div className="flex items-center justify-between gap-2">
+ <div className="text-sm font-medium text-[var(--foreground)]">
+ {notebook.name}
+ </div>
+ <span
+ className={`flex h-4.5 w-4.5 shrink-0 items-center justify-center rounded-md border transition-colors ${
+ selected
+ ? "border-[var(--primary)] bg-[var(--primary)] text-[var(--primary-foreground)]"
+ : "border-[var(--border)] text-transparent"
+ }`}
+ style={{ width: 18, height: 18 }}
+ >
+ <Check className="h-3 w-3" />
+ </span>
</div>
{notebook.description && (
- <p className="mt-1 text-xs text-slate-500 dark:text-slate-400">
+ <p className="mt-1 line-clamp-2 text-xs text-[var(--muted-foreground)]">
{notebook.description}
</p>
)}
+ <div className="mt-1 text-[11px] text-[var(--muted-foreground)]/85">
+ {notebook.record_count ?? 0} {t("records")}
+ </div>
</div>
</button>
);
@@ -270,12 +551,12 @@ export default function SaveToNotebookModal({
</div>
<div>
- <div className="mb-2 text-sm font-medium text-slate-700 dark:text-slate-200">
+ <div className="mb-2 text-sm font-medium text-[var(--foreground)]">
{t("Summary preview")}
</div>
- <div className="min-h-24 rounded-xl border border-slate-200 bg-white px-4 py-3 text-sm text-slate-600 dark:border-slate-800 dark:bg-slate-900 dark:text-slate-300">
+ <div className="min-h-24 rounded-xl border border-[var(--border)] bg-[var(--card)] px-4 py-3 text-sm leading-6 text-[var(--foreground)]/85">
{summaryPreview || (
- <span className="text-slate-400 dark:text-slate-500">
+ <span className="text-[var(--muted-foreground)]">
{t("The generated summary will appear here during saving.")}
</span>
)}
@@ -283,23 +564,23 @@ export default function SaveToNotebookModal({
</div>
{error && (
- <div className="rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-600 dark:border-red-900/50 dark:bg-red-950/40 dark:text-red-300">
+ <div className="rounded-xl border border-[var(--destructive)]/30 bg-[var(--destructive)]/8 px-4 py-3 text-sm text-[var(--destructive)]">
{error}
</div>
)}
</div>
- <div className="flex items-center justify-end gap-3 border-t border-slate-200 px-5 py-4 dark:border-slate-700">
+ <div className="flex items-center justify-end gap-2 border-t border-[var(--border)] bg-[var(--card)] px-5 py-4">
<button
onClick={onClose}
- className="rounded-xl px-4 py-2 text-sm text-slate-600 transition hover:bg-slate-100 dark:text-slate-300 dark:hover:bg-slate-800"
+ className="rounded-xl px-4 py-2 text-sm text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
>
{t("Cancel")}
</button>
<button
onClick={handleSave}
disabled={!canSave || isLoading}
- className="inline-flex items-center gap-2 rounded-xl bg-gradient-to-r from-indigo-400 to-fuchsia-400 px-4 py-2 text-sm font-medium text-white transition hover:from-indigo-500 hover:to-fuchsia-500 disabled:cursor-not-allowed disabled:opacity-60"
+ className="btn-primary inline-flex items-center gap-2 rounded-xl bg-[var(--primary)] px-4 py-2 text-sm font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-50"
>
{isLoading && <Loader2 className="h-4 w-4 animate-spin" />}
{t("Save")}
diff --git a/web/components/quiz/QuizConfigPanel.tsx b/web/components/quiz/QuizConfigPanel.tsx
index 75178af6d..588a0b194 100644
--- a/web/components/quiz/QuizConfigPanel.tsx
+++ b/web/components/quiz/QuizConfigPanel.tsx
@@ -3,14 +3,24 @@
import { useRef, useState } from "react";
import { FileText, Upload, X } from "lucide-react";
import { useTranslation } from "react-i18next";
-import type { DeepQuestionFormConfig, DeepQuestionMode } from "@/lib/quiz-types";
-import { Field, INPUT_CLS } from "@/components/chat/home/composer-field";
+import {
+ summarizeQuizConfig,
+ type DeepQuestionFormConfig,
+ type DeepQuestionMode,
+} from "@/lib/quiz-types";
+import {
+ CollapsibleConfigSection,
+ Field,
+ INPUT_CLS,
+} from "@/components/chat/home/composer-field";
interface QuizConfigPanelProps {
value: DeepQuestionFormConfig;
onChange: (next: DeepQuestionFormConfig) => void;
uploadedPdf: File | null;
onUploadPdf: (file: File | null) => void;
+ collapsed: boolean;
+ onToggleCollapsed: () => void;
}
export default function QuizConfigPanel({
@@ -18,6 +28,8 @@ export default function QuizConfigPanel({
onChange,
uploadedPdf,
onUploadPdf,
+ collapsed,
+ onToggleCollapsed,
}: QuizConfigPanelProps) {
const { t } = useTranslation();
const fileRef = useRef<HTMLInputElement>(null);
@@ -31,7 +43,12 @@ export default function QuizConfigPanel({
const setMode = (m: DeepQuestionMode) => update("mode", m);
return (
- <div className="px-3.5 py-2.5 space-y-2.5">
+ <CollapsibleConfigSection
+ collapsed={collapsed}
+ summary={summarizeQuizConfig(value)}
+ onToggleCollapsed={onToggleCollapsed}
+ bodyClassName="px-3.5 pb-2.5 space-y-2.5"
+ >
<div className="inline-flex rounded-lg border border-[var(--border)]/25 p-0.5">
{(["custom", "mimic"] as const).map((m) => (
<button
@@ -185,7 +202,7 @@ export default function QuizConfigPanel({
</Field>
</div>
)}
- </div>
+ </CollapsibleConfigSection>
);
}
diff --git a/web/components/research/ResearchConfigPanel.tsx b/web/components/research/ResearchConfigPanel.tsx
index 2fbca3ba9..3ca3f957b 100644
--- a/web/components/research/ResearchConfigPanel.tsx
+++ b/web/components/research/ResearchConfigPanel.tsx
@@ -1,6 +1,5 @@
"use client";
-import { ChevronDown } from "lucide-react";
import { useTranslation } from "react-i18next";
import type {
DeepResearchFormConfig,
@@ -8,7 +7,11 @@ import type {
ResearchMode,
} from "@/lib/research-types";
import { summarizeResearchConfig } from "@/lib/research-types";
-import { Field, INPUT_CLS } from "@/components/chat/home/composer-field";
+import {
+ CollapsibleConfigSection,
+ Field,
+ INPUT_CLS,
+} from "@/components/chat/home/composer-field";
interface ResearchConfigPanelProps {
value: DeepResearchFormConfig;
@@ -77,77 +80,64 @@ export default function ResearchConfigPanel({
next: DeepResearchFormConfig[K],
) => onChange({ ...value, [key]: next });
- const summary = summarizeResearchConfig(value);
+ const rawSummary = summarizeResearchConfig(value);
+ const summary = rawSummary === "Incomplete settings" ? undefined : rawSummary;
return (
- <div>
- <button
- type="button"
- onClick={onToggleCollapsed}
- className="flex w-full items-center gap-1.5 px-3.5 py-1.5 text-left transition-colors hover:opacity-80"
- >
- <ChevronDown
- size={10}
- className={`shrink-0 text-[var(--muted-foreground)]/40 transition-transform ${collapsed ? "-rotate-90" : ""}`}
- />
- <span className="text-[10px] font-medium text-[var(--muted-foreground)]/55">{t("Settings")}</span>
- {collapsed && summary !== "Incomplete settings" && (
- <span className="min-w-0 truncate text-[10px] text-[var(--muted-foreground)]/30">— {summary}</span>
- )}
- </button>
-
- {!collapsed && (
- <div className="space-y-2 px-3.5 pb-2.5">
- <div className="flex flex-wrap items-end gap-x-3 gap-y-2">
- <Field label="Mode" width="min-w-[130px] flex-1">
- <select
- value={value.mode}
- onChange={(e) => update("mode", e.target.value as ResearchMode)}
- className={`${INPUT_CLS} w-full`}
- >
- <option value="">{t("Select...")}</option>
- {MODE_OPTIONS.map((option) => (
- <option key={option.value} value={option.value}>
- {option.label}
- </option>
- ))}
- </select>
- </Field>
- <Field label="Depth" width="min-w-[130px] flex-1">
- <select
- value={value.depth}
- onChange={(e) => update("depth", e.target.value as ResearchDepth)}
- className={`${INPUT_CLS} w-full`}
- >
- <option value="">{t("Select...")}</option>
- {DEPTH_OPTIONS.map((option) => (
- <option key={option.value} value={option.value}>
- {option.label}
- </option>
- ))}
- </select>
- </Field>
- </div>
- {value.depth === "manual" && (
- <div className="space-y-1.5 rounded-md bg-[var(--muted-foreground)]/5 px-3 py-2">
- <NumberSlider
- label="Sub-topics"
- value={value.manual_subtopics ?? 3}
- min={1}
- max={10}
- onChange={(n) => update("manual_subtopics", n)}
- />
- <NumberSlider
- label="Iterations"
- value={value.manual_max_iterations ?? 3}
- min={1}
- max={8}
- onChange={(n) => update("manual_max_iterations", n)}
- />
- </div>
- )}
+ <CollapsibleConfigSection
+ collapsed={collapsed}
+ summary={summary}
+ onToggleCollapsed={onToggleCollapsed}
+ bodyClassName="space-y-2 px-3.5 pb-2.5"
+ >
+ <div className="flex flex-wrap items-end gap-x-3 gap-y-2">
+ <Field label="Mode" width="min-w-[130px] flex-1">
+ <select
+ value={value.mode}
+ onChange={(e) => update("mode", e.target.value as ResearchMode)}
+ className={`${INPUT_CLS} w-full`}
+ >
+ <option value="">{t("Select...")}</option>
+ {MODE_OPTIONS.map((option) => (
+ <option key={option.value} value={option.value}>
+ {option.label}
+ </option>
+ ))}
+ </select>
+ </Field>
+ <Field label="Depth" width="min-w-[130px] flex-1">
+ <select
+ value={value.depth}
+ onChange={(e) => update("depth", e.target.value as ResearchDepth)}
+ className={`${INPUT_CLS} w-full`}
+ >
+ <option value="">{t("Select...")}</option>
+ {DEPTH_OPTIONS.map((option) => (
+ <option key={option.value} value={option.value}>
+ {option.label}
+ </option>
+ ))}
+ </select>
+ </Field>
+ </div>
+ {value.depth === "manual" && (
+ <div className="space-y-1.5 rounded-md bg-[var(--muted-foreground)]/5 px-3 py-2">
+ <NumberSlider
+ label="Sub-topics"
+ value={value.manual_subtopics ?? 3}
+ min={1}
+ max={10}
+ onChange={(n) => update("manual_subtopics", n)}
+ />
+ <NumberSlider
+ label="Iterations"
+ value={value.manual_max_iterations ?? 3}
+ min={1}
+ max={8}
+ onChange={(n) => update("manual_max_iterations", n)}
+ />
</div>
)}
- </div>
+ </CollapsibleConfigSection>
);
}
diff --git a/web/components/sidebar/SidebarShell.tsx b/web/components/sidebar/SidebarShell.tsx
index 9380f59be..c5e1b6083 100644
--- a/web/components/sidebar/SidebarShell.tsx
+++ b/web/components/sidebar/SidebarShell.tsx
@@ -149,10 +149,16 @@ export function SidebarShell({
return (
<aside className="flex w-[220px] h-screen shrink-0 flex-col bg-[var(--secondary)] transition-all duration-200">
{/* Header: logo + collapse toggle */}
- <div className="flex h-12 items-center justify-between px-4">
- <Link href="/" className="flex items-center gap-2">
- <Image src="/logo-ver2.png" alt="DeepTutor" width={20} height={20} />
- <span className="text-[15px] font-semibold tracking-tight text-[var(--foreground)]">
+ <div className="flex h-14 items-center justify-between px-4">
+ <Link href="/" className="group flex items-center gap-2">
+ <Image
+ src="/logo-ver2.png"
+ alt="DeepTutor"
+ width={22}
+ height={22}
+ className="transition-transform duration-200 group-hover:scale-105"
+ />
+ <span className="text-[16px] font-semibold leading-none tracking-[-0.02em] text-[var(--foreground)]">
DeepTutor
</span>
</Link>
diff --git a/web/components/visualize/VisualizeConfigPanel.tsx b/web/components/visualize/VisualizeConfigPanel.tsx
index 3a39ebff1..a57e4aa3a 100644
--- a/web/components/visualize/VisualizeConfigPanel.tsx
+++ b/web/components/visualize/VisualizeConfigPanel.tsx
@@ -1,22 +1,38 @@
"use client";
import { useTranslation } from "react-i18next";
-import type { VisualizeFormConfig } from "@/lib/visualize-types";
-import { Field, INPUT_CLS } from "@/components/chat/home/composer-field";
+import {
+ summarizeVisualizeConfig,
+ type VisualizeFormConfig,
+} from "@/lib/visualize-types";
+import {
+ CollapsibleConfigSection,
+ Field,
+ INPUT_CLS,
+} from "@/components/chat/home/composer-field";
interface VisualizeConfigPanelProps {
value: VisualizeFormConfig;
onChange: (next: VisualizeFormConfig) => void;
+ collapsed: boolean;
+ onToggleCollapsed: () => void;
}
export default function VisualizeConfigPanel({
value,
onChange,
+ collapsed,
+ onToggleCollapsed,
}: VisualizeConfigPanelProps) {
const { t } = useTranslation();
return (
- <div className="flex flex-wrap items-end gap-x-3 gap-y-2 px-3.5 py-2.5">
+ <CollapsibleConfigSection
+ collapsed={collapsed}
+ summary={summarizeVisualizeConfig(value)}
+ onToggleCollapsed={onToggleCollapsed}
+ bodyClassName="flex flex-wrap items-end gap-x-3 gap-y-2 px-3.5 pb-2.5"
+ >
<Field label="Render Mode" width="w-[120px]">
<select
value={value.render_mode}
@@ -31,6 +47,6 @@ export default function VisualizeConfigPanel({
<option value="mermaid">{t("Mermaid")}</option>
</select>
</Field>
- </div>
+ </CollapsibleConfigSection>
);
}
diff --git a/web/context/UnifiedChatContext.tsx b/web/context/UnifiedChatContext.tsx
index 559106c24..7046f13b6 100644
--- a/web/context/UnifiedChatContext.tsx
+++ b/web/context/UnifiedChatContext.tsx
@@ -433,24 +433,28 @@ export function UnifiedChatProvider({ children }: { children: React.ReactNode })
}, []);
const hydrateMessages = useCallback((messages: SessionMessage[]): MessageItem[] => {
- return messages.map((message) => ({
- role: message.role,
- content:
- message.role === "assistant"
- ? normalizeMarkdownForDisplay(message.content)
- : message.content,
- capability: message.capability || "",
- events: Array.isArray(message.events) ? message.events : [],
- attachments: Array.isArray(message.attachments)
- ? message.attachments.map((item) => ({
- type: item.type,
- filename: item.filename,
- base64: item.base64,
- url: item.url,
- mime_type: item.mime_type,
- }))
- : [],
- }));
+ // System messages (e.g. quiz follow-up grounding context written by the
+ // backend turn runtime) are LLM-only and must not surface in the chat UI.
+ return messages
+ .filter((message) => message.role !== "system")
+ .map((message) => ({
+ role: message.role,
+ content:
+ message.role === "assistant"
+ ? normalizeMarkdownForDisplay(message.content)
+ : message.content,
+ capability: message.capability || "",
+ events: Array.isArray(message.events) ? message.events : [],
+ attachments: Array.isArray(message.attachments)
+ ? message.attachments.map((item) => ({
+ type: item.type,
+ filename: item.filename,
+ base64: item.base64,
+ url: item.url,
+ mime_type: item.mime_type,
+ }))
+ : [],
+ }));
}, []);
const moveRunner = useCallback((oldKey: string, newKey: string) => {
diff --git a/web/lib/math-animator-types.ts b/web/lib/math-animator-types.ts
index 509718830..013453885 100644
--- a/web/lib/math-animator-types.ts
+++ b/web/lib/math-animator-types.ts
@@ -61,6 +61,19 @@ export function buildMathAnimatorWSConfig(
};
}
+function titleCase(value: string): string {
+ if (!value) return "";
+ return value.charAt(0).toUpperCase() + value.slice(1);
+}
+
+/**
+ * One-line summary of the math-animator form, shown next to the collapsed
+ * `Settings` chevron in the composer.
+ */
+export function summarizeMathAnimatorConfig(cfg: MathAnimatorFormConfig): string {
+ return [titleCase(cfg.output_mode), titleCase(cfg.quality)].join(" · ");
+}
+
export function extractMathAnimatorResult(
resultMetadata: Record<string, unknown> | undefined,
): MathAnimatorResult | null {
diff --git a/web/lib/notebook-api.ts b/web/lib/notebook-api.ts
index 966ae3000..0088a4a7a 100644
--- a/web/lib/notebook-api.ts
+++ b/web/lib/notebook-api.ts
@@ -1,5 +1,119 @@
import { apiUrl } from "@/lib/api";
+// ── Real notebook system (file-backed under data/user/workspace/notebook) ──
+//
+// Notebooks created in the Knowledge → Notebooks tab and consumed everywhere
+// chat output is saved (SaveToNotebookModal) or referenced
+// (NotebookRecordPicker) live in this system. They are distinct from the
+// "Question Notebook" categories below which only track quiz entries.
+
+export type NotebookRecordType =
+ | "solve"
+ | "question"
+ | "research"
+ | "co_writer"
+ | "chat"
+ | "guided_learning";
+
+export interface NotebookSummary {
+ id: string;
+ name: string;
+ description?: string;
+ color?: string;
+ icon?: string;
+ record_count?: number;
+ created_at?: number;
+ updated_at?: number;
+}
+
+export interface NotebookRecordItem {
+ id: string;
+ type: NotebookRecordType | string;
+ title: string;
+ summary?: string;
+ user_query: string;
+ output: string;
+ metadata?: Record<string, unknown>;
+ created_at?: number;
+ kb_name?: string | null;
+}
+
+export interface NotebookDetail extends NotebookSummary {
+ records: NotebookRecordItem[];
+}
+
+export async function listNotebooks(): Promise<NotebookSummary[]> {
+ const response = await fetch(apiUrl("/api/v1/notebook/list"), {
+ cache: "no-store",
+ });
+ if (!response.ok) throw new Error(`Request failed: ${response.status}`);
+ const data = (await response.json()) as { notebooks: NotebookSummary[] };
+ return data.notebooks ?? [];
+}
+
+export async function getNotebook(notebookId: string): Promise<NotebookDetail> {
+ const response = await fetch(apiUrl(`/api/v1/notebook/${notebookId}`), {
+ cache: "no-store",
+ });
+ if (!response.ok) throw new Error(`Request failed: ${response.status}`);
+ return (await response.json()) as NotebookDetail;
+}
+
+export async function createNotebook(payload: {
+ name: string;
+ description?: string;
+ color?: string;
+ icon?: string;
+}): Promise<NotebookSummary> {
+ const response = await fetch(apiUrl("/api/v1/notebook/create"), {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ name: payload.name,
+ description: payload.description ?? "",
+ color: payload.color ?? "#6366F1",
+ icon: payload.icon ?? "book",
+ }),
+ });
+ if (!response.ok) throw new Error(`Request failed: ${response.status}`);
+ const data = (await response.json()) as { notebook: NotebookSummary };
+ return data.notebook;
+}
+
+export async function updateNotebook(
+ notebookId: string,
+ payload: { name?: string; description?: string; color?: string; icon?: string },
+): Promise<NotebookSummary> {
+ const response = await fetch(apiUrl(`/api/v1/notebook/${notebookId}`), {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(payload),
+ });
+ if (!response.ok) throw new Error(`Request failed: ${response.status}`);
+ const data = (await response.json()) as { notebook: NotebookSummary };
+ return data.notebook;
+}
+
+export async function deleteNotebook(notebookId: string): Promise<void> {
+ const response = await fetch(apiUrl(`/api/v1/notebook/${notebookId}`), {
+ method: "DELETE",
+ });
+ if (!response.ok) throw new Error(`Request failed: ${response.status}`);
+}
+
+export async function deleteNotebookRecord(
+ notebookId: string,
+ recordId: string,
+): Promise<void> {
+ const response = await fetch(
+ apiUrl(`/api/v1/notebook/${notebookId}/records/${recordId}`),
+ { method: "DELETE" },
+ );
+ if (!response.ok) throw new Error(`Request failed: ${response.status}`);
+}
+
+// ── Question notebook (quiz entries + categories) ─────────────────
+
export interface NotebookEntry {
id: number;
session_id: string;
diff --git a/web/lib/quiz-types.ts b/web/lib/quiz-types.ts
index 24fc23e6f..e31bad212 100644
--- a/web/lib/quiz-types.ts
+++ b/web/lib/quiz-types.ts
@@ -118,6 +118,28 @@ export function buildQuizFollowupConfig(
};
}
+function titleCase(value: string): string {
+ if (!value) return "";
+ return value.charAt(0).toUpperCase() + value.slice(1);
+}
+
+/**
+ * One-line summary of the quiz form, shown next to the collapsed `Settings`
+ * chevron in the composer.
+ */
+export function summarizeQuizConfig(cfg: DeepQuestionFormConfig): string {
+ if (cfg.mode === "mimic") {
+ const target = cfg.paper_path.trim() || "no paper";
+ return ["Mimic", target, `max ${cfg.max_questions}`].join(" · ");
+ }
+ return [
+ "Custom",
+ `${cfg.num_questions}q`,
+ titleCase(cfg.difficulty || "auto"),
+ titleCase(cfg.question_type || "auto"),
+ ].join(" · ");
+}
+
/**
* Build the `config` payload to send over WebSocket for a quiz generation
* request.
diff --git a/web/lib/visualize-types.ts b/web/lib/visualize-types.ts
index 0a04fcd01..f7feab709 100644
--- a/web/lib/visualize-types.ts
+++ b/web/lib/visualize-types.ts
@@ -15,6 +15,21 @@ export function buildVisualizeWSConfig(
return { render_mode: cfg.render_mode };
}
+const VISUALIZE_RENDER_LABELS: Record<VisualizeRenderMode, string> = {
+ auto: "Auto",
+ chartjs: "Chart.js",
+ svg: "SVG",
+ mermaid: "Mermaid",
+};
+
+/**
+ * One-line summary of the visualize form, shown next to the collapsed
+ * `Settings` chevron in the composer.
+ */
+export function summarizeVisualizeConfig(cfg: VisualizeFormConfig): string {
+ return VISUALIZE_RENDER_LABELS[cfg.render_mode] ?? cfg.render_mode;
+}
+
export interface VisualizeResult {
response: string;
render_type: VisualizeRenderType;
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index 8659a9510..3d5086830 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -685,6 +685,11 @@
"Expand editor": "Expand editor",
"Expand preview": "Expand preview",
"Collapse preview": "Collapse preview",
+ "Resize editor and preview": "Resize editor and preview",
+ "Drag to resize, double-click to reset": "Drag to resize, double-click to reset",
+ "Sync Scroll": "Sync Scroll",
+ "Scroll sync is on. Click to disable.": "Scroll sync is on. Click to disable.",
+ "Scroll sync is off. Click to enable.": "Scroll sync is off. Click to enable.",
"Nothing to preview yet.": "Nothing to preview yet.",
"Tell AI what to do with the selection...": "Tell AI what to do with the selection...",
"Apply AI edit": "Apply AI edit",
@@ -753,6 +758,10 @@
"No TutorBots yet": "No TutorBots yet",
"Create your first TutorBot to get started.": "Create your first TutorBot to get started.",
"Stop": "Stop",
+ "Stop generating": "Stop generating",
+ "Answer now": "Answer now",
+ "Answering…": "Answering…",
+ "Skip reasoning and answer now": "Skip reasoning and answer now",
"Permanently delete \"{{name}}\" ({{id}})? This cannot be undone.": "Permanently delete \"{{name}}\" ({{id}})? This cannot be undone.",
"started {{time}}": "started {{time}}",
"No bots to configure": "No bots to configure",
@@ -829,8 +838,36 @@
"No notebooks found.": "No notebooks found.",
"Summary preview": "Summary preview",
"The generated summary will appear here during saving.": "The generated summary will appear here during saving.",
+ "Choose which messages to include, pick one or more notebooks, and a summary will be generated automatically.": "Choose which messages to include, pick one or more notebooks, and a summary will be generated automatically.",
+ "Messages to include": "Messages to include",
+ "{{selected}} of {{total}} selected": "{{selected}} of {{total}} selected",
+ "Select all": "Select all",
+ "Last turn": "Last turn",
+ "Last 3 turns": "Last 3 turns",
+ "(empty message)": "(empty message)",
+ "System": "System",
"Select Notebook Records": "Select Notebook Records",
"Choose records across one or more notebooks to ground the next request.": "Choose records across one or more notebooks to ground the next request.",
+ "Notebook Reference": "Notebook Reference",
+ "Chat History Reference": "Chat History Reference",
+ "Select History Sessions": "Select History Sessions",
+ "Choose one or more past conversations to analyze before this turn.": "Choose one or more past conversations to analyze before this turn.",
+ "Search sessions by title or last message": "Search sessions by title or last message",
+ "No matching sessions found.": "No matching sessions found.",
+ "Untitled session": "Untitled session",
+ "1 session selected": "1 session selected",
+ "{n} sessions selected": "{n} sessions selected",
+ "Use Selected Sessions ({n})": "Use Selected Sessions ({n})",
+ "Use Selected Records ({n})": "Use Selected Records ({n})",
+ "selected": "selected",
+ "Save a chat or guided learning result first to populate a notebook.": "Save a chat or guided learning result first to populate a notebook.",
+ "Create one from the Knowledge → Notebooks page.": "Create one from the Knowledge → Notebooks page.",
+ "Delete notebook \"{{name}}\"?": "Delete notebook \"{{name}}\"?",
+ "Deselect": "Deselect",
+ "No records": "No records",
+ "Ground the plan with saved notebook records.": "Ground the plan with saved notebook records.",
+ "Select records": "Select records",
+ "Update selection ({n})": "Update selection ({n})",
"Follow-up Chat": "Follow-up Chat",
"Ask anything about this question": "Ask anything about this question",
"Try: why this answer is correct, where your reasoning went wrong, or ask for a cleaner explanation.": "Try: why this answer is correct, where your reasoning went wrong, or ask for a cleaner explanation.",
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index 3c7683723..789ed5365 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -691,6 +691,10 @@
"No TutorBots yet": "暂无 TutorBot",
"Create your first TutorBot to get started.": "创建你的第一个 TutorBot 开始使用。",
"Stop": "停止",
+ "Stop generating": "停止生成",
+ "Answer now": "直接回答",
+ "Answering…": "正在回答…",
+ "Skip reasoning and answer now": "跳过推理,直接回答",
"Permanently delete \"{{name}}\" ({{id}})? This cannot be undone.": "永久删除「{{name}}」({{id}})?此操作不可撤销。",
"started {{time}}": "启动于 {{time}}",
"No bots to configure": "没有可配置的机器人",
@@ -726,6 +730,11 @@
"Expand editor": "展开编辑器",
"Expand preview": "展开预览",
"Collapse preview": "收起预览",
+ "Resize editor and preview": "调整编辑器与预览的比例",
+ "Drag to resize, double-click to reset": "拖动以调整大小,双击复位",
+ "Sync Scroll": "同步滚动",
+ "Scroll sync is on. Click to disable.": "滚动同步已开启,点击关闭",
+ "Scroll sync is off. Click to enable.": "滚动同步已关闭,点击开启",
"Nothing to preview yet.": "暂无内容可预览。",
"Tell AI what to do with the selection...": "告诉 AI 如何处理所选内容…",
"Apply AI edit": "应用 AI 编辑",
@@ -829,8 +838,36 @@
"No notebooks found.": "未找到笔记本。",
"Summary preview": "摘要预览",
"The generated summary will appear here during saving.": "保存时生成的摘要将显示在此处。",
+ "Choose which messages to include, pick one or more notebooks, and a summary will be generated automatically.": "选择要保存的消息以及一个或多个笔记本,系统将自动生成摘要。",
+ "Messages to include": "要包含的消息",
+ "{{selected}} of {{total}} selected": "已选 {{selected}} / {{total}}",
+ "Select all": "全选",
+ "Last turn": "最近一轮",
+ "Last 3 turns": "最近三轮",
+ "(empty message)": "(空消息)",
+ "System": "系统",
"Select Notebook Records": "选择笔记本记录",
"Choose records across one or more notebooks to ground the next request.": "从一个或多个笔记本中选择记录,作为下一轮请求的依据。",
+ "Notebook Reference": "笔记本引用",
+ "Chat History Reference": "聊天历史引用",
+ "Select History Sessions": "选择历史会话",
+ "Choose one or more past conversations to analyze before this turn.": "在本轮对话前,选择一个或多个历史会话作为参考。",
+ "Search sessions by title or last message": "按标题或最后一条消息搜索会话",
+ "No matching sessions found.": "未找到匹配的会话。",
+ "Untitled session": "未命名会话",
+ "1 session selected": "已选 1 个会话",
+ "{n} sessions selected": "已选 {n} 个会话",
+ "Use Selected Sessions ({n})": "使用所选会话({n})",
+ "Use Selected Records ({n})": "使用所选记录({n})",
+ "selected": "项已选",
+ "Save a chat or guided learning result first to populate a notebook.": "请先保存一次聊天或学习结果以填充笔记本。",
+ "Create one from the Knowledge → Notebooks page.": "可在“知识 → 笔记本”页面创建。",
+ "Delete notebook \"{{name}}\"?": "确定删除笔记本 “{{name}}” 吗?",
+ "Deselect": "取消选择",
+ "No records": "暂无记录",
+ "Ground the plan with saved notebook records.": "用已保存的笔记本记录作为学习计划的依据。",
+ "Select records": "选择记录",
+ "Update selection ({n})": "更新所选({n})",
"Follow-up Chat": "追问对话",
"Ask anything about this question": "关于此题可以问任何问题",
"Try: why this answer is correct, where your reasoning went wrong, or ask for a cleaner explanation.": "试试:为什么这个答案正确、你的推理哪里出错了、或要求更清晰的解释。",