Skip to content

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

improve chat

Bingxi Zhao (Frank)c54743bfb0b5
diff --git a/deeptutor/agents/chat/agentic_pipeline.py b/deeptutor/agents/chat/agentic_pipeline.py
index 93737c6ac..75ce8cccd 100644
--- a/deeptutor/agents/chat/agentic_pipeline.py
+++ b/deeptutor/agents/chat/agentic_pipeline.py
@@ -456,18 +456,11 @@ class AgenticChatPipeline:
max_iterations=max(1, self._max_iterations),
host=host,
usage=self._usage,
- # Reasoning models with native tool-calling support emit
- # ``reasoning_content`` without parroting back
- # ````THINK```` labels. When the model is a reasoner
- # AND native tool calling is active, use LABEL_FINISH so
- # that a reply containing ``reasoning_content`` + answer
- # text (but no explicit label) terminates the loop — the
- # answer lives in ``content``, reasoning in
- # ``reasoning_content``. Non-reasoning models that emit
- # ``<think/>`` tags get LABEL_THINK so the loop continues.
- implicit_think_label=LABEL_FINISH
- if (_is_reasoner and use_native_tools)
- else LABEL_THINK,
+ # Thinking traces are trace data, not loop-control actions.
+ # The formal content stream must still begin with FINISH /
+ # TOOL / THINK / PAUSE so protocol repair can catch missing
+ # labels instead of silently treating answers as THINK.
+ implicit_think_label=None,
)
if outcome.sources:
@@ -1248,32 +1241,33 @@ class AgenticChatPipeline:
Reasoning models (e.g. Qwen3.6-Plus) emit reasoning via
``reasoning_content`` and tool calls via native ``tool_calls``
- deltas. The label protocol (TOOL/THINK/FINISH/PAUSE) confuses
- them into writing tool-call JSON in ``content`` instead of using
- the native mechanism. This note tells them to ignore labels and
- use native tool calling directly.
+ deltas. The reasoning stream is displayed separately, but the
+ formal ``content`` stream still controls the agent loop through the
+ standard first-line label.
"""
if self.language == "zh":
note = (
"\n\n# 推理模型特别说明\n"
"你是一个原生支持推理和工具调用的模型。"
- "请**忽略上面「输出协议」中关于 ``TOOL``/``THINK``/``FINISH``/``PAUSE`` 标签的指示**。"
- "你不需要在回复中输出任何标签。"
- "你的推理过程会自动在独立区域显示。"
- "当你需要调用工具时,直接通过原生 tool_calls 功能发起调用,不要在文本中写 JSON。"
- "当你准备好给出最终答案时,直接在回复正文中写出答案即可。"
+ "你的推理过程会自动在独立的思考轨迹区域显示;"
+ "但正式回复正文仍然必须遵守上面的「输出协议」,第一行写且只写一个标签:"
+ "``FINISH``、``TOOL``、``THINK`` 或 ``PAUSE``。"
+ "需要调用工具时,正式正文第一行写 ``TOOL``,并在同一次回复里通过原生 tool_calls 发起调用;"
+ "不要把工具调用写成 JSON 文本。"
+ "准备给最终答案时,正式正文第一行写 ``FINISH``。"
)
else:
note = (
"\n\n# Reasoning Model Special Instructions\n"
"You are a model with native reasoning and tool-calling support. "
- "Please **ignore the 'Output Protocol' instructions above about "
- "``TOOL``/``THINK``/``FINISH``/``PAUSE`` labels**. "
- "You do NOT need to output any labels in your replies. "
- "Your reasoning is automatically displayed in a separate area. "
- "When you need to call a tool, use native tool_calls directly — "
- "do NOT write JSON in your text output. "
- "When you are ready to give the final answer, just write it in your reply body."
+ "Your reasoning is automatically displayed in a separate trace, "
+ "but your formal content stream must still follow the Output "
+ "Protocol above: the first line must be exactly one label, "
+ "``FINISH``, ``TOOL``, ``THINK``, or ``PAUSE``. "
+ "When you need a tool, put ``TOOL`` on the first line and emit "
+ "real native tool_calls in the same reply; do NOT write tool-call "
+ "JSON as text. When you are ready to answer, put ``FINISH`` on "
+ "the first line."
)
return system_prompt + note
diff --git a/deeptutor/api/routers/auth.py b/deeptutor/api/routers/auth.py
index 775399478..a03afd778 100644
--- a/deeptutor/api/routers/auth.py
+++ b/deeptutor/api/routers/auth.py
@@ -24,6 +24,8 @@ from deeptutor.services.config import load_auth_settings
_SECURE = bool(load_auth_settings()["cookie_secure"])
_SAMESITE = "none" if _SECURE else "lax"
+from deeptutor.multi_user.context import set_current_user, user_from_token_payload
+from deeptutor.multi_user.paths import local_admin_user
from deeptutor.services.auth import (
AUTH_ENABLED,
POCKETBASE_ENABLED,
@@ -157,6 +159,27 @@ def _extract_token(authorization: str | None, dt_token: str | None) -> str | Non
# ---------------------------------------------------------------------------
+def _install_current_user(payload: TokenPayload | None) -> _CtxToken:
+ """Install the request-local current-user ContextVar from an auth result.
+
+ Single point of truth for ``payload → CurrentUser`` so HTTP and WebSocket
+ entry points produce identical user objects. ``payload is None`` means
+ "no JWT was required" (AUTH_ENABLED=false) and resolves to the local
+ admin user; a non-None payload resolves through ``user_from_token_payload``.
+
+ Returns the ContextVar reset token. HTTP callers ignore it (the request
+ ends with the task, so the var is GC'd with the task context). WebSocket
+ callers keep it and call ``reset_current_user`` in their ``finally`` block,
+ because a WS connection outlives the dependency-resolution task.
+
+ ⚠ Invariant: every authenticated entry point MUST call this before the
+ handler runs. Skipping it leaves ``get_current_path_service()`` falling
+ back to the admin workspace — the silent-routing root cause of #481.
+ """
+ user = local_admin_user() if payload is None else user_from_token_payload(payload)
+ return set_current_user(user)
+
+
async def require_auth(
authorization: str | None = Header(default=None, alias="Authorization"),
dt_token: str | None = Cookie(default=None),
@@ -184,14 +207,10 @@ async def require_auth(
of #481.
"""
if not AUTH_ENABLED:
- from deeptutor.multi_user.context import set_current_user
- from deeptutor.multi_user.paths import local_admin_user
-
- set_current_user(local_admin_user())
+ _install_current_user(None)
return None
token = _extract_token(authorization, dt_token)
-
if not token:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
@@ -207,9 +226,7 @@ async def require_auth(
headers={"WWW-Authenticate": "Bearer"},
)
- from deeptutor.multi_user.context import set_current_user, user_from_token_payload
-
- set_current_user(user_from_token_payload(payload))
+ _install_current_user(payload)
return payload
@@ -241,12 +258,8 @@ async def ws_require_auth(ws: WebSocket) -> _CtxToken | _WsAuthFailed:
finally:
reset_current_user(user_token)
"""
- from deeptutor.multi_user.context import set_current_user, user_from_token_payload
- from deeptutor.multi_user.paths import local_admin_user
- from deeptutor.services.auth import AUTH_ENABLED, decode_token
-
if not AUTH_ENABLED:
- return set_current_user(local_admin_user())
+ return _install_current_user(None)
token = ws.query_params.get("token") or ws.cookies.get("dt_token")
payload = decode_token(token) if token else None
@@ -254,7 +267,7 @@ async def ws_require_auth(ws: WebSocket) -> _CtxToken | _WsAuthFailed:
await ws.close(code=4001)
return ws_auth_failed
- return set_current_user(user_from_token_payload(payload))
+ return _install_current_user(payload)
async def require_admin(
@@ -271,9 +284,7 @@ async def require_admin(
to the endpoint.
"""
if not AUTH_ENABLED:
- from deeptutor.services.auth import TokenPayload as TP
-
- return TP(username="local", role="admin", user_id="local-admin")
+ return _local_admin_token_payload()
if payload is None or payload.role != "admin":
raise HTTPException(
@@ -283,6 +294,23 @@ async def require_admin(
return payload
+def _local_admin_token_payload() -> TokenPayload:
+ """Synthetic admin payload used when AUTH_ENABLED=false.
+
+ Mirrors the local admin identity (LOCAL_ADMIN_USERNAME / LOCAL_ADMIN_ID)
+ so audit logs and self-reference checks behave the same as in multi-user
+ mode. Values are kept aligned with ``local_admin_user()`` in
+ ``deeptutor/multi_user/paths.py``.
+ """
+ from deeptutor.multi_user.models import LOCAL_ADMIN_ID, LOCAL_ADMIN_USERNAME
+
+ return TokenPayload(
+ username=LOCAL_ADMIN_USERNAME,
+ role="admin",
+ user_id=LOCAL_ADMIN_ID,
+ )
+
+
# ---------------------------------------------------------------------------
# Public endpoints (no auth required)
# ---------------------------------------------------------------------------
diff --git a/deeptutor/core/agentic/labeled_step.py b/deeptutor/core/agentic/labeled_step.py
index f3a65c5b8..b35b71858 100644
--- a/deeptutor/core/agentic/labeled_step.py
+++ b/deeptutor/core/agentic/labeled_step.py
@@ -11,9 +11,10 @@ client, optional tool schemas, and a label protocol, this:
post-label text and returns it to the caller; the caller decides whether
to emit it as body content (so a mixed ``FINISH+TOOL`` reply never leaks
prose into the answer area before the protocol is validated).
-* Accumulates ``tool_calls`` deltas. When ``tool_label`` is set and tool-call
- deltas arrive before the label resolves, force-resolves the label to that
- value (tool-call presence is authoritative).
+* Accumulates ``tool_calls`` deltas. Tool-call presence alone does not choose
+ the action label: the formal content stream must still begin with the
+ caller's tool label (e.g. ``TOOL``), otherwise the caller's protocol repair
+ path handles the missing label.
* When a reasoning model prepends a literal ``<think>...</think>`` block
*before* the protocol label, that prelude is detected and streamed live
into the reasoning sub-trace (same routing as the ``THINK`` label).
@@ -231,16 +232,10 @@ async def run_labeled_step(
behavior — its cards only open when there is actual reasoning text to
show, avoiding empty "Reasoning…" cards for direct FINISH replies.
- ``implicit_think_label`` lets a caller (e.g. chat) say "if a reasoning
- model emits ``<think>...</think>`` without following it with one of my
- protocol labels, treat the whole iteration as *this* label". The intent
- is to gracefully accept native-format reasoning models — they think in
- ``<think>`` blocks and may not parrot back the protocol's
- ``\`\`THINK\`\``` token. Without this, the loop would see a missing
- label and burn iterations on repair-retries. When the implicit
- resolution fires, the prelude markers are preserved in the returned
- ``text`` so the next iteration's assistant context still shows the
- model's reasoning verbatim.
+ ``implicit_think_label`` is kept for API compatibility with older
+ callers, but is intentionally ignored. Reasoning traces from
+ ``reasoning_content`` or inline ``<think>`` are trace data, not loop
+ actions; the formal content stream must still provide the protocol label.
"""
kwargs: dict[str, Any] = {
"model": model,
@@ -459,20 +454,10 @@ async def run_labeled_step(
return
if len(label_buf) > LABEL_PROBE_MAX_CHARS:
- # Probe window exhausted with no protocol label match. If
- # we previously consumed a ``<think>`` prelude AND the
- # caller opted into implicit-THINK semantics, treat this
- # iteration as an implicit ``THINK`` — the model is a
- # reasoning model speaking its native dialect. Otherwise
- # fall to ``LABEL_UNKNOWN`` so the caller can repair.
- if (
- saw_pre_label_think
- and implicit_think_label
- and implicit_think_label in allowed_labels
- ):
- label = implicit_think_label
- else:
- label = LABEL_UNKNOWN
+ # Probe window exhausted with no protocol label match.
+ # Reasoning traces are not action labels, so fall to
+ # ``LABEL_UNKNOWN`` and let the caller repair.
+ label = LABEL_UNKNOWN
flushed = label_buf
label_buf = ""
await _emit_text(flushed)
@@ -603,21 +588,6 @@ async def run_labeled_step(
fn_for_chars = getattr(tc_delta, "function", None)
output_chars_seen += len(str(getattr(fn_for_chars, "name", "") or ""))
output_chars_seen += len(str(getattr(fn_for_chars, "arguments", "") or ""))
- # Tool-call deltas are authoritative for the tool branch. If
- # we're still buffering a label when tool-call deltas arrive,
- # force-resolve to ``tool_label`` so the buffered prose
- # flushes into the reasoning sub-trace and subsequent prose
- # continues there.
- if label is None and tool_label:
- label = tool_label
- if in_prelude_think:
- # Close out the prelude before treating any buffered
- # prose as the tool branch's reasoning preamble.
- await _close_prelude_artificially()
- flushed = label_buf
- label_buf = ""
- if flushed:
- await _emit_text(flushed)
idx = getattr(tc_delta, "index", 0)
entry = tc_acc.setdefault(idx, {"id": "", "name": "", "arguments": ""})
if getattr(tc_delta, "id", None):
@@ -636,12 +606,9 @@ async def run_labeled_step(
# Stream ended while still buffering a label. Decide how to resolve:
#
- # - If we saw a ``<think>`` prelude and the caller opted into
- # implicit-THINK semantics, treat the iteration as an implicit
- # ``THINK`` so the loop continues (reasoning models that natively
- # speak ``<think>...</think>`` get accepted instead of treated as
- # protocol violators).
- # - Otherwise fall to ``LABEL_UNKNOWN`` and let the caller repair.
+ # - Reasoning traces (``reasoning_content`` or inline ``<think>``) are
+ # not action labels. If no formal content label appeared, fall to
+ # ``LABEL_UNKNOWN`` and let the caller repair.
if label is None:
if in_prelude_think:
# Stream ended mid-prelude — flush remaining reasoning live so
@@ -657,14 +624,7 @@ async def run_labeled_step(
label, after_label = final_parsed
label_buf = ""
await _emit_text(after_label)
- if (
- label is None
- and saw_pre_label_think
- and implicit_think_label
- and implicit_think_label in allowed_labels
- ):
- label = implicit_think_label
- elif label is None:
+ if label is None:
label = LABEL_UNKNOWN
if label_buf:
await _emit_text(label_buf)
@@ -692,16 +652,10 @@ async def run_labeled_step(
)
text = "".join(content_acc)
- # Preserve the literal ``<think>...</think>`` block when we resolved the
- # iteration implicitly as ``THINK`` — the next iteration's assistant
- # context should reflect the model's reasoning verbatim, not a stripped
- # empty draft. For all other resolutions, fall through to the standard
- # cleanup so downstream consumers (assistant messages, final-response
- # text) aren't polluted with the prelude markers.
- implicit_think_resolved = bool(
- saw_pre_label_think and implicit_think_label and label == implicit_think_label
- )
- if (binding or saw_pre_label_think) and not implicit_think_resolved:
+ # Reasoning traces have already been streamed into the trace channel; the
+ # returned formal text should not leak inline provider markers or private
+ # pre-label thinking.
+ if binding or saw_pre_label_think:
text = clean_thinking_tags(text, binding, model)
ordered_tool_calls = [tc_acc[k] for k in sorted(tc_acc.keys())]
ordered_tool_calls = [tc for tc in ordered_tool_calls if tc.get("name")]
diff --git a/tests/agents/chat/test_agentic_parallel_tools.py b/tests/agents/chat/test_agentic_parallel_tools.py
index ff70fb8c8..60857c2d0 100644
--- a/tests/agents/chat/test_agentic_parallel_tools.py
+++ b/tests/agents/chat/test_agentic_parallel_tools.py
@@ -30,9 +30,12 @@ async def _collect_bus_events(bus: StreamBus) -> tuple[list[StreamEvent], asynci
def _llm_chunk(
*,
content: str | None = None,
+ reasoning_content: str | None = None,
tool_calls: list[dict[str, Any]] | None = None,
) -> SimpleNamespace:
delta_fields: dict[str, Any] = {"content": content}
+ if reasoning_content is not None:
+ delta_fields["reasoning_content"] = reasoning_content
if tool_calls is not None:
delta_fields["tool_calls"] = [
SimpleNamespace(
@@ -909,6 +912,83 @@ async def test_run_does_not_finish_on_unlabeled_reply_after_ask_user(
)
+async def test_reasoning_trace_does_not_replace_formal_label(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Reasoning models may stream reasoning_content, but their formal
+ content still needs a first-line protocol label."""
+ monkeypatch.setattr(
+ "deeptutor.agents.chat.agentic_pipeline.get_llm_config",
+ lambda: SimpleNamespace(
+ binding="custom",
+ model="qwen3.6-plus",
+ api_key="k",
+ base_url="u",
+ api_version=None,
+ extra_headers={},
+ reasoning_effort=None,
+ ),
+ )
+
+ class _Registry:
+ def build_prompt_text(self, *_args, **_kwargs):
+ return "- ask_user: ask a clarifying question"
+
+ def build_openai_schemas(self, _enabled_tools):
+ return [
+ {
+ "type": "function",
+ "function": {
+ "name": "ask_user",
+ "description": "Ask user",
+ "parameters": {"type": "object", "properties": {}},
+ },
+ }
+ ]
+
+ client = _ScriptedChatClient(
+ [
+ [
+ _llm_chunk(reasoning_content="I can answer from existing context."),
+ _llm_chunk(content="This is an unlabeled final-looking draft."),
+ ],
+ [_llm_chunk(content="``FINISH``\nLabeled final answer.")],
+ ]
+ )
+
+ pipeline = AgenticChatPipeline(language="en")
+ pipeline.registry = _Registry()
+ monkeypatch.setattr(pipeline, "_compose_enabled_tools", lambda _context: ["ask_user"])
+ monkeypatch.setattr(pipeline, "_build_openai_client", lambda: client)
+
+ bus = StreamBus()
+ events, consumer = await _collect_bus_events(bus)
+ await pipeline.run(UnifiedContext(session_id="s1", user_message="Explain X"), bus)
+ await asyncio.sleep(0)
+ await bus.close()
+ await consumer
+
+ assert client.call_count == 2
+ system_prompt = client.calls[0]["messages"][0]["content"]
+ assert "must still follow the Output Protocol" in system_prompt
+ assert "ignore the 'Output Protocol'" not in system_prompt
+ assert "do NOT need to output any labels" not in system_prompt
+
+ thinking_events = [e.content for e in events if e.type == StreamEventType.THINKING]
+ assert any("I can answer from existing context." in text for text in thinking_events)
+ protocol_warnings = [
+ e
+ for e in events
+ if e.type == StreamEventType.PROGRESS
+ and e.metadata.get("protocol_violation") == "missing_label"
+ ]
+ assert protocol_warnings
+ result = [e for e in events if e.type == StreamEventType.RESULT][-1]
+ assert result.metadata["completed"] is True
+ assert result.metadata["response"] == "Labeled final answer."
+
+
@pytest.mark.asyncio
async def test_run_forces_finish_after_iteration_budget_ends_on_think(
monkeypatch: pytest.MonkeyPatch,
@@ -963,7 +1043,7 @@ async def test_run_repairs_multiple_labels_in_one_llm_reply(
)
client = _ScriptedChatClient(
[
- [_llm_chunk(content="``THINK``\nFirst thought.\n``TOOL``\nMaybe search.")],
+ [_llm_chunk(content="``THINK``\nFirst thought.\n``FINISH``\nMaybe search.")],
[_llm_chunk(content="``FINISH``\nClean final.")],
]
)
diff --git a/tests/api/test_auth_contextvar.py b/tests/api/test_auth_contextvar.py
index 9c1255ba2..30cae6c16 100644
--- a/tests/api/test_auth_contextvar.py
+++ b/tests/api/test_auth_contextvar.py
@@ -1,4 +1,4 @@
-"""Regression tests for #481.
+"""Regression tests for #481 and the auth-dep refactor.
When ``require_auth`` was declared as a sync ``def``, FastAPI dispatched it
through ``anyio.to_thread.run_sync``, which executes the function in a worker
@@ -7,10 +7,13 @@ that thread is discarded when the thread returns, so the endpoint reads the
unset default. The user-scoped path service then silently falls back to the
admin workspace and non-admin users hit 404 on every session request.
-These tests pin two invariants:
+These tests pin three invariants:
1. ``require_auth`` and ``require_admin`` are declared ``async``.
-2. With ``AUTH_ENABLED=true`` and a valid token, the user ContextVar set
+2. ``_install_current_user`` is the single point of truth for the
+ payload-to-CurrentUser mapping used by both HTTP and WebSocket entry
+ points (``None`` → local admin, payload → ``user_from_token_payload``).
+3. With ``AUTH_ENABLED=true`` and a valid token, the user ContextVar set
inside ``require_auth`` is visible from inside the endpoint, so
``get_path_service()`` resolves to the per-user workspace.
"""
@@ -35,6 +38,65 @@ def test_require_auth_is_async_def() -> None:
)
+def test_install_current_user_maps_none_to_local_admin() -> None:
+ """``_install_current_user(None)`` is the AUTH_ENABLED=false branch
+ for both HTTP and WS deps. It must install the local admin user so
+ that ``get_current_path_service()`` resolves to the admin workspace
+ rather than silently falling back through the None path."""
+ from deeptutor.api.routers.auth import _install_current_user
+ from deeptutor.multi_user.context import get_current_user_or_none, reset_current_user
+ from deeptutor.multi_user.models import LOCAL_ADMIN_ID, LOCAL_ADMIN_USERNAME
+
+ token = _install_current_user(None)
+ try:
+ user = get_current_user_or_none()
+ assert user is not None
+ assert user.id == LOCAL_ADMIN_ID
+ assert user.username == LOCAL_ADMIN_USERNAME
+ assert user.role == "admin"
+ assert user.scope.kind == "admin"
+ finally:
+ reset_current_user(token)
+
+
+def test_install_current_user_maps_payload_to_scoped_user() -> None:
+ """``_install_current_user(payload)`` must produce a user-scoped
+ CurrentUser whose workspace root lives under MULTI_USER_ROOT — the
+ same shape that ``ws_require_auth`` and HTTP deps need to install."""
+ from deeptutor.api.routers.auth import _install_current_user
+ from deeptutor.multi_user.context import get_current_user_or_none, reset_current_user
+ from deeptutor.services.auth import TokenPayload
+
+ token = _install_current_user(
+ TokenPayload(username="alice", role="user", user_id="u_alice")
+ )
+ try:
+ user = get_current_user_or_none()
+ assert user is not None
+ assert user.id == "u_alice"
+ assert user.username == "alice"
+ assert user.role == "user"
+ assert user.scope.kind == "user"
+ finally:
+ reset_current_user(token)
+
+
+def test_local_admin_token_payload_matches_local_admin_user() -> None:
+ """The synthetic admin TokenPayload returned by ``require_admin`` when
+ AUTH_ENABLED=false must use the same identity constants as
+ ``local_admin_user()`` — drift between the two reintroduces the kind
+ of dual-source-of-truth bug that #481 lived in."""
+ from deeptutor.api.routers.auth import _local_admin_token_payload
+ from deeptutor.multi_user.models import LOCAL_ADMIN_ID, LOCAL_ADMIN_USERNAME
+ from deeptutor.multi_user.paths import local_admin_user
+
+ tp = _local_admin_token_payload()
+ user = local_admin_user()
+ assert tp.username == LOCAL_ADMIN_USERNAME == user.username
+ assert tp.user_id == LOCAL_ADMIN_ID == user.id
+ assert tp.role == "admin" == user.role
+
+
def test_require_auth_propagates_user_contextvar_to_endpoint(monkeypatch) -> None:
"""End-to-end: a valid token through require_auth makes the user
ContextVar visible to the endpoint."""
@@ -129,6 +191,10 @@ def test_path_service_resolves_per_user_workspace_through_dependency(monkeypatch
assert resp.status_code == 200
chat_db = resp.json()["chat_db"]
- assert "multi-user/u_alice" in chat_db, (
- f"Per-user request should resolve to multi-user/<uid>/ workspace, got: {chat_db}"
+ expected_root = str((tmp_path / "multi-user" / "u_alice").resolve())
+ assert chat_db.startswith(expected_root), (
+ "Per-user request should resolve under the user's MULTI_USER_ROOT scope. "
+ f"Expected prefix {expected_root!r}, got: {chat_db!r}. If this fails, the "
+ "ContextVar mutation in require_auth is not reaching the endpoint — "
+ "see #481."
)
diff --git a/tests/core/test_labeled_step_think_prelude.py b/tests/core/test_labeled_step_think_prelude.py
index 25fe52d85..f28243c07 100644
--- a/tests/core/test_labeled_step_think_prelude.py
+++ b/tests/core/test_labeled_step_think_prelude.py
@@ -347,9 +347,9 @@ async def test_prelude_then_tool_call_routes_correctly() -> None:
@pytest.mark.asyncio
async def test_tool_calls_mid_prelude_close_prelude_synthetically() -> None:
- """If tool_call deltas arrive while still inside an open ``<think>``
- prelude, force-resolve to TOOL, flush remaining prelude content into
- the reasoning sub-trace, and ensure the returned text is clean."""
+ """Tool-call deltas without a formal ``TOOL`` label are not enough to
+ choose the action. The tool calls are still accumulated so the caller can
+ include them in diagnostics, but the step is a missing-label violation."""
events, result = await _run(
[
_chunk("<think>still reasoning"), # never closes
@@ -357,7 +357,7 @@ async def test_tool_calls_mid_prelude_close_prelude_synthetically() -> None:
],
)
- assert result.label == "TOOL"
+ assert result.label == "UNKNOWN"
assert result.tool_calls == [{"id": "call_a", "name": "lookup", "arguments": '{"k":1}'}]
# Even though </think> never arrived, the returned text must not leak
# the prelude content (clean_thinking_tags strips the synthesized block).
@@ -444,6 +444,40 @@ async def test_reasoning_content_field_streams_to_reasoning_subtrace() -> None:
assert "step 2 continues" in thinking_joined
+async def test_reasoning_content_does_not_imply_action_for_unlabeled_body() -> None:
+ """The dedicated reasoning stream is rendered as a trace, but the formal
+ content stream still needs a protocol label. Unlabeled body text is a
+ missing-label draft, not an implicit ``THINK`` or ``FINISH``."""
+ events, result = await _run(
+ [
+ _reasoning_chunk("private reasoning trace"),
+ _chunk("This reads like a final answer but has no label."),
+ ],
+ implicit_think_label="FINISH",
+ )
+
+ assert result.label == "UNKNOWN"
+ assert result.text == "This reads like a final answer but has no label."
+ assert "private reasoning trace" in "".join(_thinking_texts(events))
+
+
+async def test_tool_calls_without_tool_label_stay_unknown() -> None:
+ """Native tool calls are parsed, but they do not override the formal
+ first-line action protocol. The caller should repair the missing label."""
+ events, result = await _run(
+ [
+ _reasoning_chunk("I need a lookup"),
+ _tc_chunk(tc_id="call_1", name="search", arguments='{"q":"x"}'),
+ ]
+ )
+
+ assert result.label == "UNKNOWN"
+ assert result.tool_calls == [{"id": "call_1", "name": "search", "arguments": '{"q":"x"}'}]
+ assert "I need a lookup" in "".join(_thinking_texts(events))
+
+
@pytest.mark.asyncio
async def test_reasoning_content_then_inline_think_merge_into_same_subtrace() -> None:
"""Some providers emit *both* a ``reasoning_content`` stream AND inline
@@ -463,11 +497,10 @@ async def test_reasoning_content_then_inline_think_merge_into_same_subtrace() ->
@pytest.mark.asyncio
-async def test_implicit_think_resolves_when_prelude_has_no_protocol_label() -> None:
- """A reasoning model that emits ``<think>...</think>`` and *nothing else*
- that matches the protocol should be accepted as an implicit ``THINK``
- iteration when the caller opts in. Without this, the loop would treat
- the iteration as a protocol violation and burn budget on repair."""
+async def test_thinking_trace_without_protocol_label_stays_unknown() -> None:
+ """A reasoning trace is trace data, not an action label. Even when the
+ caller passes the legacy ``implicit_think_label`` argument, the formal
+ content must still provide ``THINK`` / ``FINISH`` / ``TOOL`` / ``PAUSE``."""
events, result = await _run(
[
_chunk("<think>I'm thinking about this carefully</think>"),
@@ -475,20 +508,15 @@ async def test_implicit_think_resolves_when_prelude_has_no_protocol_label() -> N
implicit_think_label="THINK",
)
- assert result.label == "THINK"
- # The full reasoning structure is preserved in the returned text so the
- # next iteration's assistant context shows the model's native dialect.
- assert "<think>" in result.text
- assert "I'm thinking about this carefully" in result.text
- assert "</think>" in result.text
+ assert result.label == "UNKNOWN"
+ assert result.text == ""
@pytest.mark.asyncio
-async def test_implicit_think_resolves_on_probe_overflow_with_unlabeled_tail() -> None:
- """If a reasoning model emits ``<think>...</think>`` followed by a long
- body that doesn't include a protocol label, the implicit-THINK opt-in
- should still resolve to ``THINK`` (rather than ``UNKNOWN``) so the loop
- can continue with the next iteration."""
+async def test_unlabeled_tail_after_thinking_trace_stays_unknown() -> None:
+ """A long formal body after a thinking trace still needs a first-line
+ protocol label. The parser preserves the draft text for repair context
+ but does not silently convert it to ``THINK``."""
long_unlabeled_tail = "x" * 200 # well past the 64-char probe window
events, result = await _run(
[
@@ -496,10 +524,9 @@ async def test_implicit_think_resolves_on_probe_overflow_with_unlabeled_tail() -
],
implicit_think_label="THINK",
)
- assert result.label == "THINK"
- # Both the prelude and the post-close trailing prose stay in text.
- assert "<think>" in result.text
- assert "some reasoning" in result.text
+ assert result.label == "UNKNOWN"
+ assert "<think>" not in result.text
+ assert "some reasoning" not in result.text
assert long_unlabeled_tail in result.text
diff --git a/web/app/globals.css b/web/app/globals.css
index ada7be33c..9cd70eb99 100644
--- a/web/app/globals.css
+++ b/web/app/globals.css
@@ -670,6 +670,29 @@
animation: session-pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
}
+/* Session avatar — gentle breathing wiggle when a session is running */
+@keyframes dt-session-icon-running {
+ 0%,
+ 100% {
+ transform: translateY(0) rotate(0deg) scale(1);
+ }
+ 25% {
+ transform: translateY(-0.6px) rotate(-6deg) scale(1.05);
+ }
+ 50% {
+ transform: translateY(0) rotate(0deg) scale(1.02);
+ }
+ 75% {
+ transform: translateY(0.6px) rotate(6deg) scale(1.05);
+ }
+}
+
+.dt-session-icon-running {
+ animation: dt-session-icon-running 1.6s cubic-bezier(0.45, 0.05, 0.55, 0.95)
+ infinite;
+ transform-origin: center;
+}
+
/* ----- Chat shell ↔ file preview drawer ---------------------------------
Squeezes the chat column when the drawer is open. The transition
timing here MUST match FilePreviewDrawer's transform transition so the
diff --git a/web/components/SessionList.tsx b/web/components/SessionList.tsx
index d26f457ab..6807c370b 100644
--- a/web/components/SessionList.tsx
+++ b/web/components/SessionList.tsx
@@ -5,6 +5,7 @@ import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { type SessionSummary } from "@/lib/session-api";
import { normalizeMessageContent, truncateText } from "@/lib/message-content";
+import { SessionAvatar } from "@/components/sidebar/SessionAvatar";
import {
formatRelativeTime,
getDayGroupKey,
@@ -29,23 +30,6 @@ interface SessionListProps {
onDelete: (sessionId: string) => void | Promise<void>;
}
-function statusColor(status?: SessionRuntimeStatus): string {
- switch (status) {
- case "running":
- return "bg-blue-500";
- case "completed":
- return "bg-emerald-400";
- case "failed":
- return "bg-rose-500";
- case "rejected":
- return "bg-fuchsia-500";
- case "cancelled":
- return "bg-amber-500";
- default:
- return "bg-[var(--muted-foreground)]/25";
- }
-}
-
function StatusIndicator({ status }: { status?: SessionRuntimeStatus }) {
if (!status || status === "idle") return null;
@@ -152,7 +136,7 @@ export default function SessionList({
if (loading) {
if (compact) {
return (
- <div className="ml-5 space-y-1.5 border-l border-[var(--border)]/30 py-1 pl-3">
+ <div className="space-y-1.5 px-2 py-1">
{[1, 2, 3].map((i) => (
<div
key={i}
@@ -175,7 +159,13 @@ export default function SessionList({
}
if (sessions.length === 0) {
- if (compact) return null;
+ if (compact) {
+ return (
+ <div className="px-3 py-4 text-center text-[11px] text-[var(--muted-foreground)]/70">
+ {t("No conversations yet")}
+ </div>
+ );
+ }
return (
<div className="px-3 py-4 text-center text-[11px] text-[var(--muted-foreground)]/70">
{t("No conversations yet")}
@@ -183,45 +173,39 @@ export default function SessionList({
);
}
- /* ---- Compact tree-line style (under Chat nav item) ---- */
+ /* ---- Compact sidebar style (standalone chat history region) ---- */
if (compact) {
return (
- <div className="ml-5 border-l border-[var(--border)]/30 py-1">
- {grouped.map(([key, items], groupIdx) => (
- <div key={key}>
- {groupIdx > 0 && (
- <div className="my-1 ml-3 mr-2 border-t border-[var(--border)]/20" />
- )}
- <div className="px-3 py-0.5 text-[10px] font-medium uppercase tracking-wider text-[var(--muted-foreground)]/40">
- {groupLabels[key]}
- </div>
- {items.map((session) => {
- const active = activeSessionId === session.session_id;
- const isEditing = editingId === session.session_id;
- return (
- <div
- key={session.session_id}
- onClick={() => void onSelect(session.session_id)}
- onKeyDown={(event) => {
- if (event.key === "Enter" || event.key === " ") {
- event.preventDefault();
- void onSelect(session.session_id);
+ <div className="py-0.5">
+ {sessions.map((session) => {
+ const active = activeSessionId === session.session_id;
+ const isEditing = editingId === session.session_id;
+ return (
+ <div
+ key={session.session_id}
+ onClick={() => void onSelect(session.session_id)}
+ onKeyDown={(event) => {
+ if (event.key === "Enter" || event.key === " ") {
+ event.preventDefault();
+ void onSelect(session.session_id);
+ }
+ }}
+ role="button"
+ tabIndex={0}
+ className={`group flex items-center gap-2 rounded-lg px-2.5 py-1.5 transition-colors ${
+ active
+ ? "bg-[var(--background)]/50 text-[var(--foreground)]"
+ : "text-[var(--muted-foreground)] hover:bg-[var(--background)]/40 hover:text-[var(--foreground)]"
+ }`}
+ >
+ <SessionAvatar
+ sessionId={session.session_id}
+ running={session.status === "running"}
+ className={
+ session.status === "running"
+ ? "text-blue-500"
+ : "opacity-70"
}
- }}
- role="button"
- tabIndex={0}
- className={`group flex items-center gap-2 rounded-r-lg py-1 pl-3 pr-2 transition-colors ${
- active
- ? "bg-[var(--background)]/50 text-[var(--foreground)]"
- : "text-[var(--muted-foreground)] hover:bg-[var(--background)]/40 hover:text-[var(--foreground)]"
- }`}
- >
- <span
- className={`block h-1.5 w-1.5 shrink-0 rounded-full ${
- active
- ? "bg-[var(--foreground)]/60"
- : statusColor(session.status)
- }`}
/>
{isEditing ? (
<input
@@ -290,8 +274,6 @@ export default function SessionList({
</div>
);
})}
- </div>
- ))}
</div>
);
}
diff --git a/web/components/sidebar/SessionAvatar.tsx b/web/components/sidebar/SessionAvatar.tsx
new file mode 100644
index 000000000..f2bc4824f
--- /dev/null
+++ b/web/components/sidebar/SessionAvatar.tsx
@@ -0,0 +1,86 @@
+"use client";
+
+import { createElement } from "react";
+import {
+ Cherry,
+ Cloud,
+ Compass,
+ Cookie,
+ Droplet,
+ Feather,
+ Flame,
+ Heart,
+ Leaf,
+ Lightbulb,
+ Moon,
+ Music,
+ Sparkles,
+ Sprout,
+ Star,
+ Sun,
+ type LucideIcon,
+} from "lucide-react";
+
+/**
+ * A curated set of minimalist, friendly icons. Each idle session is mapped
+ * deterministically to one of these so the sidebar feels varied without ever
+ * shuffling on re-render. Running sessions reuse the same assignment but add
+ * a gentle wiggle animation (see `.dt-session-icon-running` in globals.css).
+ */
+const ICONS: LucideIcon[] = [
+ Sparkles,
+ Sprout,
+ Leaf,
+ Feather,
+ Cloud,
+ Droplet,
+ Sun,
+ Moon,
+ Flame,
+ Star,
+ Heart,
+ Lightbulb,
+ Compass,
+ Cherry,
+ Cookie,
+ Music,
+];
+
+// Cheap, stable hash so a given session_id always maps to the same icon.
+function hashString(input: string): number {
+ let h = 2166136261;
+ for (let i = 0; i < input.length; i++) {
+ h ^= input.charCodeAt(i);
+ h = Math.imul(h, 16777619);
+ }
+ return h >>> 0;
+}
+
+export function pickSessionIcon(sessionId: string): LucideIcon {
+ if (!sessionId) return ICONS[0];
+ return ICONS[hashString(sessionId) % ICONS.length];
+}
+
+interface SessionAvatarProps {
+ sessionId: string;
+ running?: boolean;
+ size?: number;
+ className?: string;
+}
+
+export function SessionAvatar({
+ sessionId,
+ running = false,
+ size = 14,
+ className,
+}: SessionAvatarProps) {
+ // createElement avoids the static-components lint rule that mis-flags
+ // <Icon /> when Icon is a lookup into ICONS (stable per session_id).
+ return createElement(pickSessionIcon(sessionId), {
+ size,
+ strokeWidth: 1.6,
+ className: `shrink-0 ${running ? "dt-session-icon-running" : ""} ${
+ className ?? ""
+ }`,
+ });
+}
diff --git a/web/components/sidebar/SidebarShell.tsx b/web/components/sidebar/SidebarShell.tsx
index c83dbac69..ad90ced91 100644
--- a/web/components/sidebar/SidebarShell.tsx
+++ b/web/components/sidebar/SidebarShell.tsx
@@ -3,12 +3,14 @@
import Image from "next/image";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
-import { type ReactNode } from "react";
+import { useEffect, useState, type ReactNode } from "react";
import { useAppShell } from "@/context/AppShellContext";
import {
BookOpen,
Bot,
+ BookText,
Brain,
+ ChevronDown,
Github,
LayoutGrid,
Library,
@@ -16,13 +18,11 @@ import {
PanelLeftClose,
PanelLeftOpen,
PenLine,
- Plus,
Settings,
type LucideIcon,
} from "lucide-react";
import { useTranslation } from "react-i18next";
import SessionList from "@/components/SessionList";
-import { TutorBotRecent } from "@/components/sidebar/TutorBotRecent";
import { VersionBadge } from "@/components/sidebar/VersionBadge";
import type { SessionSummary } from "@/lib/session-api";
import { Tooltip } from "@/components/ui/Tooltip";
@@ -77,15 +77,16 @@ const PRIMARY_NAV: NavEntry[] = [
const SECONDARY_NAV: NavEntry[] = [
{ href: "/settings", label: "Settings", icon: Settings },
];
-const DEFAULT_SESSION_VIEWPORT_CLASS_NAME = "max-h-[112px]";
const GITHUB_REPO_URL = "https://github.com/HKUDS/DeepTutor";
+const DOCS_URL = "https://deeptutor.info/";
+const RECENTS_COLLAPSED_KEY = "deeptutor.sidebar.recentsCollapsed";
interface SidebarShellProps {
sessions?: SessionSummary[];
activeSessionId?: string | null;
loadingSessions?: boolean;
showSessions?: boolean;
- sessionViewportClassName?: string;
+ /** Clicking the Chat nav item resets to a fresh session via this handler. */
onNewChat?: () => void;
onSelectSession?: (sessionId: string) => void | Promise<void>;
onRenameSession?: (sessionId: string, title: string) => void | Promise<void>;
@@ -98,7 +99,6 @@ export function SidebarShell({
activeSessionId = null,
loadingSessions = false,
showSessions = false,
- sessionViewportClassName = DEFAULT_SESSION_VIEWPORT_CLASS_NAME,
onNewChat,
onSelectSession,
onRenameSession,
@@ -110,12 +110,35 @@ export function SidebarShell({
const { t } = useTranslation();
const { sidebarCollapsed: collapsed, setSidebarCollapsed: setCollapsed } =
useAppShell();
+ const [recentsCollapsed, setRecentsCollapsed] = useState(false);
- const handleNewChat = () => {
- if (onNewChat) {
- onNewChat();
+ // Hydrate Recents collapse from localStorage after first render to stay SSR-safe.
+ useEffect(() => {
+ if (typeof window === "undefined") return;
+ // eslint-disable-next-line react-hooks/set-state-in-effect
+ setRecentsCollapsed(
+ window.localStorage.getItem(RECENTS_COLLAPSED_KEY) === "1",
+ );
+ }, []);
+
+ const toggleRecents = () => {
+ setRecentsCollapsed((prev) => {
+ const next = !prev;
+ if (typeof window !== "undefined") {
+ window.localStorage.setItem(RECENTS_COLLAPSED_KEY, next ? "1" : "0");
+ }
+ return next;
+ });
+ };
+
+ const handleChatClick = (event: React.MouseEvent) => {
+ // Always reset to a fresh session (mirrors the old "New Chat" affordance);
+ // let modifier-clicks fall through to default Link behavior so middle-click
+ // open-in-new-tab still works.
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.button === 1)
return;
- }
+ event.preventDefault();
+ onNewChat?.();
router.push("/chat");
};
@@ -147,21 +170,8 @@ export function SidebarShell({
</button>
</div>
- {/* New chat — visually distinct circular button */}
- <button
- onClick={handleNewChat}
- title={t("New Chat") as string}
- className="mb-2 flex h-9 w-9 items-center justify-center rounded-xl border border-[var(--border)]/50 bg-[var(--background)]/40 text-[var(--foreground)] shadow-sm transition-all duration-150 hover:border-[var(--border)] hover:bg-[var(--background)]/80"
- aria-label={t("New Chat")}
- >
- <Plus size={16} strokeWidth={2.2} />
- </button>
-
- {/* Subtle divider */}
- <div className="my-1.5 h-px w-7 bg-[var(--border)]/40" />
-
{/* Primary nav */}
- <nav className="flex w-full flex-col items-center gap-1 px-1.5">
+ <nav className="mt-1 flex w-full flex-col items-center gap-1 px-1.5">
{PRIMARY_NAV.map((item) => {
const active = pathname.startsWith(item.href);
const description = item.tooltipKey
@@ -176,6 +186,9 @@ export function SidebarShell({
>
<Link
href={item.href}
+ onClick={
+ item.href === "/chat" ? handleChatClick : undefined
+ }
aria-label={t(item.label)}
className={`relative flex h-9 w-9 items-center justify-center rounded-xl transition-all duration-150 ${
active
@@ -219,13 +232,23 @@ export function SidebarShell({
);
})}
{footerSlot}
+ <a
+ href={DOCS_URL}
+ target="_blank"
+ rel="noreferrer noopener"
+ title={t("Docs") as string}
+ aria-label={t("Docs") as string}
+ className="mt-1 flex h-9 w-9 items-center justify-center rounded-xl text-[var(--muted-foreground)]/70 transition-colors hover:bg-[var(--background)]/50 hover:text-[var(--foreground)]"
+ >
+ <BookText size={15} strokeWidth={1.6} />
+ </a>
<a
href={GITHUB_REPO_URL}
target="_blank"
rel="noreferrer noopener"
title="GitHub"
aria-label="GitHub"
- className="mt-1 flex h-9 w-9 items-center justify-center rounded-xl text-[var(--muted-foreground)]/70 transition-colors hover:bg-[var(--background)]/50 hover:text-[var(--foreground)]"
+ className="flex h-9 w-9 items-center justify-center rounded-xl text-[var(--muted-foreground)]/70 transition-colors hover:bg-[var(--background)]/50 hover:text-[var(--foreground)]"
>
<Github size={15} strokeWidth={1.6} />
</a>
@@ -269,61 +292,83 @@ export function SidebarShell({
{/* Primary nav */}
<nav className="px-2 pt-1">
<div className="space-y-px">
- {/* New chat */}
- <button
- onClick={handleNewChat}
- className="flex w-full items-center gap-2.5 rounded-lg px-3 py-2 text-[13.5px] text-[var(--muted-foreground)] transition-colors hover:bg-[var(--background)]/60 hover:text-[var(--foreground)]"
- >
- <Plus size={16} strokeWidth={2} />
- <span>{t("New Chat")}</span>
- </button>
-
{PRIMARY_NAV.map((item) => {
const active = pathname.startsWith(item.href);
- const hasSessionsBelow =
- item.href === "/chat" &&
- showSessions &&
- onSelectSession &&
- onRenameSession &&
- onDeleteSession;
- const hasBots = item.href === "/agents";
return (
- <div key={item.href}>
- <Link
- href={item.href}
- className={`flex items-center gap-2.5 rounded-lg px-3 py-2 text-[13.5px] transition-colors ${
- active
- ? "bg-[var(--background)]/70 font-medium text-[var(--foreground)]"
- : "text-[var(--muted-foreground)] hover:bg-[var(--background)]/50 hover:text-[var(--foreground)]"
- }`}
- >
- <item.icon size={16} strokeWidth={active ? 1.9 : 1.5} />
- <span>{t(item.label)}</span>
- </Link>
- {hasSessionsBelow && (
- <div
- className={`${sessionViewportClassName} overflow-y-auto`}
- >
- <SessionList
- sessions={sessions}
- activeSessionId={activeSessionId}
- loading={loadingSessions}
- onSelect={onSelectSession}
- onRename={onRenameSession}
- onDelete={onDeleteSession}
- compact
- />
- </div>
- )}
- {hasBots && <TutorBotRecent />}
- </div>
+ <Link
+ key={item.href}
+ href={item.href}
+ onClick={
+ item.href === "/chat" ? handleChatClick : undefined
+ }
+ className={`flex items-center gap-2.5 rounded-lg px-3 py-2 text-[13.5px] transition-colors ${
+ active
+ ? "bg-[var(--background)]/70 font-medium text-[var(--foreground)]"
+ : "text-[var(--muted-foreground)] hover:bg-[var(--background)]/50 hover:text-[var(--foreground)]"
+ }`}
+ >
+ <item.icon size={16} strokeWidth={active ? 1.9 : 1.5} />
+ <span>{t(item.label)}</span>
+ </Link>
);
})}
</div>
</nav>
- {/* Spacer */}
- <div className="flex-1" />
+ {/* Chat history — its own region below the nav, takes remaining height */}
+ {showSessions &&
+ onSelectSession &&
+ onRenameSession &&
+ onDeleteSession ? (
+ <section
+ className={`mt-4 flex min-h-0 flex-col ${
+ recentsCollapsed ? "" : "flex-1"
+ }`}
+ >
+ <button
+ type="button"
+ onClick={toggleRecents}
+ className="group/recents mx-2 flex items-center justify-between rounded-md px-2 py-1 text-left text-[11.5px] font-normal text-[var(--muted-foreground)]/60 transition-colors hover:bg-[var(--background)]/40 hover:text-[var(--muted-foreground)]"
+ aria-expanded={!recentsCollapsed}
+ aria-label={
+ recentsCollapsed
+ ? (t("Show recents") as string)
+ : (t("Hide recents") as string)
+ }
+ >
+ <span>{t("Recents")}</span>
+ <ChevronDown
+ size={13}
+ strokeWidth={1.7}
+ className={`transition-all duration-200 ${
+ recentsCollapsed
+ ? "-rotate-90 opacity-60"
+ : "rotate-0 opacity-0 group-hover/recents:opacity-60"
+ }`}
+ />
+ </button>
+ {!recentsCollapsed && (
+ <div className="min-h-0 flex-1 overflow-y-auto px-2 pb-2 pt-0.5">
+ <SessionList
+ sessions={sessions}
+ activeSessionId={activeSessionId}
+ loading={loadingSessions}
+ onSelect={onSelectSession}
+ onRename={onRenameSession}
+ onDelete={onDeleteSession}
+ compact
+ />
+ </div>
+ )}
+ </section>
+ ) : null}
+
+ {/* When recents is collapsed or unavailable, fill the gap above the footer. */}
+ {(!showSessions ||
+ !onSelectSession ||
+ !onRenameSession ||
+ !onDeleteSession ||
+ recentsCollapsed) && <div className="flex-1" />}
{/* Secondary nav + footer */}
<div className="border-t border-[var(--border)]/40 px-2 py-2">
@@ -347,6 +392,16 @@ export function SidebarShell({
{footerSlot}
<div className="mt-0.5 flex items-center gap-0.5">
<VersionBadge />
+ <a
+ href={DOCS_URL}
+ target="_blank"
+ rel="noreferrer noopener"
+ title={t("Docs") as string}
+ aria-label={t("Docs") as string}
+ className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-[var(--muted-foreground)]/55 transition-colors hover:bg-[var(--background)]/50 hover:text-[var(--muted-foreground)]"
+ >
+ <BookText size={13} strokeWidth={1.7} />
+ </a>
<a
href={GITHUB_REPO_URL}
target="_blank"
diff --git a/web/components/sidebar/TutorBotRecent.tsx b/web/components/sidebar/TutorBotRecent.tsx
deleted file mode 100644
index 608e76393..000000000
--- a/web/components/sidebar/TutorBotRecent.tsx
+++ /dev/null
@@ -1,70 +0,0 @@
-"use client";
-
-import Link from "next/link";
-import { useEffect, useState } from "react";
-import { useTranslation } from "react-i18next";
-import { apiFetch, apiUrl } from "@/lib/api";
-import { formatRelativeTime } from "@/lib/relative-time";
-
-interface RecentBot {
- bot_id: string;
- name: string;
- running: boolean;
- last_message: string;
- updated_at: string;
-}
-
-export function TutorBotRecent({ collapsed = false }: { collapsed?: boolean }) {
- const { i18n } = useTranslation();
- const [bots, setBots] = useState<RecentBot[]>([]);
-
- useEffect(() => {
- let cancelled = false;
- (async () => {
- try {
- const res = await apiFetch(apiUrl("/api/v1/tutorbot/recent?limit=3"));
- if (!res.ok) return;
- const data = await res.json();
- if (!cancelled) setBots(data);
- } catch {
- /* ignore */
- }
- })();
- return () => {
- cancelled = true;
- };
- }, []);
-
- if (bots.length === 0) return null;
-
- if (collapsed) return null;
-
- return (
- <div className="ml-5 border-l border-[var(--border)]/30 py-1">
- {bots.map((bot) => (
- <Link
- key={bot.bot_id}
- href={`/agents/${bot.bot_id}/chat`}
- className="group flex items-center gap-2 rounded-r-lg py-1 pl-3 pr-2 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--background)]/40 hover:text-[var(--foreground)]"
- >
- <div className="relative shrink-0">
- {bot.running ? (
- <span className="block h-1.5 w-1.5 rounded-full bg-emerald-400" />
- ) : (
- <span className="block h-1.5 w-1.5 rounded-full bg-[var(--muted-foreground)]/25" />
- )}
- </div>
- <span className="min-w-0 flex-1 truncate text-[13px]">
- {bot.name}
- </span>
- <span className="shrink-0 text-[10px] tabular-nums text-[var(--muted-foreground)]/40">
- {formatRelativeTime(
- Math.floor(new Date(bot.updated_at).getTime() / 1000),
- i18n.language,
- )}
- </span>
- </Link>
- ))}
- </div>
- );
-}
diff --git a/web/components/sidebar/UtilitySidebar.tsx b/web/components/sidebar/UtilitySidebar.tsx
index 921c8083c..04256f29b 100644
--- a/web/components/sidebar/UtilitySidebar.tsx
+++ b/web/components/sidebar/UtilitySidebar.tsx
@@ -40,11 +40,6 @@ export default function UtilitySidebar() {
void refreshSessions();
}, [refreshSessions]);
- const handleNewChat = useCallback(() => {
- setActiveSessionId(null);
- router.push("/chat");
- }, [router, setActiveSessionId]);
-
const handleSelectSession = useCallback(
async (sessionId: string) => {
setActiveSessionId(sessionId);
@@ -91,7 +86,7 @@ export default function UtilitySidebar() {
sessions={sessions}
activeSessionId={activeSessionId}
loadingSessions={loadingSessions}
- onNewChat={handleNewChat}
+ onNewChat={() => setActiveSessionId(null)}
onSelectSession={handleSelectSession}
onRenameSession={handleRenameSession}
onDeleteSession={handleDeleteSession}
diff --git a/web/components/sidebar/WorkspaceSidebar.tsx b/web/components/sidebar/WorkspaceSidebar.tsx
index 393db9819..5a9ced44e 100644
--- a/web/components/sidebar/WorkspaceSidebar.tsx
+++ b/web/components/sidebar/WorkspaceSidebar.tsx
@@ -72,11 +72,6 @@ export default function WorkspaceSidebar() {
})
.map(({ session }) => session);
- const handleNewChat = () => {
- newSession();
- router.push("/chat");
- };
-
const handleSelectSession = useCallback(
async (sessionId: string) => {
router.push(`/chat/${sessionId}`);
@@ -123,7 +118,7 @@ export default function WorkspaceSidebar() {
sessions={orderedSessions}
activeSessionId={selectedSessionId}
loadingSessions={loadingSessions}
- onNewChat={handleNewChat}
+ onNewChat={newSession}
onSelectSession={handleSelectSession}
onRenameSession={handleRenameSession}
onDeleteSession={handleDeleteSession}
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index c6192bd2c..e5a7cfa61 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -350,6 +350,10 @@
"Generate Ideas ({n} items)": "Generate Ideas ({n} items)",
"Generate Ideas (Text Only)": "Generate Ideas (Text Only)",
"Chat History": "Chat History",
+ "Recents": "Recents",
+ "Show recents": "Show recents",
+ "Hide recents": "Hide recents",
+ "Docs": "Docs",
"Solver History": "Solver History",
"All Activities": "All Activities",
"Filter by type": "Filter by type",
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index 28f11e565..46c3338f3 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -350,6 +350,10 @@
"Generate Ideas ({n} items)": "生成创意({n} 条)",
"Generate Ideas (Text Only)": "生成创意(仅文字)",
"Chat History": "聊天历史",
+ "Recents": "最近",
+ "Show recents": "展开最近会话",
+ "Hide recents": "折叠最近会话",
+ "Docs": "文档",
"Solver History": "解题历史",
"All Activities": "所有活动",
"Filter by type": "按类型筛选",